A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets:  the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different),  the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.

# Prewritten code

import os

import sys

from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

import math

def solve():

    n = int(input())

    lst1 = list(map(int,input().split()))

    lst2 = list(map(int,input().split()))

    z1,z2 = lst1.copy(),lst2.copy()

    z1.sort()

    z2.sort()

    ans = []

    bew = []

    for i in range(n):

        ans.append(z1[i])

        bew.append(z2[i])

    print(*ans)

    print(*bew)

for i in range(int(input())):

    solve()


C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets:   a occurs at (1)(1), (2)(2), (3)(3)  b occurs at (4)(4), (5)(5)  ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5)  aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3)  bb occurs at (4,5)(4,5)  aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4)  aaa occurs at (1,2,3)(1,2,3)  abb occurs at (3,4,5)(3,4,5)  aaab occurs at (1,2,3,4)(1,2,3,4)  aabb occurs at (2,3,4,5)(2,3,4,5)  aaabb occurs at (1,2,3,4,5)(1,2,3,4,5)  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

from collections import defaultdict

s = input()

d = defaultdict(int)

for c in s:

	for a in range(97,123):

		a = chr(a)

		d[a+c]+=d[a]

	d[c]+=1

print(max(d.values()))


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

from collections import deque, defaultdict, Counter, OrderedDict

from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians

from heapq import heappush, heappop, heapify, nlargest, nsmallest

import os

import sys

#sys.setrecursionlimit(10**6)

from itertools import *

from io import BytesIO, IOBase

import math

import bisect

from math import inf

import random

def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def out(var): sys.stdout.write(str(var))  # for fast output, always take string

def lis(): return list(map(int, inp().split()))

def stringlis(): return list(map(str, inp().split()))

def sep(): return map(int, inp().split())

def strsep(): return map(str, inp().split())

def fsep(): return map(float, inp().split())

def inpu(): return int(inp())

M = 1000000007

def main():

    t=1

    #t=inpu()

    for _ in range(t):

        h,n = sep()

        arr = lis()

        c = 0

        flag = False

        ans = -1

        for i in range(n):

            c+=arr[i]

            if c+h<=0:

                ans = i+1

                flag = True

                break

        if flag:

            print(ans)

            continue

        if c>=0:

            print(-1)

            continue

        min1 = float("inf")

        temp = 0

        for i in range(n):

            temp+=arr[i]

            min1 = min(min1,temp)

        ans = 0

        while(h>=0):

            if h>abs(min1):

                p = h-abs(min1)

                x = (p+abs(c)-1)//abs(c)

                ans += x*n

                h+=(x*c)

            else:

                flag = False

                for i in range(n):

                    ans+=1

                    h+=arr[i]

                    if h<=0:

                        flag = True

                        break

                if flag:

                    print(ans)

                    break

        else:

            print(-1)

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

        self.writable = "x" in file.mode or "r" not in file.mode

        self.write = self.buffer.write if self.writable else None

    def read(self):

        while True:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            if not b:

                break

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))

            self.newlines = b.count(b"\n") + (not b)

            ptr = self.buffer.tell()

            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

            os.write(self._fd, self.buffer.getvalue())

            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

        self.write = lambda s: self.buffer.write(s.encode("ascii"))

        self.read = lambda: self.buffer.read().decode("ascii")

        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == '__main__':

    main()


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

import os,sys, threading
from random import randint, shuffle
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop, heapify
from functools import lru_cache, reduce
from itertools import accumulate, permutations
import math, copy

# sys.setrecursionlimit(2**20)
# threading.stack_size(2**20)
# sys.setrecursionlimit(0x0FFFFFFF)
# threading.stack_size(0x04000000)

# resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# MOD = 998244353
from math import *

