I found an interesting problem on https://codeforces.com/problemset/problem/1185/C2:
The only difference between easy and hard versions is constraints.

If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.

A session has begun at Beland State University. Many students are taking exams.

Polygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following:  The $i$-th student randomly chooses a ticket.  if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.  if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home.

Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.

The duration of the whole exam for all students is $M$ minutes ($\max t_i \le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam.

For each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to pass the exam.

For each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home.

-----Input-----

The first line of the input contains two integers $n$ and $M$ ($1 \le n \le 2 \cdot 10^5$, $1 \le M \le 2 \cdot 10^7$) — the number of students and the total duration of the exam in minutes, respectively.

The second line of the input contains $n$ integers $t_i$ ($1 \le t_i \le 100$) — time in minutes that $i$-th student spends to answer to a ticket.

It's guaranteed that all values of $t_i$ are not greater than $M$.

-----Output-----

Print $n$ numbers: the $i$-th number must...

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

import math

nM=input().split(' ')
n = int(nM[0])
M = int(nM[1])

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

carr = [0 for i in range(100)]

carr[a[0]-1]+=1
print('0',end=' ')

sum=a[0]
for i in range(1,len(a)):
    failed=0
    if sum+a[i] > M:
        A = sum+a[i]
        for itr in range(100,0,-1):
            if A - carr[itr-1]*itr > M:
                A-=carr[itr-1]*itr
                failed+=carr[itr-1]
                # print(A,itr,failed)
            else:
                failed+=math.ceil((A-M)/itr)
                # print('vade',failed)
                break
        print(failed,end=' ')
    else:
        print(failed, end=' ')

    sum+=a[i]
    carr[a[i]-1]+=1


I found an interesting problem on https://codeforces.com/problemset/problem/1185/D:
A sequence $a_1, a_2, \dots, a_k$ is called an arithmetic progression if for each $i$ from $1$ to $k$ elements satisfy the condition $a_i = a_1 + c \cdot (i - 1)$ for some fixed $c$.

For example, these five sequences are arithmetic progressions: $[5, 7, 9, 11]$, $[101]$, $[101, 100, 99]$, $[13, 97]$ and $[5, 5, 5, 5, 5]$. And these four sequences aren't arithmetic progressions: $[3, 1, 2]$, $[1, 2, 4, 8]$, $[1, -1, 1, -1]$ and $[1, 2, 3, 3, 3]$.

You are given a sequence of integers $b_1, b_2, \dots, b_n$. Find any index $j$ ($1 \le j \le n$), such that if you delete $b_j$ from the sequence, you can reorder the remaining $n-1$ elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.

-----Input-----

The first line of the input contains one integer $n$ ($2 \le n \le 2\cdot10^5$) — length of the sequence $b$. The second line contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) — elements of the sequence $b$.

-----Output-----

Print such index $j$ ($1 \le j \le n$), so that if you delete the $j$-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.

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

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

Output
1
Input
4
1 2 4 8

Output
-1

-----Note-----

Note to the first example. If you delete the $4$-th element, you can get the arithmetic progression $[2, 4, 6, 8]$.

Note to the second example. The original sequence is already arithmetic progression, so you can delete $1$-st or last element and you will get an arithmetical progression again.

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

n = int(input())
b = list(map(int, input().split()))
b_ = []
for i, t in enumerate(b):
    b_.append([t, i+1])
b_.sort()

def solve(s):
    def check(a):
        if len(a) <= 1:
            return True
        delta = a[1] - a[0]
        for i in range(1, len(a) - 1):
            if a[i + 1] - a[i] != delta:
                return False
        return True

    if check([x[0] for x in s[1:]]):
        # print('a')
        return s[0][1]
    if check([x[0] for x in s[:-1]]):
        # print('b')
        return s[-1][1]
    if check([x[0] for x in s[:1] + s[2:]]):
        # print('c')
        return s[1][1]
    if check([x[0] for x in s[:-2] + s[-1:]]):
        # print('d')
        return s[-2][1]

    # mid
    t = []
    for i in range(len(s) - 1):
        t.append(s[i+1][0] - s[i][0])
    # print(t)

    i = 0
    while t[i] == t[0]:
        i += 1
    j = len(t) - 1
    while t[j] == t[-1]:
        j -= 1

    if t[0] == t[-1]:
        if i != j - 1:
            return -1
        if t[i] + t[j] != t[0]:
            return -1
        return s[j][1]
    else:
        if i != j:
            return -1
        if i == 1 and t[0] + t[1] == t[2]:
            return s[1][1]
        if j == len(t) - 2 and t[j] + t[j+1] == t[j - 1]:
            return s[len(t) - 1][1]
        return -1

print(solve(b_))


I found an interesting problem on https://codeforces.com/problemset/problem/1185/E:
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $n \times m$ (where $n$ is the number of rows, $m$ is the number of columns) and starts to draw snakes in cells.

Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $26$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $26$.

Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $1$, i.e. each snake has size either $1 \times l$ or $l \times 1$, where $l$ is snake's length. Note that snakes can't bend.

When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.

Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.

-----Input-----

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

The first line of the test case description contains two integers $n$, $m$ ($1 \le n,m \le 2000$) — length and width of the checkered sheet of paper respectively.

Next $n$ lines of test case description contain $m$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty...

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

import sys
input = sys.stdin.readline

T = int(input())
for _ in range(T):
    n, m = list(map(int, input().split()))
    minx = {}
    maxx = {}
    miny = {}
    maxy = {}
    matrix = []
    for i in range(n):
        matrix.append(list(input().strip()))
    for i in range(n):
        for j in range(m):
            if matrix[i][j]!='.':
                try:
                    minx[matrix[i][j]] = min(minx[matrix[i][j]], j)
                except: minx[matrix[i][j]] = j
                try:
                    maxx[matrix[i][j]] = max(maxx[matrix[i][j]], j)
                except: maxx[matrix[i][j]] = j
                try:
                    miny[matrix[i][j]] = min(miny[matrix[i][j]], i)
                except: miny[matrix[i][j]] = i
                try:
                    maxy[matrix[i][j]] = max(maxy[matrix[i][j]], i)
                except: maxy[matrix[i][j]] = i
    copy = []
    for i in range(n):
        copy.append([])
        for j in range(m):
            copy[-1].append('.')
    for char in range(ord('a'), ord('z')+1):
        char = chr(char)
        try:
            if minx[char]==maxx[char]:
                c = minx[char]
                for r in range(miny[char], maxy[char]+1):
                    copy[r][c] = char
            else:
                r = miny[char]
                for c in range(minx[char], maxx[char]+1):
                    copy[r][c] = char
        except: pass
    if matrix==copy:
        print("YES")
        cnt = -1
        for char in range(ord('z'), ord('a')-1, -1):
            char = chr(char)
            try:
                minx[char]+=0
                break
            except: pass
        else: cnt = 0
        if cnt!=0:
            cnt = ord(char)-ord('a')+1
        print(cnt)
        ans = []
        for char in range(ord('a'), ord('a')+cnt):
            char = chr(char)
            try:
                ans.append((miny[char], minx[char], maxy[char], maxx[char]))
            except: pass
        i = 0
        for char in range(ord('a'), ord('a')+cnt):
       ...


I found an interesting problem on https://codeforces.com/problemset/problem/1185/F:
A company of $n$ friends wants to order exactly two pizzas. It is known that in total there are $9$ pizza ingredients in nature, which are denoted by integers from $1$ to $9$.

Each of the $n$ friends has one or more favorite ingredients: the $i$-th of friends has the number of favorite ingredients equal to $f_i$ ($1 \le f_i \le 9$) and your favorite ingredients form the sequence $b_{i1}, b_{i2}, \dots, b_{if_i}$ ($1 \le b_{it} \le 9$).

The website of CodePizza restaurant has exactly $m$ ($m \ge 2$) pizzas. Each pizza is characterized by a set of $r_j$ ingredients $a_{j1}, a_{j2}, \dots, a_{jr_j}$ ($1 \le r_j \le 9$, $1 \le a_{jt} \le 9$) , which are included in it, and its price is $c_j$.

Help your friends choose exactly two pizzas in such a way as to please the maximum number of people in the company. It is known that a person is pleased with the choice if each of his/her favorite ingredients is in at least one ordered pizza. If there are several ways to choose two pizzas so as to please the maximum number of friends, then choose the one that minimizes the total price of two pizzas.

-----Input-----

The first line of the input contains two integers $n$ and $m$ ($1 \le n \le 10^5, 2 \le m \le 10^5$) — the number of friends in the company and the number of pizzas, respectively.

Next, the $n$ lines contain descriptions of favorite ingredients of the friends: the $i$-th of them contains the number of favorite ingredients $f_i$ ($1 \le f_i \le 9$) and a sequence of distinct integers $b_{i1}, b_{i2}, \dots, b_{if_i}$ ($1 \le b_{it} \le 9$).

Next, the $m$ lines contain pizza descriptions: the $j$-th of them contains the integer price of the pizza $c_j$ ($1 \le c_j \le 10^9$), the number of ingredients $r_j$ ($1 \le r_j \le 9$) and the ingredients themselves as a sequence of distinct integers $a_{j1}, a_{j2}, \dots, a_{jr_j}$ ($1 \le a_{jt} \le 9$).