def main():
    def solve():
        n = int(input())
        arr = list(map(int, input().split()))
        @lru_cache(None)
        def dfs(i,j,k):
            if j < 0 or i+j > n:
                return float('inf')
            if i == n:
                return 0
            res = min(dfs(i+1,j-(k%2 == 0),k), dfs(i+1,j-(k%2 == 0),k^1)+1)
            if arr[i] > 0:
                return float('inf') if k%2 != arr[i]%2 else res
            return res

        return min(dfs(0,n//2,0), dfs(0,n//2,1))

    # sys.stdin = open('contests/input', 'r')
    # print(input().split(' '))
    # t = int(input())
    t = 1
    for i in range(t):
        # n, k = list(map(int, input().split()))
        # solve()
        print(solve())
        # if solve():
        #     print("YES")
        # else:
        #     print("NO")
        # print(solve())
        # n = int(input())
        # arr = list(map(int, input().split()))
        # if solve(n, m, k):
        #     print("YES")
        # else:
        #     print("NO")

    # debug(ans)

if __name__ == "__main__":
    main()
    # threading.Thread(target=main).start()


B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows:  However, the results of the Olympiad could also look like this:  In the first case Nikolay would have taken first place, and in the second — third place.

for i in range(int(input())):

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

	if((a+b)<(n+1)):

		print(1,end=" ")

	else:

		print(min((a+b)-n+1,n),end=" ")

	print(min(a+b-1,n))


A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4
3
2 -1 -1
4
-1 0 0 1
2
-1 2
3
0 -2 1
OutputCopy1
2
0
2
NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.

def get(f): return f(input().strip())
def gets(f): return [*map(f, input().split())]

for _ in range(get(int)):
    n = get(int)
    s = 0
    z = 0
    for a in gets(int):
        s += (not a) + a
        z += not a
    print((not s) + z)


B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5


A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

q = int(input())

for i in range(q):

  w = input()

  a = [i for i in w]

  e = 0

  r = 0

  t = 0

  for i in range(len(w)):

    if w[i] == "1":

      r += e

      t = 1

      e = 0

    else:

      if t > 0:

        e += 1

  print(r)


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

# LUOGU_RID: 101916896
from fractions import Fraction

n = int(input())

s = 0

for i in range(2, n):

    t = n

    while t:

        s += t % i

        t //= i

if s % (n - 2):

    print(Fraction(s, n - 2))

else:

    print(f'{s // (n - 2)}/1')


E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements:  The score of each problem should be a positive integer not exceeding 109109.  A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109.  The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3
OutputCopy4 5 9 13 18InputCopy8 0
OutputCopy10 11 12 13 14 15 16 17
InputCopy4 10
OutputCopy-1
NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution.   (1,2,3)(1,2,3)  (1,3,4)(1,3,4)  (2,4,5)(2,4,5)

def solve(n, m):

    if m > arr[n]:

        return False, -1

    ind = None

    for i in range(1, 5001):

        if arr[i] <= m and m <= arr[i+1]:

            ind = i

            break

    ans = [i for i in range(1, ind+1)]

    if m > arr[ind]:

        ans.append(ans[-(m-arr[ind])*2]+ans[-1])

    cur  = 100000

    step = ans[-1] + 1

    while len(ans) < n:

        ans.append(cur)

        cur+=step

    return True, ans

arr  = [0]

for i in range(1, 5003):

    arr.append(arr[-1] + (i-1) // 2)

n, m = map(int, input().split())

flg, ans = solve(n, m)

if flg==False:

    print(-1)

else:

    print(' '.join([str(x) for x in ans]))


C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between 00 and n−2n−2 inclusive.  All the written labels are distinct.  The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:

import sys

from math import sqrt, gcd, factorial, ceil, floor, pi, inf

from collections import deque, Counter, OrderedDict, defaultdict

from heapq import heapify, heappush, heappop

#sys.setrecursionlimit(10**5)

from functools import lru_cache

#@lru_cache(None)

#======================================================#

input = lambda: sys.stdin.readline()

I = lambda: int(input().strip())

S = lambda: input().strip()

M = lambda: map(int,input().strip().split())

L = lambda: list(map(int,input().strip().split()))

#======================================================#

#======================================================#

def primelist():

    L = [False for i in range((10**10)+1)]

    primes = [False for i in range((10**10)+1)]

    for i in range(2,(10**10)+1):

        if not L[i]:

            primes[i]=True

            for j in range(i,(10**10)+1,i):

                L[j]=True

    return primes

def isPrime(n):

    p = primelist()

    return p[n]

#======================================================#

def bst(arr,x):

    low,high = 0,len(arr)-1

    ans = -1

    while low<=high:

        mid = (low+high)//2

        #if arr[mid]==x:

        #    return mid

        if arr[mid]<=x:

            low = mid+1

        else:

            high = mid-1

            ans = mid

    return ans

def factors(x):

    l1 = []

    l2 = []

    for i in range(1,int(sqrt(x))+1):

        if x%i==0:

            if (i*i)==x:

                l1.append(i)

            else:

                l1.append(i)

                l2.append(x//i)

    for i in range(len(l2)//2):

        l2[i],l2[len(l2)-1-i]=l2[len(l2)-1-i],l2[i]

    return l1+l2

#======================================================#

def power(n,x):

    if x==0:

        return 1

    k = (10**9)+7

    if n==1:

        return 1

    if x==1:

        return n

    ans = power(n,x//2)

    if x%2==0:

        return (ans*ans)%k

    return (ans*ans*n)%k

#======================================================#

n = I()

adj = [[] for i in range(n)]

a = [-1 for i in range(n-1)]

for _ in range(n-1):

    u,v = M()

    adj[u-1].append([v-1,_])

    adj[v-1].append([u-1,_])

if n==2:

    print(0)

else:

    c = 0

    for i in range(n):

        if len(adj[i])==1:

            a[adj[i][0][1]]=c

            c+=1

    for i in range(n-1):

        if a[i]==-1:

            a[i]=c

            c+=1

    for i in a:

        print(i)


C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.

from collections import Counter

from itertools import accumulate

t = int(input())

for _ in range(t):

    n, m = map(int, input().split())

    s = input()

    nums = list(map(int, input().split()))

    prefix = [0]*(n+1)

    for val in nums:

        prefix[0] += 1

        prefix[val] -= 1

    prefix = list(accumulate(prefix))

    cnt = Counter(s)

    ans = [0]*26

    for idx in range(n):

        ans[ord(s[idx]) - 97] += prefix[idx]

    for char in cnt:

        ans[ord(char) -97] += cnt[char]

    print(*ans)


C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1

import sys

input = sys.stdin.readline

n,m,p=map(int,input().split())

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

A=[tuple(map(int,input().split())) for i in range(m)]

M=[tuple(map(int,input().split())) for i in range(p)]

Q=[[] for i in range(10**6+1)]

for x,y,c in M:

    Q[x].append((c,y))

for x,c in W:

    Q[x-1].append((c,0))

seg_el=1<<((10**6+1).bit_length())

SEGMAX=[-1<<31]*seg_el

for x,y in A:

    SEGMAX[x-1]=max(SEGMAX[x-1],-y)

for i in range(seg_el-2,-1,-1):

    SEGMAX[i]=max(SEGMAX[i+1],SEGMAX[i])

SEGMAX=[-1<<31]*(seg_el)+SEGMAX

for i in range(seg_el-1,0,-1):

    SEGMAX[i]=max(SEGMAX[i*2],SEGMAX[(i*2)+1])

SEGADD=[0]*(2*seg_el)

def adds(l,r,x):

    L=l+seg_el

    R=r+seg_el

    while L<R:

        if L & 1:

            SEGADD[L]+=x

            L+=1

        if R & 1:

            R-=1

            SEGADD[R]+=x

        L>>=1

        R>>=1

    L=(l+seg_el)>>1

    R=(r+seg_el-1)>>1

    while L!=R:

        if L>R:

            SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)])

            L>>=1

        else:

            SEGMAX[R]=max(SEGMAX[R*2]+SEGADD[R*2],SEGMAX[1+(R*2)]+SEGADD[1+(R*2)])

            R>>=1

    while L!=0:

        SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)])

        L>>=1

ANS=-1<<31

for i in range(10**6+1):

    for c,y in Q[i]:

        if y==0:

            ANS=max(ANS,SEGMAX[1]-c)

        else:

            adds(y,seg_el,c)

print(ANS)


C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

from collections import defaultdict

from string import ascii_lowercase

test=int(input())

for _ in range(test):

    string=list(input())

    value=set(string)

    graph=defaultdict(set)

    inDegree=defaultdict(int)

    x=string[0]

    inDegree[x]=0

    for i in range(1,len(string)):

        if string[i] not in graph[x]:

            inDegree[x]+=1

        graph[x].add(string[i])

        if x not in graph[string[i]]:

            inDegree[string[i]]+=1

        graph[string[i]].add(x)

        x=string[i]

    level=[]

    visited=set()

    for i in inDegree:

        if inDegree[i]==1 or inDegree[i]==0:

            level.append(i)

            visited.add(i)

            break

    ans=[]

    while level:

        node=level.pop()

        ans.append(node)

        for val in graph[node]:

            if val not in visited:

                visited.add(val)

                inDegree[val]-=1

                if inDegree[val]==1 or inDegree[val]==0:

                    level.append(val)

    if len(value)==len(ans):

        print("YES")

        for c in ascii_lowercase:

            if c not in ans:

                ans.append(c)

        print("".join(ans))

    else:

        print("NO")


C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y);  'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y);  'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1);  'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1

test = int(input())

for t in range(test):

	n = int(input())

	s = input()

	m = {}

	x = 0

	y = 0

	c = False

	r = -1

	l = -1

	lnn = 1000000

	m[(x,y)] = 0

	for i in range(n):

		if s[i] == "R":

			x += 1

		if s[i] == "L":

			x -= 1

		if s[i] == "U":

			y += 1

		if s[i] == "D":

			y -= 1

		if (x,y) in m:

			ln = i - m[(x,y)]+1

			if ln < lnn:

				lnn = ln

				l = m[(x,y)]+1

				r = i + 1

			c = True

		m[(x,y)] = i + 1

	if not c:

		print(-1)

	else:

		print(l,r)


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

import math

import sys

import queue

import itertools

from heapq import heappop, heappush

import random

def solve():

    def n(s):

        return ord(s) - 97

    s = str(input())

    q = int(input())

    d = [[0 for i in range(len(s) + 1)] for j in range(26)]

    d[n(s[0])][1] = 1

    for i in range(1, len(s)):

        for j in range(26):

            d[j][i + 1] = d[j][i]

        d[n(s[i])][i + 1] += 1

    for _ in range(q):

        l, r = map(int, input().split())

        if r - l == 0 or s[l - 1] != s[r - 1]:

            print("Yes")

        else:

            diff = 0

            for i in range(26):

                f = d[i][r] - d[i][l - 1]

                if f != 0:

                    diff += 1

            if diff >= 3:

                print("Yes")

            else:

                print("No")

if __name__ == '__main__':

    multi_test = 0

    if multi_test:

        t = int(sys.stdin.readline())

        for _ in range(t):

            solve()

    else:

        solve()


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111

for t in range(0, int(input())):

    n  = int(input())

    count = 0

    inc = 0

    while n > 9:

        inc = n//10

        n = n%10 + inc

        count += (inc*10)

    count += n

    print(count)


B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets:  "SETT"; "TEST"; "EEET"  "TEST"; "ESTE", "STES"

# 08:58-

import sys

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

from collections import defaultdict,Counter

N,K = map(int, input().split())

A = []

for _ in range(N):

	A.append(input())

B = set(A)

# EST

ans = 0

for i in range(N-1):

	for j in range(i+1,N):

		key = []

		for k in range(K):

			if A[i][k]==A[j][k]:

				key.append(A[i][k])

			else:

				tmp = [A[i][k],A[j][k]]

				if 'S' not in tmp:

					key.append('S')

				elif 'E' not in tmp:

					key.append('E')

				else:

					key.append('T')

		key = ''.join(key)

		if key in B:

			ans+=1