-----Output-----

Output two integers $j_1$ and $j_2$ ($1 \le j_1,j_2 \le m$, $j_1 \ne j_2$) denoting the indices of two pizzas in the required set. If there...

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

from sys import stdin, stdout
import itertools

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

friends = [0]*512
exists = [0]*512
costs_min = [0]*512
costs_2 = [0]*512
index_min = [0]*512
index_2 = [0]*512

count_friends = [0]*512

def top_to_idx(top):
    ans = 0
    for t in top:
        ans += 1 << (t-1)
    return ans

def idx_to_top(idx):
    ans = []
    for i in range(9):
        if idx & (1 << i):
            ans.append(i+1)
    return ans

for i in range(n):
    top = list(map(int, stdin.readline().split()))[1:]
    friends[top_to_idx(top)] += 1

#print(friends)

def subset(i, j):
    for s in range(9):
        if i & (1 << s) and not (j & (1 << s)):
            return False
    return True

for i in range(512):
    for j in range(512):
        if subset(j, i):
            count_friends[i] += friends[j]

#print(count_friends)

for i in range(m):
    pizza = list(map(int, stdin.readline().split()))
    top_idx = top_to_idx(pizza[2:])
    cost = pizza[0]
    exists[top_idx] = True
    if costs_min[top_idx] == 0 or cost < costs_min[top_idx]:
        costs_2[top_idx] = costs_min[top_idx]
        index_2[top_idx] = index_min[top_idx]
        costs_min[top_idx] = cost
        index_min[top_idx] = i+1
    elif costs_2[top_idx] == 0 or cost < costs_2[top_idx]:
        costs_2[top_idx] = cost
        index_2[top_idx] = i+1

best_matches = -1
best_cost = -1
best = None
for p1 in range(512):
    for p2 in range(p1, 512):
        if not exists[p1] or not exists[p2]:
            continue
        if p1 == p2 and index_2[p1] == 0:
            continue
        p = p1 | p2
    #    print(idx_to_top(p1 | p2))
        matches = count_friends[p]
     #   print(matches)
        cost = costs_min[p1] + costs_min[p2] if p1 != p2 else costs_min[p1] + costs_2[p2]
        if best_matches == -1 or matches > best_matches or (matches == best_matches and cost < best_cost):
            best = (index_min[p1], index_min[p2]) if p1 != p2 else (index_min[p1], index_2[p2])
            best_matches = matches
            best_cost =...


I found an interesting problem on https://codeforces.com/problemset/problem/1185/G1:
The only difference between easy and hard versions is constraints.

Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.

In the player, Polycarp stores $n$ songs, each of which is characterized by two parameters: $t_i$ and $g_i$, where $t_i$ is the length of the song in minutes ($1 \le t_i \le 15$), $g_i$ is its genre ($1 \le g_i \le 3$).

Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the $i$-th song, he would spend exactly $t_i$ minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.

Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.

-----Input-----

The first line of the input contains two integers $n$ and $T$ ($1 \le n \le 15, 1 \le T \le 225$) — the number of songs in the player and the required total duration, respectively.

Next, the $n$ lines contain descriptions of songs: the $i$-th line contains two integers $t_i$ and $g_i$ ($1 \le t_i \le 15, 1 \le g_i \le 3$) — the duration of the $i$-th song and its genre, respectively.

-----Output-----

Output one integer — the number of different sequences of songs, the total length of exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo $10^9 + 7$ (that is, the remainder when dividing the quantity by $10^9 +...

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

def popcount(i):
    assert 0 <= i < 0x100000000
    i = i - ((i >> 1) & 0x55555555)
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
    return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24

N, T = map(int, input().split())
TG = [list(map(int, input().split())) for _ in range(N)]
mod = 10**9+7

dp = [[0]*(2**N) for _ in range(4)]
for i in range(1, 4):
    dp[i][0] = 1

for S in range(2**N):
    if popcount(S) == 1:
        dp[TG[(S&(-S)).bit_length() - 1][1]][S] = 1
    for i in range(1, 4):
        for j in range(N):
            if S & (2**j) or i == TG[j][1]:
                continue
            dp[TG[j][1]][S|(2**j)] = (dp[TG[j][1]][S|(2**j)] + dp[i][S]) % mod

table = [0]*(2**N)
for S in range(2**N):
    table[S] = sum(TG[j][0] for j in range(N) if 2**j & S)

ans = 0
for S in range(2**N):
    if table[S] == T:
        for i in range(1, 4):
            ans = (ans + dp[i][S]) % mod

print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1186/A:
Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks.

Determine whether the Cossack can reward all participants, giving each of them at least one pen and at least one notebook.

-----Input-----

The first line contains three integers $n$, $m$, and $k$ ($1 \leq n, m, k \leq 100$) — the number of participants, the number of pens, and the number of notebooks respectively.

-----Output-----

Print "Yes" if it possible to reward all the participants. Otherwise, print "No".

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

-----Examples-----
Input
5 8 6

Output
Yes

Input
3 9 3

Output
Yes

Input
8 5 20

Output
No

-----Note-----

In the first example, there are $5$ participants. The Cossack has $8$ pens and $6$ notebooks. Therefore, he has enough pens and notebooks.

In the second example, there are $3$ participants. The Cossack has $9$ pens and $3$ notebooks. He has more than enough pens but only the minimum needed number of notebooks.

In the third example, there are $8$ participants but only $5$ pens. Since the Cossack does not have enough pens, the answer is "No".

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

n, m, k = [int(x) for x in input().split()]

if m >= n and k >= n:
    print("Yes")
else:
    print("No")


I found an interesting problem on https://codeforces.com/problemset/problem/1186/C:
Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $a$ and $b$. It is known that $|b| \leq |a|$, that is, the length of $b$ is at most the length of $a$.

The Cossack considers every substring of length $|b|$ in string $a$. Let's call this substring $c$. He matches the corresponding characters in $b$ and $c$, after which he counts the number of positions where the two strings are different. We call this function $f(b, c)$.

For example, let $b = 00110$, and $c = 11000$. In these strings, the first, second, third and fourth positions are different.

Vus the Cossack counts the number of such substrings $c$ such that $f(b, c)$ is even.

For example, let $a = 01100010$ and $b = 00110$. $a$ has four substrings of the length $|b|$: $01100$, $11000$, $10001$, $00010$.  $f(00110, 01100) = 2$; $f(00110, 11000) = 4$; $f(00110, 10001) = 4$; $f(00110, 00010) = 1$.

Since in three substrings, $f(b, c)$ is even, the answer is $3$.

Vus can not find the answer for big strings. That is why he is asking you to help him.

-----Input-----

The first line contains a binary string $a$ ($1 \leq |a| \leq 10^6$) — the first string.

The second line contains a binary string $b$ ($1 \leq |b| \leq |a|$) — the second string.

-----Output-----

Print one number — the answer.

-----Examples-----
Input
01100010
00110

Output
3

Input
1010111110
0110

Output
4

-----Note-----

The first example is explained in the legend.

In the second example, there are five substrings that satisfy us: $1010$, $0101$, $1111$, $1111$.

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

import sys
from math import floor, ceil

IS_LOCAL = False

def read_one(dtype=int):
    return dtype(input())

def read_multiple(f, dtype=int):
    return f(list(map(dtype, input().split())))

def main():
    a = '01100010'
    b = '00110'

    if not IS_LOCAL:
        a = input()
        b = input()

    def cst(x):
        return 0 if x == '0' else 1

    def rsum(arr):
        return sum(map(cst, arr))

    sb, lb = rsum(b), len(b)
    s = None
    res = 0
    for i in range(lb - 1, len(a)):
        if s is None:
            s = rsum(a[:lb])
        else:
            s = s - cst(a[i - lb]) + cst(a[i])

        if (s - sb) % 2 == 0:
            res += 1

    print(res)

def __starting_point():
    if len(sys.argv) > 1 and sys.argv[1] == 'True':
        IS_LOCAL = True
    main()

__starting_point()


I found an interesting problem on https://codeforces.com/problemset/problem/1186/D:
Vus the Cossack has $n$ real numbers $a_i$. It is known that the sum of all numbers is equal to $0$. He wants to choose a sequence $b$ the size of which is $n$ such that the sum of all numbers is $0$ and each $b_i$ is either $\lfloor a_i \rfloor$ or $\lceil a_i \rceil$. In other words, $b_i$ equals $a_i$ rounded up or down. It is not necessary to round to the nearest integer.

For example, if $a = [4.58413, 1.22491, -2.10517, -3.70387]$, then $b$ can be equal, for example, to $[4, 2, -2, -4]$.

Note that if $a_i$ is an integer, then there is no difference between $\lfloor a_i \rfloor$ and $\lceil a_i \rceil$, $b_i$ will always be equal to $a_i$.

Help Vus the Cossack find such sequence!

-----Input-----

The first line contains one integer $n$ ($1 \leq n \leq 10^5$) — the number of numbers.

Each of the next $n$ lines contains one real number $a_i$ ($|a_i| < 10^5$). It is guaranteed that each $a_i$ has exactly $5$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $0$.

-----Output-----

In each of the next $n$ lines, print one integer $b_i$. For each $i$, $|a_i-b_i|<1$ must be met.

If there are multiple answers, print any.

-----Examples-----
Input
4
4.58413
1.22491
-2.10517
-3.70387

Output
4
2
-2
-4

Input
5
-6.32509
3.30066
-0.93878
2.00000
1.96321

Output
-6
3
-1
2
2

-----Note-----

The first example is explained in the legend.

In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.

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

# JMD
# Nagendra Jha-4096

import sys
from math import ceil,floor

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

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

##### Main ####
t = 1
for tt in range(t):
    n=int(input())
    a=[]

    for i in range(n):
        a.append(float(input()))

    intcnt = 0

    for num in a:
        if(ceil(num)==floor(num)):
            intcnt+=1

    non_int = n-intcnt

    minsum=0
    ans=[]

    for num in a:
        minsum+=floor(num)
        ans.append(floor(num))

    if(abs(minsum)<=non_int ):
        cnt = abs(minsum)

        for i in range(n):
            if cnt == 0:
                break
            if(floor(a[i])!=ceil(a[i])):
                ans[i]+=1
                cnt-=1
        for num in ans:
            print(num)

    else:
        maxsum = 0
        newans = []

        for num in a:
            maxsum+=ceil(num)
            ans.append(ceil(num))

        assert(maxsum<=non_int)

        for i in range(n):
            if maxsum == 0:
                break
            if(floor(a[i])!=ceil(a[i])):
                ans[i]-=1
                maxsum-=1

        for num in ans:
            print(num)


I found an interesting problem on https://codeforces.com/problemset/problem/1188/A1:
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.

You are given a tree with $n$ nodes. In the beginning, $0$ is written on all edges. In one operation, you can choose any $2$ distinct leaves $u$, $v$ and any real number $x$ and add $x$ to values written on all edges on the simple path between $u$ and $v$.

For example, on the picture below you can see the result of applying two operations to the graph: adding $2$ on the path from $7$ to $6$, and then adding $-0.5$ on the path from $4$ to $5$.

 [Image]

Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?

Leaf is a node of a tree of degree $1$. Simple path is a path that doesn't contain any node twice.

-----Input-----

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

Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1 \le u, v \le n$, $u \neq v$), meaning that there is an edge between nodes $u$ and $v$. It is guaranteed that these edges form a tree.