print(ans//3)


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

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

q=m//n

w=0

while(m%n==0 and q%2==0):

    w+=1

    q=q//2

while(m%n==0 and q%3==0):

    w+=1

    q=q//3

if(m%n==0 and q==1):

    print(w)

else:

    print(-1)


F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const ll maxN=2e5+10;
#define pb push_back
#define int ll
#define pli pair<ll,ll>
#define fi first
#define se second
#define task "danang"
#define plii pair<ll,pli>
ll ct[maxN];
bool check(ll x)
{
    ll s=x;
    for(int i=2;i*i<=x;i++)
    {
        ll cnt=0;
        while(x%i==0)
        {
            cnt++;
            x/=i;
        }
        if(cnt>0) ct[s]++;
        if(cnt>1) return false;
    }
    if(x>1) ct[s]++;
    return true;
}
vector<ll> d[maxN];
ll cnt[maxN];
void add(ll x)
{
    for(auto zz:d[x])
    {
        cnt[zz]++;
    }
}
void del(ll x)
{
    for(auto zz:d[x])
    {
        cnt[zz]--;
    }
}
ll cal(ll x)
{
    ll ans=0;
    for(auto zz:d[x])
    {
        if(ct[zz]%2==0) ans+=cnt[zz];
        else ans-=cnt[zz];
    }
    return ans;
}
ll n,a[maxN];
vector<ll> vec[maxN];
bool c[maxN];
void solve()
{
    cin >> n;
    for(int i=1;i<=n;i++)
    {
        cin >> a[i];
        vec[a[i]].pb(i);
    }
    for(int i=1;i<=1e5;i++)
    {
        c[i]=check(i);
    }
    for(int i=1;i<=1e5;i++)
    {
        if(c[i])
        {
            for(int j=i;j<=1e5;j+=i)
            {
                d[j].pb(i);
            }
        }
    }
    vector<ll> x;
    deque<ll> dq;
    ll ans=0;
    for(int i=1;i<=1e5;i++)
    {
        x.clear();
        for(int j=i;j<=1e5;j+=i)
        {
            for(int k=0;k<min(2ll,(int)vec[j].size());k++)
            {
                x.pb(j/i);
            }
        }
        dq.clear();
        for(int j=(int)x.size()-1;j>=0;j--)
        {
            if(cal(x[j])>=1)
            {
                ll cc=cal(x[j]);
                while(dq.size()>0)
                {
                    if(__gcd(x[j],dq.back())==1)
                    {
                        cc--;
                        if(cc==0) break;
                    }
                    del(dq.back());
                    dq.pop_back();
                }
                ans=max(ans,i*x[j]*dq.back());
            }
            dq.pb(x[j]);
            add(x[j]);
        }
        for(int j=0;j<x.size();j++)
        {
            for(auto zz:d[x[j]])
            {
                cnt[zz]=0;
            }
        }
    }
    cout << ans;
}
signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    //freopen(task".inp","r",stdin);
    //freopen(task".out","w",stdout);
    solve();
}


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

#include<iostream>

#include<stdio.h>

#include<list>

#include<set>

#include<map>

#include<string>

#include<functional>

#include <cmath>

#include <cstdio>

#include <vector>

#include <algorithm>

#include<bits/stdc++.h>

using namespace std;

#define ll long long

#define forn(i,k,n) for(int i=k;i<n;i++)

int main(){

    int t;cin>>t;

    while(t--){

        int n;cin>>n;int a[n];forn(i,0,n){cin>>a[i];}

        int k=0;

        int k1=0;

        // if(n==1){cout<<"YES"<<endl;continue;}

        forn(i,0,n){

            if(a[i]%2==0){k++;}

            if(a[i]%2!=0){k1++;}

        }

        if(k==n){cout<<"YES"<<endl;continue;}

        if(k1==n){cout<<"YES"<<endl;continue;}

        else{cout<<"NO"<<endl;}

    }

    return 0;

}


C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1

#include <bits/stdc++.h>

#define int long long

#define fi first

#define se second

#define all(x) (x).begin(), (x).end()

using namespace std;

int32_t main()

{

        ios_base::sync_with_stdio(false);

        cin.tie(NULL);

        int n;

        cin >> n;

        priority_queue<int> pq;

        int ans = 0;

        for (int i = 0; i < n; i++) {

                int x;

                cin >> x;

                pq.push(x);

                pq.push(x);

                ans += pq.top() - x;

                pq.pop();

        }

        cout << ans << '\n';

        return 0;

}


D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

#include <bits/stdc++.h>

using namespace std;

#define mp make_pair

#define pb emplace_back

#define rep(i, s, e) for (int i = s; i <= e; ++i)

#define drep(i, s, e) for (int i = s; i >= e; --i)

#define file(a) freopen(#a".in", "r", stdin), freopen(#a".out", "w", stdout)

#define pv(a) cout << #a << " = " << a << endl

#define pa(a, l, r) cout << #a " : "; rep(_, l, r) cout << a[_] << ' '; cout << endl

using pii = pair <int, int>;

const int P = 1e9 + 7;

const int N = 1e5 + 10;

const int W = 32;

const int K = 400;

int read() {

  int x = 0, f = 1; char c = getchar();

  for (; c < '0' || c > '9'; c = getchar()) if (c == '-') f = -1;

  for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - 48;

  return x * f;

}

int inc(int a, int b) { return (a += b) >= P ? a - P : a; }

int dec(int a, int b) { return (a -= b) < 0 ? a + P : a; }

int mul(int a, int b) { return 1ll * a * b % P; }

int qpow(int a, int b) { int res = 1; for (; b; b >>= 1, a = mul(a, a)) if (b & 1) res = mul(res, a); return res; }

struct node {

  int dat[5];

  node() { rep(i, 0, 4) dat[i] = 0; }

  void clear() { rep(i, 0, 4) dat[i] = 0; }

  bool insert(int x) {

    drep(i, 4, 0) if (x >> i & 1) {

      if (!dat[i]) {

        dat[i] = x;

        rep(j, 0, i - 1) if (dat[j] && dat[i] >> j & 1) dat[i] ^= dat[j];

        rep(j, i + 1, 4) if (dat[j] && dat[j] >> i & 1) dat[j] ^= dat[i];

        return true;

      }

      else x ^= dat[i];

    }

    return false;

  }

  int val() {

    int res = 0;

    rep(i, 0, 4) res |= dat[i] << i * (i + 1) / 2;

    return res;

  }

} base[K], con;

int cnt, id[N], h[N], add[K][K];

void dfs(int i, node cur) {

  if (i == W) {

    if (!id[cur.val()]) id[cur.val()] = ++ cnt, base[cnt] = cur, h[cnt] = cur.val();

    return;

  }

  dfs(i + 1, cur);

  if (cur.insert(i)) dfs(i + 1, cur);

}

int join(int u, int v) {

  if (~add[u][v]) return add[u][v];

  node s = base[u], t = base[v];

  rep(i, 0, 4) if (t.dat[i]) {

    if (!s.insert(t.dat[i])) return add[u][v] = add[v][u] = 0;

  }

  return id[s.val()];

}

int n, m, d[N], f[K], g[K], ans, v1[N], v2[N];

vector <pii> e[N];

map <int, int> E[N];

bool tag[N];

int fa[N];

int get(int u) { return u == fa[u] ? u : fa[u] = get(fa[u]); }

void merge(int u, int v) { fa[get(v)] = get(u); }

bool dfs0(int u, int fa) {

  tag[u] = true;

  bool flag = true;

  for (auto [v, w] : e[u]) if (v != 1 && v != fa) {

    if (!tag[v]) d[v] = d[u] ^ w, flag &= dfs0(v, u);

    else if (u < v) flag &= con.insert(d[u] ^ d[v] ^ w);

  }

  return flag;

}

int main() {

  dfs(0, node());

  rep(i, 1, cnt) rep(j, 1, cnt) add[i][j] = -1;

  n = read(), m = read();

  rep(i, 1, n) fa[i] = i;

  rep(i, 1, m) {

    int u = read(), v = read(), w = read();

    e[u].pb(mp(v, w)), e[v].pb(mp(u, w));

    E[u][v] = E[v][u] = w;

    if (u > 1 && v > 1) merge(u, v);

  }

  tag[1] = true, f[1] = 1;

  for (auto [r, w] : e[1]) {

    if (!v1[get(r)]) v1[get(r)] = r;

    else v2[get(r)] = r;

  }

  rep(r, 1, n) if (v1[r]) {

    if (!v2[r]) {

      int u = v1[r];

      if (dfs0(u, 1)) {

        int p = id[con.val()];

        fill(g, g + K, 0);

        rep(i, 1, cnt) {

          g[i] = inc(g[i], f[i]);

          if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], f[i]);

        }

        swap(f, g);

      }

      con.clear();

    }

    else {

      int u = v1[r], v = v2[r];

      fill(g, g + K, 0);

      rep(i, 1, cnt) g[i] = inc(g[i], f[i]);

      if (dfs0(u, 1)) {

        int p = id[con.val()];

        rep(i, 1, cnt) {

          if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], inc(f[i], f[i]));

        }

        if (con.insert(E[1][u] ^ E[1][v] ^ E[u][v])) {

          int p = id[con.val()];

          rep(i, 1, cnt) {

            if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], f[i]);

          }

        }

      }

      con.clear(), swap(f, g);

    }

  }

  rep(i, 1, cnt) ans = inc(ans, f[i]);

  printf("%d\n", ans);

  return 0;

}


A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5
2
2 3
4
2 2 8 8
3
3 3 3
4
5 5 5 5
4
1 1 1 1
OutputCopyYES
NO
YES
NO
NO

#include<bits/stdc++.h>

using namespace std;

int main(){

  int t;

  cin>>t;

  while(t--){

  int x;

  cin>>x;

  int a[x];

  int flag=0;

  int del=0;

  for(int i=0;i<x;++i){

    cin>>a[i];

    if(a[i]%2!=0)

    flag=1;

    if(a[i]%2==0)

    del=1;

   }

  if(x%2!=0 && flag==1)

  cout<<"YES";

  else if(x%2==0 && del==1 && flag==1)

   cout<<"YES";

  else

  cout<<"NO";

   cout<<endl;

  }

}


C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can:   either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define mod 1000000007ll

bool inPowerOfK(ll num, int k, bool vis[]){
    int bit = 0;
    while(num){
        if(num % k > 1) return false;
        if(num % k == 1) {
            if(!vis[bit]) vis[bit] = true;
            else return false;
        }
        num /= k;
        bit++;
    }
    return true;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t; cin >> t;
    while(t--){
        bool vis[60] = {false};
        int n, k; cin >> n >> k;
        ll arr[n];
        bool ans = true;
        for(int i = 0; i < n; i++) cin >> arr[i];
        for(int i = 0; i < n; i++){
            if(!inPowerOfK(arr[i], k, vis))
                {ans = false; break;}
        }
        if(ans) cout << "YES\n";
        else cout << "NO\n";
    }
}