-----Output-----

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".

Otherwise, output "YES".

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

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

Output
YES
Input
3
1 2
2 3

Output
NO
Input
5
1 2
1 3
1 4
2 5

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

Output
YES

-----Note-----

In the first example, we can add any real $x$ to the value written on the only edge $(1, 2)$.

 [Image]

In the second example, one of configurations that we can't reach is $0$ written on $(1, 2)$ and $1$ written on $(2, 3)$.

 $8$

Below you can see graphs from examples $3$, $4$:

 [Image]

 [Image]

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

n = int(input())
adj = [[] for i in range(n)]
for _ in range(n-1):
  u, v = map(int, input().split())
  adj[u-1].append(v)
  adj[v-1].append(u)

for v in adj:
  if len(v) == 2:
    print('NO')
    break
else:
  print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1189/A:
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.

Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For example, 1, 101, 0000 are good, while 01, 1001, and 111000 are not good.

We are given a string $s$ of length $n$ consisting of only zeroes and ones. We need to cut $s$ into minimal possible number of substrings $s_1, s_2, \ldots, s_k$ such that all of them are good. More formally, we have to find minimal by number of strings sequence of good strings $s_1, s_2, \ldots, s_k$ such that their concatenation (joining) equals $s$, i.e. $s_1 + s_2 + \dots + s_k = s$.

For example, cuttings 110010 into 110 and 010 or into 11 and 0010 are valid, as 110, 010, 11, 0010 are all good, and we can't cut 110010 to the smaller number of substrings as 110010 isn't good itself. At the same time, cutting of 110010 into 1100 and 10 isn't valid as both strings aren't good. Also, cutting of 110010 into 1, 1, 0010 isn't valid, as it isn't minimal, even though all $3$ strings are good.

Can you help Keanu? We can show that the solution always exists. If there are multiple optimal answers, print any.

-----Input-----

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

The second line contains the string $s$ of length $n$ consisting only from zeros and ones.

-----Output-----

In the first line, output a single integer $k$ ($1\le k$) — a minimal number of strings you have cut $s$ into.

In the second line, output $k$ strings $s_1, s_2, \ldots, s_k$ separated with spaces. The length of each string has to be positive. Their concatenation has to be equal to $s$ and all of them have to be good.

If there are multiple answers, print any.

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

Output
1
1
Input
2
10

Output
2
1 0
Input
6
100011

Output
2
100 011

-----Note-----

In the first...

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

# @author

import sys

class AKeanuReeves:
    def solve(self):
        n = int(input())
        s = input()
        if s.count('0') != s.count('1'):
            print(1)
            print(s)
        else:
            print(2)
            print(s[0], s[1:])

solver = AKeanuReeves()
input = sys.stdin.readline

solver.solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1189/B:
You are given $n$ numbers $a_1, a_2, \ldots, a_n$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?

For example, for the array $[1, 4, 5, 6, 7, 8]$, the arrangement on the left is valid, while arrangement on the right is not, as $5\ge 4 + 1$ and $8> 1 + 6$. [Image]

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \le 10^9$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).

-----Output-----

If there is no solution, output "NO" in the first line.

If there is a solution, output "YES" in the first line. In the second line output $n$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.

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

Output
YES
4 2 3
Input
5
1 2 3 4 4

Output
YES
4 4 2 1 3
Input
3
13 8 5

Output
NO
Input
4
1 10 100 1000

Output
NO

-----Note-----

One of the possible arrangements is shown in the first example:

$4< 2 + 3$;

$2 < 4 + 3$;

$3< 4 + 2$.

One of the possible arrangements is shown in the second example.

No matter how we arrange $13, 8, 5$ in a circle in the third example, $13$ will have $8$ and $5$ as neighbors, but $13\ge 8 + 5$.

There is no solution in the fourth example.

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

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

a.sort()

if a[-2]+a[-3]<=a[-1]:
    print("NO")
else:
    print("YES")
    print(" ".join(map(str, a[:-2]+[a[-1], a[-2]])))


I found an interesting problem on https://codeforces.com/problemset/problem/1189/C:
Consider a sequence of digits of length $2^k$ $[a_1, a_2, \ldots, a_{2^k}]$. We perform the following operation with it: replace pairs $(a_{2i+1}, a_{2i+2})$ with $(a_{2i+1} + a_{2i+2})\bmod 10$ for $0\le i<2^{k-1}$. For every $i$ where $a_{2i+1} + a_{2i+2}\ge 10$ we get a candy! As a result, we will get a sequence of length $2^{k-1}$.

Less formally, we partition sequence of length $2^k$ into $2^{k-1}$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $\ldots$, the last pair consists of the ($2^k-1$)-th and ($2^k$)-th numbers. For every pair such that sum of numbers in it is at least $10$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $10$ (and don't change the order of the numbers).

Perform this operation with a resulting array until it becomes of length $1$. Let $f([a_1, a_2, \ldots, a_{2^k}])$ denote the number of candies we get in this process.

For example: if the starting sequence is $[8, 7, 3, 1, 7, 0, 9, 4]$ then:

After the first operation the sequence becomes $[(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10]$ $=$ $[5, 4, 7, 3]$, and we get $2$ candies as $8 + 7 \ge 10$ and $9 + 4 \ge 10$.

After the second operation the sequence becomes $[(5 + 4)\bmod 10, (7 + 3)\bmod 10]$ $=$ $[9, 0]$, and we get one more candy as $7 + 3 \ge 10$.

After the final operation sequence becomes $[(9 + 0) \bmod 10]$ $=$ $[9]$.

Therefore, $f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$ as we got $3$ candies in total.

You are given a sequence of digits of length $n$ $s_1, s_2, \ldots s_n$. You have to answer $q$ queries of the form $(l_i, r_i)$, where for $i$-th query you have to output $f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}])$. It is guaranteed that $r_i-l_i+1$ is of form $2^k$ for some nonnegative integer $k$.

-----Input-----

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

The second line contains $n$ digits $s_1,...

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

# @author

import sys