E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n−1n−1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n−1n−1 ai=median(bi−1,bi,bi+1)ai=median(bi−1,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1≤n≤5000001≤n≤500000) — the number of mountains.The second line contains integers a1,a2,a3,…,ana1,a2,a3,…,an (1≤ai≤1091≤ai≤109) — current heights of the mountains.OutputIn the first line print cc — the number of alignments, which change the height of at least one mountain.In the second line print nn integers — the final heights of the mountains after cc alignments.ExamplesInputCopy5
1 2 1 2 1
OutputCopy2
1 1 1 1 1
InputCopy6
1 3 2 5 4 6
OutputCopy1
1 2 3 4 5 6
InputCopy6
1 1 2 2 1 1
OutputCopy0
1 1 2 2 1 1
NoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00.

#include <bits/stdc++.h>

#define int long long
using namespace std;
const int N = 5e5 + 5;
const int LOG = 20;
int n, type, res, a[N], b[N], lg[N], mn[LOG][N], mx[LOG][N];

pair<int, int> get(int l, int r) {
    int LG = lg[r - l];
    return {min(mn[LG][l], mn[LG][r - (1 << LG)]), max(mx[LG][l], mx[LG][r - (1 << LG)])};
}

void precalc() {
    for (int i = 2; i < N; i++) {
        lg[i] = lg[i / 2] + 1;
    }
    for (int i = 0; i <= n; i++) {
        mn[0][i] = max(a[i], a[i + 1]);
        mx[0][i] = min(a[i], a[i + 1]);
    }
    for (int i = 0; i < LOG - 1; i++) {
        for (int j = 0; j <= n - (1 << i); j++) {
            mn[i + 1][j] = min(mn[i][j], mn[i][j + (1 << i)]);
            mx[i + 1][j] = max(mx[i][j], mx[i][j + (1 << i)]);
        }
    }
}

signed main() {
    cin >> n;
    type = 1;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    a[0] = a[1], a[n + 1] = a[n];
    precalc();
    for (int i = 1; i <= n; i++) {
        int l = 1, r = min(n + 1 - i, i), cnt = 0;
        int pff = 400;
        while (l <= r && pff--) {
            int m = (l + r) / 2;
            auto t = get(i - m, i + m);
            if (t.first <= t.second) {
                r = m - 1;
                cnt = m;
            }
            else {
                l = m + 1;
            }
        }
        if (!type)
            continue;
        if (cnt == 1) {
            b[i] = a[i];
        } else {
            auto got = get(i - cnt, i + cnt);
            if (a[i] > a[i - 1]) {
                if (cnt % 2 == 0) {
                    b[i] = got.second;
                } else {
                    b[i] = got.first;
                }
            } else {
                if (cnt % 2 == 1) {
                    b[i] = got.second;
                } else {
                    b[i] = got.first;
                }
            }
        }
        res = max(res, cnt - 1);
    }
    cout << res << '\n';
    if (type == 1) {
        for (int i = 1; i <= n; i++) {
            cout << b[i] << ' ';
        }
    }
    return 0;
}


E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1:  After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1≤n≤1500001≤n≤150000).The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer  — the answer to the ii-th question.ExamplesInputCopy5
2 4 1 5 3
OutputCopy1
3
6
8
11
InputCopy6
1 2 4 5 6 3
OutputCopy1
3
6
8
12
17
NoteAfter the first round; the sequence is 11. The tree is  The answer is 11.After the second round, the sequence is 2,12,1. The tree is  The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is  The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is  The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is  The answer is 1+3+1+5+1=111+3+1+5+1=11.

#include<bits/stdc++.h>

using namespace std;
int n,a[150003],_[150003];
struct BIT{
int dat[150003];
void init(){
memset(dat,0,sizeof(dat));
}
int query(int x){
int ret=0;
while(x){
ret+=dat[x];
x^=(x&-x);
}return ret;
}
void add(int x,int y){
while(x<=n){
dat[x]+=y;
x+=(x&-x);
}
}
}tr1,tr2;
long long sum;
void add1(int x,int y){
tr1.add(x,y);
sum+=1ll*tr2.query(n+1-x)*y;
}
void add2(int x,int y){
sum+=1ll*tr1.query(x)*y;
tr2.add(n+1-x,y);
}
struct sgt{
int mn[524288],mc[524288],sn[524288],lzy[524288];
void init(){
sum=0;
memset(mn,31,sizeof(mn));
memset(mc,0,sizeof(mc));
memset(sn,31,sizeof(sn));
memset(lzy,-1,sizeof(lzy));
}
void pushtag(int k,int val,bool tp){
if(mn[k]>=val)
return;
if(tp){
add1(mn[k],-mc[k]);
add1(val,mc[k]);
}
mn[k]=val;
lzy[k]=val;
}
void pushdown(int k){
pushtag(k<<1,lzy[k],0);
pushtag(k<<1|1,lzy[k],0);
lzy[k]=0;
}
void pushup(int k){
if(mn[k<<1]<mn[k<<1|1]){
mn[k]=mn[k<<1];
mc[k]=mc[k<<1];
sn[k]=min(sn[k<<1],mn[k<<1|1]);
}
if(mn[k<<1]==mn[k<<1|1]){
mn[k]=mn[k<<1];
mc[k]=mc[k<<1]+mc[k<<1|1];
sn[k]=min(sn[k<<1],sn[k<<1|1]);
}
if(mn[k<<1]>mn[k<<1|1]){
mn[k]=mn[k<<1|1];
mc[k]=mc[k<<1|1];
sn[k]=min(mn[k<<1],sn[k<<1|1]);
}
}
void add(int k){
k+=262144;
int tk=k;vector<int>v;tk>>=1;
while(tk)v.push_back(tk),tk>>=1;
while(v.size())pushdown(v.back()),v.pop_back();
mn[k]=1;mc[k]=1;
add1(1,1);
k>>=1;
while(k){
pushup(k);
k>>=1;
}
}
void modify(int l,int r,int _l,int _r,int k,int val){
if(l>_r||r<_l||val<=mn[k])return;
if(_l<=l&&r<=_r&&val<sn[k]){
pushtag(k,val,1);
return;
}
pushdown(k);
modify(l,l+r>>1,_l,_r,k<<1,val);
modify(l+r+1>>1,r,_l,_r,k<<1|1,val);
pushup(k);
}
}TR;
long long ans[150003];
int main(){
cin>>n;
for(int i=0;i<n;i++)
cin>>_[i],a[_[i]-1]=i+1;
for(int i=0;i<2;i++){
tr1.init();tr2.init();TR.init();sum=0;
for(int j=0;j<n;j++){
if(a[j]!=n)
TR.modify(0,262143,a[j]+1,n,1,a[j]+1);
TR.add(a[j]);
add2(a[j],1);
ans[j]+=sum;
a[j]=n+1-a[j];
}
}
for(int i=0;i<n;i++)
cout<<ans[i]-1ll*(i+1)*(i+1)<<'\n';
}


F. Red-Blue Graphtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph: the first part of this graph contains n1n1 vertices, the second part contains n2n2 vertices, and there are mm edges. The graph can contain multiple edges.Initially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs rr coins) or paint it blue (it costs bb coins). No edge can be painted red and blue simultaneously.There are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours:  for each red vertex, the number of red edges indicent to it should be strictly greater than the number of blue edges incident to it;  for each blue vertex, the number of blue edges indicent to it should be strictly greater than the number of red edges incident to it. Colorless vertices impose no additional constraints.Your goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost. InputThe first line contains five integers n1n1, n2n2, mm, rr and bb (1≤n1,n2,m,r,b≤2001≤n1,n2,m,r,b≤200) — the number of vertices in the first part, the number of vertices in the second part, the number of edges, the amount of coins you have to pay to paint an edge red, and the amount of coins you have to pay to paint an edge blue, respectively.The second line contains one string consisting of n1n1 characters. Each character is either U, R or B. If the ii-th character is U, then the ii-th vertex of the first part is uncolored; R corresponds to a red vertex, and B corresponds to a blue vertex.The third line contains one string consisting of n2n2 characters. Each character is either U, R or B. This string represents the colors of vertices of the second part in the same way.Then mm lines follow, the ii-th line contains two integers uiui and vivi (1≤ui≤n11≤ui≤n1, 1≤vi≤n21≤vi≤n2) denoting an edge connecting the vertex uiui from the first part and the vertex vivi from the second part.The graph may contain multiple edges.OutputIf there is no coloring that meets all the constraints, print one integer −1−1.Otherwise, print an integer cc denoting the total cost of coloring, and a string consisting of mm characters. The ii-th character should be U if the ii-th edge should be left uncolored, R if the ii-th edge should be painted red, or B if the ii-th edge should be painted blue. If there are multiple colorings with minimum possible cost, print any of them.ExamplesInputCopy3 2 6 10 15
RRB
UB
3 2
2 2
1 2
1 1
2 1
1 1
OutputCopy35
BUURRU
InputCopy3 1 3 4 5
RRR
B
2 1
1 1
3 1
OutputCopy-1
InputCopy3 1 3 4 5
URU
B
2 1
1 1
3 1
OutputCopy14
RBB

// LUOGU_RID: 101653663
#include<bits/stdc++.h>

using namespace std;

const int INF=2147483647;

struct Edge

{

	int to;

	int nxt;

	int flow;

	int cost;

}e[10005];

int n1,n2,m,r,b,s,t,ss,tt,edgenum=1,head[505],dis[505],a[505],pre[505],d[505];

char s1[505],s2[505];

bool flag[1005];

queue<int>q;

void add(int u,int v,int f,int c)

{

	e[++edgenum].cost=c;

	e[edgenum].flow=f;

	e[edgenum].to=v;

	e[edgenum].nxt=head[u];

	head[u]=edgenum;

}

bool SPFA()

{

	while(!q.empty()) q.pop();

	for(int i=1;i<=t;i++)dis[i]=INF,a[i]=0,flag[i]=0;

	q.push(s);

	dis[s]=0;

	a[s]=INF;

	flag[s]=1;

	while(!q.empty())

	{

		int node=q.front();

		q.pop();

		flag[node]=0;

		for(int hd=head[node];hd;hd=e[hd].nxt)

		{

			if(e[hd].flow==0)continue;

			int to=e[hd].to;

			if(dis[to]>dis[node]+e[hd].cost)

			{

				dis[to]=dis[node]+e[hd].cost;

				a[to]=min(a[node],e[hd].flow);

				pre[to]=hd;

				if(!flag[to])

				{

					q.push(to);

					flag[to]=1;

				}

			}

		}

	}

	return dis[t]<INF;

}

int EK1()

{

	int ans=0;

	while(SPFA())

	{

		ans+=dis[t]*a[t];

		int x=t;

		while(x!=s)

		{

			int hd=pre[x];

			e[hd].flow-=a[t];

			e[hd^1].flow+=a[t];

			x=e[hd^1].to;

		}

	}

	return ans;

}

int EK2()