class CCandies:
    def solve(self):
        n = int(input())
        s = [int(_) for _ in input().split()]
        q = int(input())
        pre = [0] * (n + 1)
        for i in range(1, n + 1):
            pre[i] = pre[i - 1] + s[i - 1]
        for i in range(q):
            li, ri = [int(_) for _ in input().split()]
            print((pre[ri] - pre[li - 1]) // 10)

solver = CCandies()
input = sys.stdin.readline

solver.solve()


I found an interesting problem on https://codeforces.com/problemset/problem/1189/F:
Let's call beauty of an array $b_1, b_2, \ldots, b_n$ ($n > 1$)  — $\min\limits_{1 \leq i < j \leq n} |b_i - b_j|$.

You're given an array $a_1, a_2, \ldots a_n$ and a number $k$. Calculate the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $998244353$.

A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.

-----Input-----

The first line contains integers $n, k$ ($2 \le k \le n \le 1000$).

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

-----Output-----

Output one integer — the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $998244353$.

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

Output
8
Input
5 5
1 10 100 1000 10000

Output
9

-----Note-----

In the first example, there are $4$ subsequences of length $3$ — $[1, 7, 3]$, $[1, 3, 5]$, $[7, 3, 5]$, $[1, 7, 5]$, each of which has beauty $2$, so answer is $8$.

In the second example, there is only one subsequence of length $5$ — the whole array, which has the beauty equal to $|10-1| = 9$.

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

from collections import defaultdict
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ans))+"\n")
'''
inf = 100000000000000000  # 1e17
mod = 998244353

n, m = list(map(int, input().split()))
A = [0] + sorted(list(map(int, input().split())))

ans = 0

f = [[0] * (n + 10) for _ in range(m + 10)]

for x in range(1,(A[n] - A[1]) // (m - 1) + 1):
    for i in range(1, n + 1):
        f[1][i] = 1
    for i in range(2, m + 1):
        sum = 0
        pre = 1
        for j in range(1, n + 1):
            while pre <= n and A[pre] + x <= A[j]:
                sum += f[i - 1][pre]
                sum %= mod
                pre += 1
            f[i][j] = sum
    for i in range(1, n + 1):
        ans += f[m][i]
        ans %= mod
print(ans)

# the end


I found an interesting problem on https://codeforces.com/problemset/problem/1190/A:
Recently, Tokitsukaze found an interesting game. Tokitsukaze had $n$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $m$ ($1 \le m \le n$) special items of them.

These $n$ items are marked with indices from $1$ to $n$. In the beginning, the item with index $i$ is placed on the $i$-th position. Items are divided into several pages orderly, such that each page contains exactly $k$ positions and the last positions on the last page may be left empty.

Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.

 [Image] Consider the first example from the statement: $n=10$, $m=4$, $k=5$, $p=[3, 5, 7, 10]$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $3$ and $5$. After, the first page remains to be special. It contains $[1, 2, 4, 6, 7]$, Tokitsukaze discards the special item with index $7$. After, the second page is special (since it is the first page containing a special item). It contains $[9, 10]$, Tokitsukaze discards the special item with index $10$.

Tokitsukaze wants to know the number of operations she would do in total.

-----Input-----

The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 10^{18}$, $1 \le m \le 10^5$, $1 \le m, k \le n$) — the number of items, the number of special items to be discarded and the number of positions in each page.

The...

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

R = lambda :list(map(int,input().split()))
n,m,k = R()
l = R()

q = 0
t = 1
nb = 0
for i in range(m-1) :
	if ((l[i+1]-1-q)//k) == ( ( (l[i]-1-q)//k)) :
		t += 1
		pass
	else :
		nb +=1
		q += t
		t = 1

print(nb+1)


I found an interesting problem on https://codeforces.com/problemset/problem/1190/B:
Tokitsukaze and CSL are playing a little game of stones.

In the beginning, there are $n$ piles of stones, the $i$-th pile of which has $a_i$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?

Consider an example: $n=3$ and sizes of piles are $a_1=2$, $a_2=3$, $a_3=0$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $[1, 3, 0]$ and it is a good move. But if she chooses the second pile then the state will be $[2, 2, 0]$ and she immediately loses. So the only good move for her is to choose the first pile.

Supposing that both players always take their best moves and never make mistakes, who will win the game?

Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_1, a_2, \ldots, a_n \le 10^9$), which mean the $i$-th pile has $a_i$ stones.

-----Output-----

Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.

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

Output
cslnb

Input
2
1 0

Output
cslnb

Input
2
2 2

Output
sjfnb

Input
3
2 3 1

Output
sjfnb

-----Note-----

In the first example, Tokitsukaze cannot take any stone, so CSL will win.

In the second example, Tokitsukaze can only take a stone from the first pile, and...

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

ans=["sjfnb","cslnb"]
n=int(input())
l=list(map(int,input().split()))
l.sort()
d=set()
e=0
s=0
for i in range(n):
    if l[i] in d:
        e+=1
        s=l[i]
    d.add(l[i])
if e>1 or l.count(0)>1 or s-1 in d:
    print(ans[1])

else:
    l=[l[i]-i for i in range(n)]
    #print(l)
    print(ans[1-sum(l)%2])


I found an interesting problem on https://codeforces.com/problemset/problem/1190/C:
"Duel!"

Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.

There are $n$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $k$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $n$ cards face the same direction after one's move, the one who takes this move will win.

Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.

-----Input-----

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

The second line contains a single string of length $n$ that only consists of $0$ and $1$, representing the situation of these $n$ cards, where the color side of the $i$-th card faces up if the $i$-th character is $1$, or otherwise, it faces down and the $i$-th character is $0$.

-----Output-----

Print "once again" (without quotes) if the total number of their moves can exceed $10^9$, which is considered a draw.

In other cases, print "tokitsukaze" (without quotes) if Tokitsukaze will win, or "quailty" (without quotes) if Quailty will win.

Note that the output characters are case-sensitive, and any wrong spelling would be rejected.

-----Examples-----
Input
4 2
0101

Output
quailty

Input
6 1
010101

Output
once again

Input
6 5
010101

Output
tokitsukaze

Input
4 1
0011

Output
once again

-----Note-----

In the first example, no matter how Tokitsukaze moves, there would be three cards with color sides facing the same direction after her move, and Quailty can flip the last card to this direction and win.

In the second example, no matter how Tokitsukaze moves, Quailty can choose the same card and flip back to the initial situation, which can allow the...

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

import sys
import copy
input = sys.stdin.readline

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

def JUDGE(C):
    ANS_one=0
    ANS_zero=0

    for c in C:
        if c=="0":
            ANS_zero+=1
        else:
            break

    for c in C[::-1]:
        if c=="0":
            ANS_zero+=1
        else:
            break

    for c in C:
        if c=="1":
            ANS_one+=1
        else:
            break

    for c in C[::-1]:
        if c=="1":
            ANS_one+=1
        else:
            break

    if ANS_zero>=n-k or ANS_one>=n-k:
        return 1
    else:
        return 0

if JUDGE(C)==1:
    print("tokitsukaze")
    return

if k>=n-1:
    print("quailty")
    return
if k<n/2:
    print("once again")
    return

CAN1=copy.copy(C)
CAN2=copy.copy(C)

if C[0]=="0":
    for i in range(1,k+1):
        CAN1[i]="1"
else:
    for i in range(1,k+1):
        CAN1[i]="0"

if C[-1]=="0":
    for i in range(n-1,n-k-1,-1):
        CAN2[i]="1"
else:
    for i in range(n-2,n-k-2,-1):
        CAN2[i]="0"

if JUDGE(CAN1)==1 and JUDGE(CAN2)==1:
    print("quailty")
    return
else:
    print("once again")
    return


I found an interesting problem on https://codeforces.com/problemset/problem/1190/D:
There are $n$ points on the plane, the $i$-th of which is at $(x_i, y_i)$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.

The strange area is enclosed by three lines, $x = l$, $y = a$ and $x = r$, as its left side, its bottom side and its right side respectively, where $l$, $r$ and $a$ can be any real numbers satisfying that $l < r$. The upper side of the area is boundless, which you can regard as a line parallel to the $x$-axis at infinity. The following figure shows a strange rectangular area. [Image]

A point $(x_i, y_i)$ is in the strange rectangular area if and only if $l < x_i < r$ and $y_i > a$. For example, in the above figure, $p_1$ is in the area while $p_2$ is not.

Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.

-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 2 \times 10^5$) — the number of points on the plane.

The $i$-th of the next $n$ lines contains two integers $x_i$, $y_i$ ($1 \leq x_i, y_i \leq 10^9$) — the coordinates of the $i$-th point.

All points are distinct.

-----Output-----

Print a single integer — the number of different non-empty sets of points she can obtain.

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

Output
3

Input
3
1 1
2 1
3 1

Output
6

Input
4
2 1
2 2
3 1
3 2

Output
6

-----Note-----

For the first example, there is exactly one set having $k$ points for $k = 1, 2, 3$, so the total number is $3$.

For the second example, the numbers of sets having $k$ points for $k = 1, 2, 3$ are $3$, $2$, $1$ respectively, and their sum is $6$.

For the third example, as the following figure shows, there are  $2$ sets having one point;  $3$ sets having two points;  $1$ set having four points.

Therefore, the number of different non-empty sets in this example is $2 + 3 + 0 + 1 = 6$. [Image]

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

import sys
import copy
input = sys.stdin.readline

n=int(input())
P=[list(map(int,input().split())) for i in range(n)]

SET_X=set()
SET_Y=set()

for x,y in P:
    SET_X.add(x)
    SET_Y.add(y)

CX=sorted(SET_X)
CY=sorted(SET_Y)

LEN=len(CX)
MAX=len(CX)-1

DICT_X={x:i for i,x in enumerate(CX)}
DICT_Y={x:i for i,x in enumerate(CY)}

for i in range(n):
    P[i]=[DICT_X[P[i][0]],DICT_Y[P[i][1]]]

check=[0]*len(CX)

# BIT(BIT-indexed tree)

BIT=[0]*(LEN+1)# 1-indexedなtree

def update(v,w):# vにwを加える
    while v<=LEN:
        BIT[v]+=w
        v+=(v&(-v))# 自分を含む大きなノードへ. たとえばv=3→v=4

def getvalue(v):# [1,v]の区間の和を求める
    ANS=0
    while v!=0:
        ANS+=BIT[v]
        v-=(v&(-v))# 自分より小さい2ベキのノードへ. たとえばv=3→v=2へ
    return ANS

LIST_Y=[[] for i in range(len(CY))]
for x,y in P:
    LIST_Y[y].append(x)

for i in range(len(CY)):
    LIST_Y[i].sort()

ANS=0
for y in range(len(CY)-1,-1,-1):
    for x in LIST_Y[y]:
        #print(x,check)
        if check[x]==0:
            check[x]=1
            update(x+1,1)

    ANS+=getvalue(LIST_Y[y][0]+1)*(getvalue(MAX+1)-getvalue(LIST_Y[y][0]+1)+1)

    for i in range(1,len(LIST_Y[y])):
        #print(getvalue(LIST_Y[y][i]+1)-getvalue(LIST_Y[y][i-1]+1)),getvalue(MAX+1)
        ANS+=(getvalue(LIST_Y[y][i]+1)-getvalue(LIST_Y[y][i-1]+1))*(getvalue(MAX+1)-getvalue(LIST_Y[y][i]+1)+1)

    #print(ANS)

print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1191/A:
Tokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP.

In general, different values of HP are grouped into $4$ categories:  Category $A$ if HP is in the form of $(4 n + 1)$, that is, when divided by $4$, the remainder is $1$;  Category $B$ if HP is in the form of $(4 n + 3)$, that is, when divided by $4$, the remainder is $3$;  Category $C$ if HP is in the form of $(4 n + 2)$, that is, when divided by $4$, the remainder is $2$;  Category $D$ if HP is in the form of $4 n$, that is, when divided by $4$, the remainder is $0$.

The above-mentioned $n$ can be any integer.

These $4$ categories ordered from highest to lowest as $A > B > C > D$, which means category $A$ is the highest and category $D$ is the lowest.

While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most $2$ (that is, either by $0$, $1$ or $2$). How much should she increase her HP so that it has the highest possible category?

-----Input-----

The only line contains a single integer $x$ ($30 \leq x \leq 100$) — the value Tokitsukaze's HP currently.

-----Output-----

Print an integer $a$ ($0 \leq a \leq 2$) and an uppercase letter $b$ ($b \in \lbrace A, B, C, D \rbrace$), representing that the best way is to increase her HP by $a$, and then the category becomes $b$.

Note that the output characters are case-sensitive.

-----Examples-----
Input
33

Output
0 A

Input
98

Output
1 B

-----Note-----

For the first example, the category of Tokitsukaze's HP is already $A$, so you don't need to enhance her ability.

For the second example:  If you don't increase her HP, its value is still $98$, which equals to $(4 \times 24 + 2)$, and its category is $C$.  If you increase her HP by $1$, its value becomes $99$, which equals to $(4 \times 24 + 3)$, and its category becomes $B$.  If you increase her HP by $2$, its value becomes $100$, which equals to $(4 \times 25)$, and its...

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

import math as mt
import sys,string,bisect
input=sys.stdin.readline
from collections import deque,defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : list(map(int,input().split()))
I=lambda :int(input())
n=I()
if(n%4==0):
    print(1,"A")
if(n%4==1):
    print(0,"A")
if(n%4==2):
    print(1,"B")
if(n%4==3):
    print(2,"A")


I found an interesting problem on https://codeforces.com/problemset/problem/1191/B:
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from $1$ to $9$). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, $\ldots$, 9m, 1p, 2p, $\ldots$, 9p, 1s, 2s, $\ldots$, 9s.

In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.

Do you know the minimum number of extra suited tiles she needs to draw so that she can win?

Here are some useful definitions in this game:  A mentsu, also known as meld, is formed by a koutsu or a shuntsu;  A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;  A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.

Some examples:   [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no koutsu or shuntsu, so it includes no mentsu;  [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;  [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.

Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.

-----Input-----

The only line contains three strings — the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from $1$ to $9$ and the second character is m, p or s.

-----Output-----

Print a single integer — the minimum...

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

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 12 17:39:54 2019

@author: Hamadeh
"""

# -*- coding: utf-8 -*-
"""
Created on Fri Jul 12 17:33:49 2019

@author: Hamadeh
"""

class cinn:
    def __init__(self):
        self.x=[]
    def cin(self,t=int):
        if(len(self.x)==0):
            a=input()
            self.x=a.split()
            self.x.reverse()
        return self.get(t)
    def get(self,t):
        return t(self.x.pop())
    def clist(self,n,t=int): #n is number of inputs, t is type to be casted
        l=[0]*n
        for i in range(n):
            l[i]=self.cin(t)
        return l
    def clist2(self,n,t1=int,t2=int,t3=int,tn=2):
        l=[0]*n
        for i in range(n):
            if(tn==2):
                a1=self.cin(t1)
                a2=self.cin(t2)
                l[i]=(a1,a2)
            elif (tn==3):
                a1=self.cin(t1)
                a2=self.cin(t2)
                a3=self.cin(t3)
                l[i]=(a1,a2,a3)
        return l
    def clist3(self,n,t1=int,t2=int,t3=int):
        return self.clist2(self,n,t1,t2,t3,3)
    def cout(self,i,ans=''):
        if(ans==''):
            print("Case #"+str(i+1)+":", end=' ')
        else:
            print("Case #"+str(i+1)+":",ans)
    def printf(self,thing):
        print(thing,end='')
    def countlist(self,l,s=0,e=None):
        if(e==None):
            e=len(l)
        dic={}
        for el in range(s,e):
            if l[el] not in dic:
                dic[l[el]]=1
            else:
                dic[l[el]]+=1
        return dic
    def talk (self,x):
        print(x,flush=True)
    def dp1(self,k):
        L=[-1]*(k)
        return L
    def dp2(self,k,kk):
        L=[-1]*(k)
        for i in range(k):
            L[i]=[-1]*kk
        return L
    def isprime(self,n):
        if(n==1 or n==0):
            return False
        for i in range(2,int(n**0.5+1)):
            if(n%i==0):
                return False
        return True
    def factors(self,n):
        from functools import reduce
        return...


I found an interesting problem on https://codeforces.com/problemset/problem/1194/A:
You have a list of numbers from $1$ to $n$ written from left to right on the blackboard.

You perform an algorithm consisting of several steps (steps are $1$-indexed). On the $i$-th step you wipe the $i$-th number (considering only remaining numbers). You wipe the whole number (not one digit). $\left. \begin{array}{r}{1234567 \ldots} \\{234567 \ldots} \\{24567 \ldots} \end{array} \right.$

When there are less than $i$ numbers remaining, you stop your algorithm.

Now you wonder: what is the value of the $x$-th remaining number after the algorithm is stopped?

-----Input-----

The first line contains one integer $T$ ($1 \le T \le 100$) — the number of queries. The next $T$ lines contain queries — one per line. All queries are independent.

Each line contains two space-separated integers $n$ and $x$ ($1 \le x < n \le 10^{9}$) — the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least $x$ numbers.

-----Output-----

Print $T$ integers (one per query) — the values of the $x$-th number after performing the algorithm for the corresponding queries.

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

Output
2
4
12

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

q = int(input())
for i in range(q):
    n, x = map(int, input().split())
    print(x * 2)


I found an interesting problem on https://codeforces.com/problemset/problem/1194/C:
You are given three strings $s$, $t$ and $p$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.

During each operation you choose any character from $p$, erase it from $p$ and insert it into string $s$ (you may insert this character anywhere you want: in the beginning of $s$, in the end or between any two consecutive characters).

For example, if $p$ is aba, and $s$ is de, then the following outcomes are possible (the character we erase from $p$ and insert into $s$ is highlighted):

  aba $\rightarrow$ ba, de $\rightarrow$ ade;  aba $\rightarrow$ ba, de $\rightarrow$ dae;  aba $\rightarrow$ ba, de $\rightarrow$ dea;  aba $\rightarrow$ aa, de $\rightarrow$ bde;  aba $\rightarrow$ aa, de $\rightarrow$ dbe;  aba $\rightarrow$ aa, de $\rightarrow$ deb;  aba $\rightarrow$ ab, de $\rightarrow$ ade;  aba $\rightarrow$ ab, de $\rightarrow$ dae;  aba $\rightarrow$ ab, de $\rightarrow$ dea;

Your goal is to perform several (maybe zero) operations so that $s$ becomes equal to $t$. Please determine whether it is possible.

Note that you have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 100$) — the number of queries. Each query is represented by three consecutive lines.

The first line of each query contains the string $s$ ($1 \le |s| \le 100$) consisting of lowercase Latin letters.

The second line of each query contains the string $t$ ($1 \le |t| \le 100$) consisting of lowercase Latin letters.

The third line of each query contains the string $p$ ($1 \le |p| \le 100$) consisting of lowercase Latin letters.

-----Output-----

For each query print YES if it is possible to make $s$ equal to $t$, and NO otherwise.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

-----Example-----
Input
4
ab
acxb
cax
a
aaaa
aaabbcc
a
aaaa
aabbcc
ab
baaa
aaaaa

Output
YES
YES
NO
NO

-----Note-----

In the first test...

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

import sys
input = sys.stdin.readline
from collections import Counter

Q=int(input())
for testcases in range(Q):
    s=input().strip()
    t=input().strip()
    p=input().strip()

    L=len(s)
    ind=0

    for te in t:
        if te==s[ind]:
            ind+=1
        if ind==L:
            break

    if ind != L:
        print("NO")
        continue

    C=Counter(s)+Counter(p)
    CT=Counter(t)

    #print(s,p,t,C,CT)

    for ct in CT:
        if CT[ct]>C[ct]:
            print("NO")
            break
    else:
        print("YES")


I found an interesting problem on https://codeforces.com/problemset/problem/1194/D:
Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).

Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i - 1, i - 2 or i - k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i < k. The player who can't make a move loses the game.

Who wins if both participants play optimally?

Alice and Bob would like to play several games, so you should determine the winner in each game.

-----Input-----

The first line contains the single integer T (1 ≤ T ≤ 100) — the number of games. Next T lines contain one game per line. All games are independent.

Each of the next T lines contains two integers n and k (0 ≤ n ≤ 10^9, 3 ≤ k ≤ 10^9) — the length of the strip and the constant denoting the third move, respectively.

-----Output-----

For each game, print Alice if Alice wins this game and Bob otherwise.

-----Example-----
Input
4
0 3
3 3
3 4
4 4

Output
Bob
Alice
Bob
Alice

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

def Game(n, k):
    if k % 3 != 0:
        return [1, 0, 0][n % 3]
    else:
        n %= (k+4)
        if n == k+3:
            return 0
        else:
            return [1, 0, 0][n % 3]

for i in range(int(input())):
    N, K = list(map(int, input().split()))
    print(['Alice', 'Bob'][Game(N, K-3)])


I found an interesting problem on https://codeforces.com/problemset/problem/1194/F:
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $T$ seconds after coming.

Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $n$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $t_i$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).

Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $t_i$ seconds or $t_i + 1$ seconds to solve the $i$-th crossword, equiprobably (with probability $\frac{1}{2}$ he solves the crossword in exactly $t_i$ seconds, and with probability $\frac{1}{2}$ he has to spend an additional second to finish the crossword). All these events are independent.

After $T$ seconds pass (or after solving the last crossword, if he manages to do it in less than $T$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $E$ — the expected number of crosswords he will be able to solve completely. Can you calculate it?

Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $E = \sum \limits_{i = 0}^{n} i p_i$, where $p_i$ is the probability that Adilbek will solve exactly $i$ crosswords.

We can represent $E$ as rational fraction...

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

from sys import stdin, stdout, exit

mod = 10**9 + 7

def modinv(x):
    return pow(x, mod-2, mod)

N = 2*10**5 + 10
facts = [1]*N
for i in range(1,N):
    facts[i] = facts[i-1] * i
    facts[i] %= mod

def binom(n, k):
    ans = modinv(facts[k]) * modinv(facts[n-k])
    ans %= mod
    ans *= facts[n]
    ans %= mod
    return ans

#print("Finished preprocess")

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

ans = 0
total = sum(ts)
running = total
last_idx = n-1
while running > T:
    running -= ts[last_idx]
    last_idx -= 1
#print(last_idx+1)

last_bd = -1
last_sum = 0
idx = last_idx
while running + idx + 1 > T:
    bd = T - running
#    print("time remaining for", idx+1, "flips is", bd)
    cur_sum = last_sum + (binom(idx+1, last_bd) if last_bd >= 0 else 0)
    cur_sum *= modinv(2)
    cur_sum %= mod
    for fresh in range(last_bd+1, bd+1):
        cur_sum += binom(idx+1, fresh)
        cur_sum %= mod
 #   print("pr of", idx+1, "flips is", cur_sum, cur_sum / (2**(idx+1)))
    ans += cur_sum * modinv(pow(2, idx+1, mod))
    ans %= mod
    running -= ts[idx]
    last_bd = bd
    last_sum = cur_sum
    idx -= 1

#print(idx+1, "freebies")
ans += idx+1
ans %= mod
print(ans)


I found an interesting problem on https://codeforces.com/problemset/problem/1195/A:
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?

There are $n$ students living in a building, and for each of them the favorite drink $a_i$ is known. So you know $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le k$) is the type of the favorite drink of the $i$-th student. The drink types are numbered from $1$ to $k$.

There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $k$ types of drink sets, the $j$-th type contains two portions of the drink $j$. The available number of sets of each of the $k$ types is infinite.

You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $\lceil \frac{n}{2} \rceil$, where $\lceil x \rceil$ is $x$ rounded up.

After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $n$ is odd then one portion will remain unused and the students' teacher will drink it.

What is the maximum number of students that can get their favorite drink if $\lceil \frac{n}{2} \rceil$ sets will be chosen optimally and students will distribute portions between themselves optimally?

-----Input-----

The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 1\,000$) — the number of students in the building and the number of different drinks.

The next $n$ lines contain student's favorite drinks. The $i$-th line contains a single integer from $1$ to $k$ — the type of the favorite drink of the $i$-th student.

-----Output-----

Print exactly one integer — the maximum number of students that can get a favorite drink.

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

Output
4

Input
10 3
2
1
3
2
3
3
1
3
1
2

Output
9

-----Note-----

In the first example, students could...

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

from math import ceil
n, k = list(map(int, input().split()))
a = []
for i in range(n):
  a.append(int(input()))
res = 0
d = [0] * 1024
for i in a:
  d[i] += 1
for i in d:
  res += 2 * (i // 2)
res = res + ceil((n - res) / 2)
print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1195/B:
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.

For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs $n$ actions. The first action performed is to put a single candy into the box. For each of the remaining moves she can choose from two options:

  the first option, in case the box contains at least one candy, is to take exactly one candy out and eat it. This way the number of candies in the box decreased by $1$;  the second option is to put candies in the box. In this case, Alya will put $1$ more candy, than she put in the previous time.

Thus, if the box is empty, then it can only use the second option.

For example, one possible sequence of Alya's actions look as follows:

  put one candy into the box;  put two candies into the box;  eat one candy from the box;  eat one candy from the box;  put three candies into the box;  eat one candy from the box;  put four candies into the box;  eat one candy from the box;  put five candies into the box;

This way she will perform $9$ actions, the number of candies at the end will be $11$, while Alya will eat $4$ candies in total.

You know the total number of actions $n$ and the number of candies at the end $k$. You need to find the total number of sweets Alya ate. That is the number of moves of the first option. It's guaranteed, that for the given $n$ and $k$ the answer always exists.

Please note, that during an action of the first option, Alya takes out and eats exactly one candy.

-----Input-----

The first line contains two integers $n$ and $k$ ($1 \le n \le 10^9$; $0 \le k \le 10^9$) — the total number of moves and the number of candies in the box at the end.

It's guaranteed, that for the given $n$ and $k$ the answer exists.

-----Output-----

Print a single integer — the number of candies, which Alya ate. Please note, that in this problem there aren't multiple possible answers — the answer is unique for any input data....

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

from math import sqrt as sqrt
n, k = map(int, input().split())
t = int(sqrt(8 * n + 8 * k + 9) + 0.0001)
m = (t - 3) // 2
print(n - m)


I found an interesting problem on https://codeforces.com/problemset/problem/1195/C:
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $2 \cdot n$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $n$ people in each row). Students are numbered from $1$ to $n$ in each row in order from left to right.

 [Image]

Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $2n$ students (there are no additional constraints), and a team can consist of any number of students.

Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.

-----Input-----

The first line of the input contains a single integer $n$ ($1 \le n \le 10^5$) — the number of students in each row.

The second line of the input contains $n$ integers $h_{1, 1}, h_{1, 2}, \ldots, h_{1, n}$ ($1 \le h_{1, i} \le 10^9$), where $h_{1, i}$ is the height of the $i$-th student in the first row.

The third line of the input contains $n$ integers $h_{2, 1}, h_{2, 2}, \ldots, h_{2, n}$ ($1 \le h_{2, i} \le 10^9$), where $h_{2, i}$ is the height of the $i$-th student in the second row.

-----Output-----

Print a single integer — the maximum possible total height of players in a team Demid can choose.

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

Output
29

Input
3
1 2 9
10 1 1

Output
19

Input
1
7
4

Output
7

-----Note-----

In the first example Demid can choose the following team as follows:  [Image]

In the second example Demid can choose the following...

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

from sys import stdin, stdout, exit

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

top_dp = [0]*(n+1)
bot_dp = [0]*(n+1)

for i in range(n):
    top_dp[i+1] = max(top_dp[i], bot_dp[i] + top[i])
    bot_dp[i+1] = max(bot_dp[i], top_dp[i] + bot[i])

ans = max(top_dp[n], bot_dp[n])
stdout.write(str(ans) + "\n")


I found an interesting problem on https://codeforces.com/problemset/problem/1195/D1:
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.

A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.

Let's denote a function that alternates digits of two numbers $f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$, where $a_1 \dots a_p$ and $b_1 \dots b_q$ are digits of two integers written in the decimal notation without leading zeros.

In other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.

For example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$

Formally,  if $p \ge q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$;  if $p < q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$.

Mishanya gives you an array consisting of $n$ integers $a_i$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$ modulo...

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

import sys
input = sys.stdin.readline

n=int(input())
A=list(input().split())
mod= 998244353

def dup(a):
    ANS=""
    for k in a:
        ANS+=k*2

    return int(ANS)

B=[dup(a) for a in A]

ANS=0
for b in B:
    ANS=(ANS+b*n)%mod

print(ANS)


I found an interesting problem on https://codeforces.com/problemset/problem/1195/D2:
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $a_1, a_2, \dots, a_n$.

A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.

Let's denote a function that alternates digits of two numbers $f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$, where $a_1 \dots a_p$ and $b_1 \dots b_q$ are digits of two integers written in the decimal notation without leading zeros.

In other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.

For example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$

Formally,  if $p \ge q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$;  if $p < q$ then $f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$.

Mishanya gives you an array consisting of $n$ integers $a_i$, your task is to help students to calculate $\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\,244\,353$.

-----Input-----

The first line of the input contains a single integer $n$ ($1 \le n \le 100\,000$) — the number of elements in the array. The second line of the input contains $n$ integers $a_1, a_2,...

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

def dig_cnt(n):
	ans = 0
	while n>=1:
		ans += 1
		n /= 10
	return ans

n = int(input())
arr = [int(x) for x in input().split()]
dig_count = [0 for _ in range(11)]
for i in arr:
	dig_count[dig_cnt(i)] += 1

ans = 0
mod = 998244353

for x in range(n):
	gv = str(arr[x])
	list_dig = []
	for i in gv:
		list_dig.append(i)
	list_dig = list_dig[::-1]
	digs = dig_cnt(arr[x])
	num = 0
	for i in gv:
		num=num*10+int(i)
		num=num*10+int(i)
	ans += num*dig_count[digs]
	for i in range(digs):
		if dig_count[i] == 0:
			continue
		num1,num2 = "",""
		zeroth = [str(0) for _ in range(i)]
		p = 0
		while p<i:
			num1 += list_dig[p]
			num1 += zeroth[p]
			p += 1
		while p < digs:
			num1 += list_dig[p]
			p += 1
		p = 0
		while p<i:
			num2 += zeroth[p]
			num2 += list_dig[p]
			p += 1
		while p < digs:
			num2 += list_dig[p]
			p += 1
		num1 = num1[::-1]
		num2 = num2[::-1]
		ans += (int(num1)+int(num2))*dig_count[i]

	for i in range(digs+1,11):
		if dig_count[i] == 0:
			continue
		num1,num2 = "",""
		zeroth = [str(0) for _ in range(i)]
		p = 0
		while p<digs:
			num1 += list_dig[p]
			num1 += zeroth[p]
			p += 1
		num1 += "0"
		p = 0
		while p<digs:
			num2 += zeroth[p]
			num2 += list_dig[p]
			p += 1
		num2 += "0"
		num1 = num1[::-1]
		num2 = num2[::-1]
		ans += (int(num1)+int(num2))*dig_count[i]

print(ans%mod)


I found an interesting problem on https://codeforces.com/problemset/problem/1195/E:
Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size $n \times m$ cells on a map (rows of grid are numbered from $1$ to $n$ from north to south, and columns are numbered from $1$ to $m$ from west to east). After that he measured the average height of each cell above Rybinsk sea level and obtained a matrix of heights of size $n \times m$. The cell $(i, j)$ lies on the intersection of the $i$-th row and the $j$-th column and has height $h_{i, j}$.

Seryozha is going to look at the result of his work in the browser. The screen of Seryozha's laptop can fit a subrectangle of size $a \times b$ of matrix of heights ($1 \le a \le n$, $1 \le b \le m$). Seryozha tries to decide how the weather can affect the recreation center — for example, if it rains, where all the rainwater will gather. To do so, he is going to find the cell having minimum height among all cells that are shown on the screen of his laptop.

Help Seryozha to calculate the sum of heights of such cells for all possible subrectangles he can see on his screen. In other words, you have to calculate the sum of minimum heights in submatrices of size $a \times b$ with top left corners in $(i, j)$ over all $1 \le i \le n - a + 1$ and $1 \le j \le m - b + 1$.

Consider the sequence $g_i = (g_{i - 1} \cdot x + y) \bmod z$. You are given integers $g_0$, $x$, $y$ and $z$. By miraculous coincidence, $h_{i, j} = g_{(i - 1) \cdot m + j - 1}$ ($(i - 1) \cdot m + j - 1$ is the index).

-----Input-----

The first line of the input contains four integers $n$, $m$, $a$ and $b$ ($1 \le n, m \le 3\,000$, $1 \le a \le n$, $1 \le b \le m$) — the number of rows and columns in the matrix Seryozha has, and the number of rows and columns that can be shown on the screen of the laptop, respectively.

The second line of the input contains four integers $g_0$, $x$, $y$ and $z$ ($0 \le g_0, x, y < z \le 10^9$).

-----Output-----

Print a single integer — the answer to the...

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/1196/A:
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.

After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.

Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).

You have to answer $q$ independent queries.

Let's see the following example: $[1, 3, 4]$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $4$ candies, and Bob has $4$ candies.

Another example is $[1, 10, 100]$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $54$ candies, and Alice takes $46$ candies. Now Bob has $55$ candies, and Alice has $56$ candies, so she has to discard one candy — and after that, she has $55$ candies too.

-----Input-----

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

The only line of the query contains three integers $a, b$ and $c$ ($1 \le a, b, c \le 10^{16}$) — the number of candies in the first, second and third piles correspondingly.

-----Output-----

Print $q$ lines. The $i$-th line should contain the answer for the $i$-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same...

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

for _ in range(int(input())):
    l=list(map(int,input().split()))
    a=sum(l)
    print(a//2)


I found an interesting problem on https://codeforces.com/problemset/problem/1196/B:
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. You want to split it into exactly $k$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $n$ elements of the array $a$ must belong to exactly one of the $k$ subsegments.

Let's see some examples of dividing the array of length $5$ into $3$ subsegments (not necessarily with odd sums): $[1, 2, 3, 4, 5]$ is the initial array, then all possible ways to divide it into $3$ non-empty non-intersecting subsegments are described below:  $[1], [2], [3, 4, 5]$;  $[1], [2, 3], [4, 5]$;  $[1], [2, 3, 4], [5]$;  $[1, 2], [3], [4, 5]$;  $[1, 2], [3, 4], [5]$;  $[1, 2, 3], [4], [5]$.

Of course, it can be impossible to divide the initial array into exactly $k$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation.

You have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Then $q$ queries follow.

The first line of the query contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of elements in the array and the number of subsegments, respectively.

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

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

-----Output-----

For each query, print the answer to it. If it is impossible to divide the initial array into exactly $k$ subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and...

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

from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 10**5+10
MOD = 10**9+7
def isprime(n):
    n = abs(int(n))
    if n < 2:
        return False
    if n == 2:
        return True
    if not n & 1:
        return False
    for x in range(3, int(n**0.5) + 1, 2):
        if n % x == 0:
            return False
    return True

def mhd(a,b):
    return abs(a[0]-b[0])+abs(b[1]-a[1])

def charIN(x= ' '):
    return(sys.stdin.readline().strip().split(x))

def arrIN(x = ' '):
    return list(map(int,sys.stdin.readline().strip().split(x)))

def eld(x,y):
    a = y[0]-x[0]
    b = x[1]-y[1]
    return (a*a+b*b)**0.5

def lgcd(a):
    g = a[0]
    for i in range(1,len(a)):
        g = math.gcd(g,a[i])
    return g

def ms(a):
    msf = -MAX
    meh = 0
    st = en = be = 0
    for i in range(len(a)):
        meh+=a[i]
        if msf<meh:
            msf = meh
            st = be
            en = i
        if meh<0:
            meh = 0
            be = i+1
    return msf,st,en

def ncr(n,r):
    num=den=1
    for i in range(r):
        num = (num*(n-i))%MOD
        den = (den*(i+1))%MOD

    return (num*(pow(den,MOD-2,MOD)))%MOD

def flush():
    return sys.stdout.flush()

'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''
for _ in range(int(input())):
    n,k = arrIN()
    a = arrIN()
    pre = list(accumulate(a))
    ans = []
    for i in range(n):
        if ans:
            if (pre[i]-pre[ans[-1]])%2:
                ans.append(i)
        else:
            if pre[i]%2:
                ans.append(i)
    #print(ans)
    if len(ans)<k:
        print('NO')
    else:
        if len(ans)==k:
            print('YES')
            print(*[i+1 for i in ans[:len(ans)-1]],n)
        else:
            ext = len(ans)-k
            if ext%2:
                print('NO')
            else:
                print('YES')
                print(*[i+1...


I found an interesting problem on https://codeforces.com/problemset/problem/1196/D1:
The only difference between easy and hard versions is the size of the input.

You are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'.

You are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there will be a string of length $k$ that is a substring of $s$, and is also a substring of the infinite string "RGBRGBRGB ...".

A string $a$ is a substring of string $b$ if there exists a positive integer $i$ such that $a_1 = b_i$, $a_2 = b_{i + 1}$, $a_3 = b_{i + 2}$, ..., $a_{|a|} = b_{i + |a| - 1}$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.

You have to answer $q$ independent queries.

-----Input-----

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

The first line of the query contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) — the length of the string $s$ and the length of the substring.

The second line of the query contains a string $s$ consisting of $n$ characters 'R', 'G' and 'B'.

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

-----Output-----

For each query print one integer — the minimum number of characters you need to change in the initial string $s$ so that after changing there will be a substring of length $k$ in $s$ that is also a substring of the infinite string "RGBRGBRGB ...".

-----Example-----
Input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR

Output
1
0
3

-----Note-----

In the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".

In the second example, the substring is "BRG".

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

R = lambda: map(int, input().split())
for _ in range(int(input())):
    n,k = R()
    s = input()
    p = (k+2)//2
    l = "RGB"*p
    res = n
    for i in range(n-k+1):
        c = 0
        #print(l[0:k])
        for j in range(0,k):
            c += (s[i+j] != l[j])
        res = min(res,c)
        #print(c)
        c = 0
        #print(l[1:k+1])
        for j in range(1,k+1):
            c += (s[i+j-1] != l[j])
        res = min(res,c)
        #print(c)
        c = 0
        #print(l[2:k+2])
        for j in range(2,k+2):
            c += (s[i+j-2] != l[j])
        res = min(res,c)
        #print(c)
    print(res)


I found an interesting problem on https://codeforces.com/problemset/problem/1196/F:
You are given a connected undirected weighted graph consisting of $n$ vertices and $m$ edges.

You need to print the $k$-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one).

More formally, if $d$ is the matrix of shortest paths, where $d_{i, j}$ is the length of the shortest path between vertices $i$ and $j$ ($1 \le i < j \le n$), then you need to print the $k$-th element in the sorted array consisting of all $d_{i, j}$, where $1 \le i < j \le n$.

-----Input-----

The first line of the input contains three integers $n, m$ and $k$ ($2 \le n \le 2 \cdot 10^5$, $n - 1 \le m \le \min\Big(\frac{n(n-1)}{2}, 2 \cdot 10^5\Big)$, $1 \le k \le \min\Big(\frac{n(n-1)}{2}, 400\Big)$ — the number of vertices in the graph, the number of edges in the graph and the value of $k$, correspondingly.

Then $m$ lines follow, each containing three integers $x$, $y$ and $w$ ($1 \le x, y \le n$, $1 \le w \le 10^9$, $x \ne y$) denoting an edge between vertices $x$ and $y$ of weight $w$.

It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices $x$ and $y$, there is at most one edge between this pair of vertices in the graph).

-----Output-----

Print one integer — the length of the $k$-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one).

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

Output
3

Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1

Output
9

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

import sys
input = sys.stdin.readline
N, M, K = list(map(int, input().split()))
X = []
for _ in range(M):
    x, y, w = list(map(int, input().split()))
    X.append([min(x,y), max(x,y), w])
X = (sorted(X, key = lambda x: x[2])+[[0, 0, 10**20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
    if x: D[x*10**6+y] = w

flg = 1
while flg:
    flg = 0
    for i in range(len(X)):
        x1, y1, w1 = X[i]
        for j in range(i+1, len(X)):
            x2, y2, w2 = X[j]
            if x1==x2: a, b = min(y1,y2), max(y1,y2)
            elif y1==y2: a, b = min(x1,x2), max(x1,x2)
            elif x1==y2: a, b = x2, y1
            elif x2==y1: a, b = x1, y2
            else: a, b = 0, 0
            if a:
                if (a*10**6+b in D and w1+w2 < D[a*10**6+b]) or (a*10**6+b not in D and w1+w2 < X[-1][2]):
                    if a*10**6+b in D:
                        for k in range(len(X)):
                            if X[k][0] == a and X[k][1] == b:
                                X[k][2] = w1+w2
                    else:
                        x, y, w = X.pop()
                        if x: D.pop(x*10**6+y)
                        X.append([a,b,w1+w2])
                    D[a*10**6+b] = w1+w2
                    X = sorted(X, key = lambda x: x[2])
                    flg = 1
print(X[-1][2])


I found an interesting problem on https://codeforces.com/problemset/problem/1197/A:
Let's denote a $k$-step ladder as the following structure: exactly $k + 2$ wooden planks, of which

  two planks of length at least $k+1$ — the base of the ladder;  $k$ planks of length at least $1$ — the steps of the ladder;

Note that neither the base planks, nor the steps planks are required to be equal.

For example, ladders $1$ and $3$ are correct $2$-step ladders and ladder $2$ is a correct $1$-step ladder. On the first picture the lengths of planks are $[3, 3]$ for the base and $[1]$ for the step. On the second picture lengths are $[3, 3]$ for the base and $[2]$ for the step. On the third picture lengths are $[3, 4]$ for the base and $[2, 3]$ for the steps.

 $H - 1 =$

You have $n$ planks. The length of the $i$-th planks is $a_i$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.

The question is: what is the maximum number $k$ such that you can choose some subset of the given planks and assemble a $k$-step ladder using them?

-----Input-----

The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of queries. The queries are independent.

Each query consists of two lines. The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the number of planks you have.

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

It's guaranteed that the total number of planks from all queries doesn't exceed $10^5$.

-----Output-----

Print $T$ integers — one per query. The $i$-th integer is the maximum number $k$, such that you can choose some subset of the planks given in the $i$-th query and assemble a $k$-step ladder using them.

Print $0$ if you can't make even $1$-step ladder from the given set of planks.

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

Output
2
1
2
0

-----Note-----

Examples for the queries $1-3$ are shown at the image in the legend section.

The Russian meme...

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

t = int(input())
for i in range(t):
    n = int(input())
    arr = [int(x) for x in input().split()]
    arr.sort(reverse=True)
    print(min(arr[1] - 1, len(arr) - 2))


I found an interesting problem on https://codeforces.com/problemset/problem/1197/B:
There are $n$ pillars aligned in a row and numbered from $1$ to $n$.

Initially each pillar contains exactly one disk. The $i$-th pillar contains a disk having radius $a_i$.

You can move these disks from one pillar to another. You can take a disk from pillar $i$ and place it on top of pillar $j$ if all these conditions are met:

  there is no other pillar between pillars $i$ and $j$. Formally, it means that $|i - j| = 1$;  pillar $i$ contains exactly one disk;  either pillar $j$ contains no disks, or the topmost disk on pillar $j$ has radius strictly greater than the radius of the disk you move.

When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.

You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $n$ disks on the same pillar simultaneously?

-----Input-----

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

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_i$ ($1 \le a_i \le n$), where $a_i$ is the radius of the disk initially placed on the $i$-th pillar. All numbers $a_i$ are distinct.

-----Output-----

Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

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

Output
YES

Input
3
3 1 2

Output
NO

-----Note-----

In the first case it is possible to place all disks on pillar $3$ using the following sequence of actions:

  take the disk with radius $3$ from pillar $2$ and place it on top of pillar $3$;  take the disk with radius $1$ from pillar $1$ and place it on top of pillar $2$;  take...

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

n = int(input())
array = list(map(int, input().split()))
ind = array.index(max(array))
i, j = ind - 1, ind + 1
now = array[ind]
while i != -1 or j != n:
    if i == -1:
        if array[j] < now:
            now = array[j]
            j += 1
        else:
            print('NO')
            return
    elif j == n:
        if array[i] < now:
            now = array[i]
            i -= 1
        else:
            print('NO')
            return
    else:
        if array[i] > array[j]:
            if array[i] < now:
                now = array[i]
                i -= 1
            else:
                print('NO')
                return
        else:
            if array[j] < now:
                now = array[j]
                j += 1
            else:
                print('NO')
                return
print('YES')


I found an interesting problem on https://codeforces.com/problemset/problem/1197/C:
You are given a sorted array $a_1, a_2, \dots, a_n$ (for each index $i > 1$ condition $a_i \ge a_{i-1}$ holds) and an integer $k$.

You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.

Let $max(i)$ be equal to the maximum in the $i$-th subarray, and $min(i)$ be equal to the minimum in the $i$-th subarray. The cost of division is equal to $\sum\limits_{i=1}^{k} (max(i) - min(i))$. For example, if $a = [2, 4, 5, 5, 8, 11, 19]$ and we divide it into $3$ subarrays in the following way: $[2, 4], [5, 5], [8, 11, 19]$, then the cost of division is equal to $(4 - 2) + (5 - 5) + (19 - 8) = 13$.

Calculate the minimum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays.

-----Input-----

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($ 1 \le a_i \le 10^9$, $a_i \ge a_{i-1}$).

-----Output-----

Print the minimum cost you can obtain by dividing the array $a$ into $k$ nonempty consecutive subarrays.

-----Examples-----
Input
6 3
4 8 15 16 23 42

Output
12

Input
4 4
1 3 3 7

Output
0

Input
8 1
1 1 2 3 5 8 13 21

Output
20

-----Note-----

In the first test we can divide array $a$ in the following way: $[4, 8, 15, 16], [23], [42]$.

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

N, K = list(map(int, input().split()))
A = [int(a) for a in input().split()]
D = sorted([A[i+1]-A[i] for i in range(N-1)])
print(A[-1]-A[0]-(sum(D[-K+1:]) if K-1 else 0))