{

	int ans=0;

	while(SPFA())

	{

		if(dis[t]>=0)break;

		ans+=dis[t]*a[t];

		int x=t;

		while(x!=s)

		{

			int hd=pre[x];

			e[hd].flow-=a[t];

			e[hd^1].flow+=a[t];

			x=e[hd^1].to;

		}

	}

	return ans;

}

int main()

{

	scanf("%d%d%d%d%d",&n1,&n2,&m,&r,&b);

	ss=n1+n2+1;

	tt=ss+1;

	s=tt+1;

	t=s+1;

	scanf("%s%s",s1+1,s2+1);

	for(int i=1;i<=m;i++)

	{

		int u,v;

		scanf("%d%d",&u,&v);

		d[u]++,d[v+n1]++;

		add(u,v+n1,1,-r);

		add(v+n1,u,0,r);

		add(u,v+n1,1,b);

		add(v+n1,u,0,-b);

	}

	for(int i=1;i<=n1;i++)

	{

		if(s1[i]=='U')

		{

			add(ss,i,2*d[i],0);

			add(i,ss,0,0);

		}

		if(s1[i]=='R')

		{

			add(ss,i,d[i]-1,0);

			add(i,ss,0,0);

		}

		if(s1[i]=='B')

		{

			add(ss,i,d[i]-1,0);

			add(i,ss,0,0);

			add(s,i,d[i]+1,0);

			add(i,s,0,0);

			add(ss,t,d[i]+1,0);

			add(t,ss,0,0);

		}

	}

	for(int i=1;i<=n2;i++)

	{

		if(s2[i]=='U')

		{

			add(i+n1,tt,2*d[i+n1],0);

			add(tt,i+n1,0,0);

		}

		if(s2[i]=='R')

		{

			add(i+n1,tt,d[i+n1]-1,0);

			add(tt,i+n1,0,0);

		}

		if(s2[i]=='B')

		{

			add(i+n1,tt,d[i+n1]-1,0);

			add(tt,i+n1,0,0);

			add(s,tt,d[i+n1]+1,0);

			add(tt,s,0,0);

			add(i+n1,t,d[i+n1]+1,0);

			add(t,i+n1,0,0);

		}

	}

	add(tt,ss,INF,0);

	add(ss,tt,0,0);

	int ans=r*m;

	for(int i=2;i<edgenum;i+=2)

	{

		if(e[i].cost<0&&e[i].flow)

		{

			add(s,e[i].to,e[i].flow,0);

			add(e[i].to,s,0,0);

			add(e[i^1].to,t,e[i].flow,0);

			add(t,e[i^1].to,0,0);

			ans+=e[i].cost*e[i].flow;

			e[i^1].flow=e[i].flow,e[i].flow=0;

		}

	}

	ans+=EK1();

	for(int hd=head[s];hd;hd=e[hd].nxt)

	{

		if(e[hd].flow)

		{

			printf("-1\n");

			return 0;

		}

	}

	for(int hd=head[s];hd;hd=e[hd].nxt)

	{

		e[hd].flow=e[hd^1].flow=0;

	}

	for(int hd=head[t];hd;hd=e[hd].nxt)

	{

		e[hd].flow=e[hd^1].flow=0;

	}

	ans+=EK2();

	printf("%d\n",ans);

	for(int i=1;i<=m;i++)

	{

		if(e[4*i-2].flow==1)putchar('R');

		else if(e[4*i].flow==1)putchar('U');

		else putchar('B');

	}

	return 0;

}


F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either:  find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:

#include<bits/stdc++.h>

using namespace std;
enum{N=200001};
basic_string<int>G[N],a,b;
int n,m,u,v,ok[N],dep[N];
void dfs(int u){
a+=u,dep[u]=a.size();
for(int v:G[u])
if(!dep[v])dfs(v);
else if(dep[u]-dep[v]+1>=n){
cout<<"2\n"<<dep[u]-dep[v]+1<<'\n';
for(int i=dep[v]-1;i<dep[u];++i)cout<<a[i]<<' ';
exit(0);
}
if(!ok[u]){
b+=u;
for(int v:G[u])ok[v]=1;
}
a.pop_back();
}
main(){
cin>>n>>m,n=sqrt(n-1)+1;
while(m--)cin>>u>>v,G[u]+=v,G[v]+=u;
dfs(1);
puts("1");
for(m=0;m<n;++m)cout<<b[m]<<' ';
}


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

#include <bits/stdc++.h>

using i64 = long long;

int main() {

	std::ios::sync_with_stdio(false);

	std::cin.tie(nullptr);

	int n, h, l, r;

	std::cin >> n >> h >> l >> r;

	std::vector<int> a(n);

	for (int i = 0; i < n; i++) {

		std::cin >> a[i];

	}

	std::vector<int> dp(h + 1);

	std::vector<int> vis(h);

	vis[0] = true;

	for (int i = 0; i < n; i++) {

		std::vector<int> ndp(h), nvis(h);

		for (int j = 0; j < h; j++) {

			if (vis[j]) {

				int x = (j + a[i]) % h, y = (x - 1 + h) % h;

				ndp[x] = std::max(ndp[x], dp[j] + (x >= l && x <= r));

				ndp[y] = std::max(ndp[y], dp[j] + (y >= l && y <= r));

				nvis[x] = nvis[y] = true;

			}

		}

		std::swap(nvis, vis);

		std::swap(ndp, dp);

	}

	std::cout << *max_element(dp.begin(), dp.end()) << "\n";

	return 0;

}