B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

#  If you win, you live. You cannot win unless you fight.

from math import  sin

from sys import stdin,setrecursionlimit

input=stdin.readline

import heapq

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

ri=lambda: int(input())

rs=lambda :input().strip()

from collections import defaultdict as unsafedict,deque,Counter as unsafeCounter

from bisect import bisect_left as bl, bisect_right as br

from random import randint

random = randint(1, 10 ** 9)

mod=998244353

def ceil(a,b):

    return (a+b-1)//b

class myDict:

    def __init__(self,func):

        self.RANDOM = randint(0,1<<32)

        self.default=func

        self.dict={}

    def __getitem__(self,key):

        myKey=self.RANDOM^key

        if myKey not in self.dict:

            self.dict[myKey]=self.default()

        return self.dict[myKey]

    def get(self,key,default):

        myKey=self.RANDOM^key

        if myKey not in self.dict:

            return default

        return self.dict[myKey]

    def __setitem__(self,key,item):

        myKey=self.RANDOM^key

        self.dict[myKey]=item

    def getKeys(self):

        return [self.RANDOM^i for i in self.dict]

    def __str__(self):

        return f'{[(self.RANDOM^i,self.dict[i]) for i in self.dict]}'

from math import prod

'''

x*ts+y==m

(m-y)%ts==0

type 2

x*ts-x==m

'''

def samepar(a,b):

    return (a>=0 and b>=0) or (a<=0 and b<=0)

for _ in range(ri()):

    n,m=rd()

    s=rs()

    ts=s.count("0")-s.count("1")

    if ts==0:

        x=0

        ans=0

        for i in s:

            if i=="0":

                x+=1

            else:

                x-=1

            if x==m:

                ans+=1

        if ans:

            print(-1)

        else:

            print(0)

        continue

    ans=0

    y=0

    st=set()

    if (m%ts)==0 and samepar(m,ts) :

        # print("here ",m ,ts)

        st.add((m//ts,n-1))

    for i in range(n-1):

        if s[i]=="1":

            y-=1

        else:

            y+=1

        if (m-y)%ts==0:

            if (m-y)//ts>=0:

                # print(m - y, y, (m - y) // ts)

                st.add(((m-y)//ts,i))

            ans+=1

    # print(st)

    print(len(st))


A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3
1 1
4 5
5 11
OutputCopyYES
YES
NO
NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.

#Это кстати моя самая первая решенная задача на кодфорсес раунде (13 попыток 1ч18мин)

import math

t = int(input())

for i in range(t):

    n, d = input().split()

    n = int(n)

    d = int(d)

    c = 0

    for x in range(n):

        if(x + math.ceil(d/(x + 1)) <= n):

            print("YES")

            c += 1

            break

    if c == 0:

        print("NO")


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

for _ in range(int(input())):
    print(
        "YES"
        if all(ai == ci or bi == ci for ai, bi, ci in zip(input(), input(), input()))
        else "NO"
    )


D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0

import os, sys

from io import BytesIO, IOBase

from array import array

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, 8192))

            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, 8192))

            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().strip()

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

Int = lambda: int(input())

def queryInteractive(a, b, c):

    print('? {} {} {}'.format(a, b, c))

    sys.stdout.flush()

    return int(input())

def answerInteractive(x1, x2):

    print('! {} {}'.format(x1, x2))

    sys.stdout.flush()

inf = float('inf')

pow2 = [1]

for _ in range(30):

    pow2.append(2 * pow2[-1])

dic = {pow2[i]:i for i in range(30)}

T = Int()

while T:

    T -= 1

    n, m = ints()

    arr = ints()

    if sum(arr) < n:

        print(-1)

        continue

    l = [0] * 61

    for x in arr:

        l[dic[x]] += 1

    ans = 0

    i = 0

    while i < 60:

        if (n>>i)&1:

            if l[i] > 0:

                l[i] -= 1

            else:

                while l[i] == 0:

                    i += 1

                    ans += 1

                l[i] -= 1

                continue

        l[i+1] += l[i]//2

        i += 1

    print(ans)


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

import os, sys

from io import BytesIO, IOBase

from math import log2, ceil, sqrt, gcd

from _collections import deque

import heapq as hp

from bisect import bisect_left, bisect_right

from math import cos, sin

from itertools import permutations

from operator import itemgetter

# sys.setrecursionlimit(2*10**5+10000)

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")

def update(i, vl, x):

    i += x

    tree[i] += vl

    while i:

        tree[i >> 1] = tree[i] + tree[i ^ 1]

        i >>= 1

def query(l, r, x):

    l += x

    r += x

    ans = 0

    while l < r:

        if l & 1:

            ans += tree[l]

            l += 1

        if r & 1:

            r -= 1

            ans += tree[r]

        l >>= 1

        r >>= 1

    return ans

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

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

tree = [0] * (2 * n + 5)

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

for i in a:

    ans[i][0] = 1

    if tree[i + n + 1] == 0:

        x = query(i, n + 1, n + 1)

        ans[i][1] = x + i

        update(i, 1, n + 1)

tree = [0] * (2 * m + 5)

v = [-1] * (n + 1)

for i, vl in enumerate(a):

    if v[vl] == -1:

        v[vl] = i

        update(i, 1, m)

    else:

        x = query(v[vl], i, m)

        ans[vl][1] = max(ans[vl][1], x)

        update(v[vl], -1, m)

        update(i, 1, m)

        v[vl] = i

ct = n

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

    if v[i] == -1:

        ans[i][1] = max(ans[i][1], ct)

        ct -= 1

ck = []

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

    if v[i] != -1:

        ck.append([v[i], i])

ck.sort()

for vl, i in ck:

    ans[i][1] = max(ans[i][1], ct)

    ct -= 1

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

    print(*ans[i])


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

def main():

    t = int(input())

    for _ in range(t):

        _ = int(input())

        a = [int(i) for i in input().split()]

        o, e = 0, 0

        for x in a:

            if x % 2:

                o += 1

            else:

                e += 1

        s = sum(a)

        if s % 2:

            print("YES")

        else:

            if o != 0 and e != 0:

                print("YES")

            else:

                print("NO")

if __name__ == "__main__":

    main()


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

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

out, max_ = [], 4 * n * m - 2 * n - 2 * m

if k > max_:

    exit(print('NO'))

for i in range(n - 1):

    if m > 1:

        cur = 'DUR' if i & 1 == 0 else 'DUL'

        out.append(f'{m - 1} {cur}')

    out.append('1 D')

if m > 1:

    ch = 'R' if n & 1 else 'L'

    out.append(f'{m - 1} {ch}')

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

    if m > 1:

        ch = 'L' if i & 1 else 'R'

        out.append(f'{m - 1} {ch}')

    if i > 1:

        out.append('1 U')

out2 = ['YES', '0']

for i in out:

    num, pat = i.split()

    num = int(num)

    if num * len(pat) >= k:

        div, mod = divmod(k, len(pat))

        if div:

            out2.append(f'{div} {pat}')

        if mod:

            out2.append(f'1 {pat[:mod]}')

        break

    k -= num * len(pat)

    out2.append(i)

out2[1] = str(len(out2) - 2)

print('\n'.join(out2))


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.

def helper(a):

    s=set()

    for i in range(n):

        c=0

        while a[i]>0:

            while a[i]%k==0:

                a[i]//=k

                c+=1

            if a[i]%k==1:

                a[i]-=1

            else:return "NO"

            if c in s:return "NO"

            else:s.add(c)

    return "YES"

import sys

input=sys.stdin.readline

t=int(input())

for _ in range(t):

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

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

    print(helper(a))


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

from math import *

from collections import *

import os

from io import BytesIO, IOBase

import sys

from bisect import *

from heapq import *

MOD = 1000000007

# Code by Big Dick Daddy Dick

def binpow(a, b, m):

    a %= m

    x = 1

    while b > 0:

        if b & 1:

            x = x * a % m

        a = a * a % m

        b >>= 1

    return x

def binser(arr, l, r, x):

    while l < r:

        mid = l + (r - l) // 2

        # print(l, r, mid)

        if arr[mid] == x:

            return mid

        elif arr[mid] < x:

            l = mid + 1

        else:

            r = mid - 1

    return mid

def lcm(a, b):

    return (a * b) // gcd(a, b)

def sod(n):

    l = list(str(n))

    s = 0

    for i in l:

        s += int(i)

    return s

def prime_factors(num):

    l =[]

    if num % 2:

        l.append(2)

    while num % 2 == 0:

        num = num / 2

    for i in range(3, int(sqrt(num)) + 1, 2):

        if not num % i:

            l.append(i)

        while num % i == 0:

            num = num / i

    if num > 2:

        l.append(num)

    return l

def factmod(n, p):

    f = defaultdict(int)

    f[0] = 1

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

        f[i] = (f[i-1] * i) % MOD

    """

    res = 1

    while (n > 1):

        if (n//p) % 2:

            res = p - res

        res = res * f[n%p] % p

        n //= p

    """

    return f

def largestPower(n, p):

    # Initialize result

    x = 0

    # Calculate x = n/p + n/(p^2) + n/(p^3) + ....

    while (n):

        n //= p

        x += n

    return x

def modFact(n, p) :

    if (n >= p) :

        return 0

    res = 1

    isPrime = [1] * (n + 1)

    i = 2

    while(i * i <= n):

        if (isPrime[i]):

            for j in range(2 * i, n, i) :

                isPrime[j] = 0

        i += 1

    # Consider all primes found by Sieve

    for i in range(2, n):

        if (isPrime[i]) :

            k = largestPower(n, i)

            # Multiply result with (i^k) % p

            res = (res * binpow(i, k, p)) % p

    return res

def drec(x, y):

    if y == x + 1:

        return 'R'

    if y == x - 1:

        return 'L'

    if x < y:

        return 'D'

    return 'U'

def cellhash(x, y):

    return (x - 1) * m + y

def bfs(src, dest):

    q = deque([src])

    vis[src] = True

    while q:

        i = q.popleft()

        if i == dest:

            return True

        for j in ajl[i]:

            if not vis[j]:

                vis[j] = True

                q.append(j)

    return False

def bins(l, x, n):

    i = bisect_left(l, x)

    if i < n:

        return i

    if i:

        return (i-1)

    else:

        return n

def cond(l):

    for i in range(len(l) - 1):

        if l[i] == str(int(l[i + 1]) - 1):

            return False

    return True

def isvowel(s):

    if s in list("aeiou"):

        return 1

    return 0

def countOdd(L, R):

    N = (R - L) // 2

    # if either R or L is odd

    if (R % 2 != 0 or L % 2 != 0):

        N += 1

    return N

def tst(A, B, C):

    return ((A|B) & (B|C) & (C|A))

def palcheck(n, s):

    i, j = 0, n - 1

    while i <= j:

        if s[i] == s[j]:

            return False

        i += 1

        j -= 1

    return True

def sakurajima(n):

    if n < 9:

        n = 10

    l = [1] * (n + 1)

    l[1] = 0

    for i in range(2, int(n ** 0.5) + 1):

        if l[i]:

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

                if not j % i:

                    l[j] = 0

    return l

def prchck(n):

    l = [1] * (n + 1)

    l[1] = 0

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

        for j in range(2, int(sqrt(n)) + 1):

            if j % i == 0:

                l[j] = 1

    return l

def ispal(s, n):

    for i in range(n // 2):

        if s[i] != s[n - i - 1]:

            return False

    return True

def dfs(i, tmp, vis):

    vis[i] = True

    if i == int(i):

        for j in range(cnt[i]):

            tmp.append(i)

    for j in ajl[i]:

        if not vis[j]:

            tmp = dfs(j, tmp, vis)

    return tmp

def panda(n, s):

	x, y = '0', '0'

	ans = ['0'] * n

	for i in range(n):

		if s[i] >= x:

			ans[i] = '1'

			x = s[i]

		elif s[i] >= y:

			y = s[i]

		else:

			return "NO"

	print("YES")

	return "".join(ans)

# Code by Big Dick Daddy Dick

# n = int(input())

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

# s = input()

# l = list(map(int, input().split()))

# memo = [[-1 for i in range(n + 1)] for j in range(2)]

input = sys.stdin.readline

t = 1

# t = int(input())

for _ in range(t):

    n = int(input())

    s = input()

    print(panda(n, s))

    # print("Case #" + str(_ + 1) + ": " + str(ans))


C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation:   z=acacez=acace (if we choose subsequence aceace);  z=acbcdz=acbcd (if we choose subsequence bcdbcd);  z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3

import sys, threading

import math

from os import path

from collections import defaultdict, Counter, deque

from bisect import *

from string import ascii_lowercase

from functools import cmp_to_key

import heapq

def readInts():

    x = list(map(int, (sys.stdin.readline().rstrip().split())))

    return x[0] if len(x) == 1 else x

def readList(type=int):

    x = sys.stdin.readline()

    x = list(map(type, x.rstrip('\n\r').split()))

    return x

def readStr():

    x = sys.stdin.readline().rstrip('\r\n')

    return x

write = sys.stdout.write

read = sys.stdin.readline

MAXN = 1123456

class mydict:

    def __init__(self, func):

        self.random = randint(0, 1 << 32)

        self.default = func

        self.dict = {}

    def __getitem__(self, key):

        mykey = self.random ^ key

        if mykey not in self.dict:

            self.dict[mykey] = self.default()

        return self.dict[mykey]

    def get(self, key, default):

        mykey = self.random ^ key

        if mykey not in self.dict:

            return default

        return self.dict[mykey]

    def __setitem__(self, key, item):

        mykey = self.random ^ key

        self.dict[mykey] = item

    def getkeys(self):

        return [self.random ^ i for i in self.dict]

    def __str__(self):

        return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'

def lcm(a, b):

    return (a*b)//(math.gcd(a,b))

def mod(n):

    return n%(1000000000 + 7)

def upper_bound(a, num):

     l = 0

     r = len(a)-1

     ans = -1

     while l <= r:

         mid = (l+r)//2

         if a[mid] > num:

             ans = mid

             r = mid-1

         else:

             l = mid+1

     return ans

def solve(t):

    # print(f'Case #{t}: ', end = '')

    a = readStr()

    b = readStr()

    cnt = 1

    mpind = defaultdict(list)

    for i, c in enumerate(a):

        mpind[c].append(i)

    j = 0

    lind = -1

    for c in b:

        ui = upper_bound(mpind[c], lind)

        if ui == -1:

            lind = -1

            ui = upper_bound(mpind[c], lind)

            cnt += 1

        if ui == -1 and lind == -1:

            print(-1)

            return

        else:

            lind = mpind[c][ui]

    print(cnt)

def main():

    t = 1

    if path.exists("F:/Comp Programming/input.txt"):

        sys.stdin = open("F:/Comp Programming/input.txt", 'r')

        sys.stdout = open("F:/Comp Programming/output1.txt", 'w')

    # sys.setrecursionlimit(1e6)

    t = readInts()

    for i in range(t):

        solve(i+1)

if __name__ == '__main__':

    main()


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.

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

if n%m != 0:

    print(-1)

else:

    d = n//m

    p = 0

    while d%2 == 0 or d%3 == 0:

        if d%2 == 0:

            p += 1

            d = d//2

        if d%3 == 0:

            p += 1

            d = d//3

    if d == 1:

        print(p)

    else:

        print(-1)


F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

import sys, os, io

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def update(l, r, s):

    q, lr, i = [1], [(0, l1 - 1)], 0

    while len(q) ^ i:

        j = q[i]

        l0, r0 = lr[i]

        if l <= l0 and r0 <= r:

            lazy[j] += s

            i += 1

            continue

        m0 = (l0 + r0) // 2

        if j < l1:

            lazy[2 * j] += lazy[j]

            lazy[2 * j + 1] += lazy[j]

            lazy[j] = 0

        if l <= m0 and l0 <= r:

            q.append(2 * j)

            lr.append((l0, m0))

        if l <= r0 and m0 + 1 <= r:

            q.append(2 * j + 1)

            lr.append((m0 + 1, r0))

        i += 1

    while q:

        i = q.pop()

        if i < l1:

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

    return

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

if n == 1:

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

    c = [0]

    for i in s:

        c.append(i + c[-1])

    ans = 0

    for i in range(m - k + 1):

        ans = max(ans, c[i + k] - c[i])

    print(ans)

    exit()

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

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

c1, c2 = [0], [0]

for i in s1:

    c1.append(i + c1[-1])

for i in s2:

    c2.append(i + c2[-1])

n0 = m - k + 1

dp0 = [0] * n0

for i in range(n0):

    dp0[i] = c1[i + k] - c1[i] + c2[i + k] - c2[i]

s1, c1 = s2, c2

l1 = pow(2, (2 * n0).bit_length())

l2 = 2 * l1

u = [max(i - k + 1, 0) for i in range(m)]

v = [min(i, m - k) for i in range(m)]

for x in range(n - 1):

    s2 = [0] * m if x == n - 2 else list(map(int, input().split()))

    c2 = [0]

    for i in s2:

        c2.append(i + c2[-1])

    tree, lazy = [0] * l2, [0] * l2

    for i in range(n0):

        tree[i + l1] = dp0[i]

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

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

    for i in range(k - 1):

        update(u[i], v[i], -s1[i])

    dp = [0] * n0

    for i in range(n0):

        j = i + k - 1

        update(u[j], v[j], -s1[j])

        dp[i] = c1[i + k] - c1[i] + c2[i + k] - c2[i] + tree[1] + lazy[1]

        update(u[i], v[i], s1[i])

    dp0 = dp

    s1, c1 = s2, c2

ans = max(dp0)

print(ans)


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

import sys

import math

import collections

import heapq

input=sys.stdin.readline

n=int(input())

s=list(input())

if(n==1):

    print(0)

else:

    s1=[]

    for i in range(n):

        s1.append(s[i])

    c=1

    ans=0

    while(c==1):

        m=-1

        ind=-1

        n1=len(s1)

        if(n1==1):

            break

        else:

            for i in range(n1):

                if(i==0):

                    if(ord(s1[i])-ord(s1[i+1])==1):

                        if(s1[i]!='a'):

                            ind=i

                            m=s1[i]

                elif(i==n1-1):

                    if(ord(s1[i])-ord(s1[i-1])==1):

                        if(s1[i]!='a'):

                            if(m==-1):

                                ind=i

                                m=s1[i]

                            else:

                                if(s1[i]>m):

                                    ind=i

                                    m=s1[i]

                else:

                    if(ord(s1[i])-ord(s1[i-1])==1 or ord(s1[i])-ord(s1[i+1])==1):

                        if(s1[i]!='a'):

                            if(m==-1):

                                ind=i

                                m=s1[i]

                            else:

                                if(s1[i]>m):

                                    ind=i

                                    m=s1[i]

        if(m==-1):

            c=0

        else:

            s2=[]

            for i in range(n1):

                if(i!=ind):

                    s2.append(s1[i])

            s1=[]

            for i in range(n1-1):

                s1.append(s2[i])

            ans+=1

    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

a = ord('a')

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

    s = input()

    t = [s[0]]

    i = 0

    for l in s[1:]:

        if i > 0 and l == t[i-1]:

            i -= 1

        elif i < len(t) - 1 and l == t[i+1]:

            i += 1

        elif l in t:

            print('NO')

            break

        elif i == len(t) - 1:

            t.append(l)

            i += 1

        elif i == 0:

            t.insert(0, l)

            i = 0

        else:

            print('NO')

            break

    else:

        print('YES')

        for l in range(26):

            l = chr(l + a)

            if l not in t:

                t.append(l)

        print(''.join(t))


import sys

from math import log2

input = lambda: sys.stdin.buffer.readline().decode().strip()

get_bit, sz = lambda x, i: (x >> i) & 1, 47

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

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

    a, mem, ans = [int(x) for x in input().split()], [0] * sz, 0

    if n > sum(a):

        print(-1)

        continue

    for i in range(m):

        mem[int(log2(a[i]))] += 1

    for bit in range(sz - 1):

        cur = get_bit(n, bit)

        if cur:

            if mem[bit]:

                mem[bit] -= 1

            else:

                for j in range(bit + 1, sz):

                    if mem[j]:

                        ans += j - bit

                        mem[j] -= 1

                        break

                    n ^= get_bit(n, j) << j

        mem[bit + 1] += mem[bit] >> 1

    print(ans)


C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that:   The intersection of any three subsets is empty;  It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3
0011100
3
1 4 6
3
3 4 7
2
2 3
OutputCopy1
2
3
3
3
3
3
InputCopy8 6
00110011
3
1 3 8
5
1 2 5 6 7
2
6 8
2
3 5
2
4 7
1
2
OutputCopy1
1
1
1
1
1
4
4
InputCopy5 3
00011
3
1 2 3
1
4
3
3 4 5
OutputCopy1
1
1
1
1
InputCopy19 5
1001001001100000110
2
2 3
2
5 6
2
8 9
5
12 13 14 15 16
1
19
OutputCopy0
1
1
1
2
2
2
3
3
3
3
4
4
4
4
4
4
4
5
NoteIn the first example:   For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110;  For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110;  For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example:   For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101;  For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.

import sys

input = sys.stdin.readline

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

S=[1]+list(map(int,list(input().strip())))

C=[]

for i in range(k):

    c=int(input())

    C.append(list(map(int,input().split())))

NUM=[[] for i in range(n+1)]

for i in range(k):

    for c in C[i]:

        NUM[c].append(i)

COLORS=[-1]*k

EDGE0=[[] for i in range(k)]

EDGE1=[[] for i in range(k)]

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

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

        if S[i]==0:

            COLORS[NUM[i][0]]=1

        else:

            COLORS[NUM[i][0]]=0

    elif len(NUM[i])==2:

        x,y=NUM[i]

        if S[i]==0:

            EDGE0[x].append(y)

            EDGE0[y].append(x)

        else:

            EDGE1[x].append(y)

            EDGE1[y].append(x)

Q=[i for i in range(k) if COLORS[i]!=-1]

while Q:

    x=Q.pop()

    for to in EDGE0[x]:

        if COLORS[to]==-1:

            COLORS[to]=1-COLORS[x]

            Q.append(to)

    for to in EDGE1[x]:

        if COLORS[to]==-1:

            COLORS[to]=COLORS[x]

            Q.append(to)

for i in range(k):

    if COLORS[i]==-1:

        COLORS[i]=0

        Q=[i]

        while Q:

            x=Q.pop()

            for to in EDGE0[x]:

                if COLORS[to]==-1:

                    COLORS[to]=1-COLORS[x]

                    Q.append(to)

            for to in EDGE1[x]:

                if COLORS[to]==-1:

                    COLORS[to]=COLORS[x]

                    Q.append(to)

#print(COLORS)

Group = [i for i in range(k)]

W0 = [0]*(k)

W1 = [0]*(k)

for i in range(k):

    if COLORS[i]==0:

        W0[i]=1

    else:

        W1[i]=1

def find(x):

    while Group[x] != x:

        x=Group[x]

    return x

def Union(x,y):

    if find(x) != find(y):

        if W0[find(x)] + W1[find(x)] < W0[find(y)] + W1[find(y)]:

            W0[find(y)] += W0[find(x)]

            W0[find(x)] =0

            W1[find(y)] += W1[find(x)]

            W1[find(x)] =0

            Group[find(x)] =find(y)

        else:

            W0[find(x)] += W0[find(y)]

            W0[find(y)] =0

            W1[find(x)] += W1[find(y)]

            W1[find(y)] =0

            Group[find(y)] =find(x)

ANS=0

SCORES=[0]*(k)

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

    if len(NUM[i])==0:

        True

    elif len(NUM[i])==1:

        x=NUM[i][0]

        ANS-=SCORES[find(x)]

        SCORES[find(x)]=0

        W0[find(x)]+=1<<31

        ANS+=W1[find(x)]

        SCORES[find(x)]=W1[find(x)]

    else:

        x,y=NUM[i]

        ANS-=SCORES[find(x)]

        SCORES[find(x)]=0

        ANS-=SCORES[find(y)]

        SCORES[find(y)]=0

        if find(x)!=find(y):

            Union(x,y)

        SCORES[find(x)]+=min(W0[find(x)],W1[find(x)])

        ANS+=min(W0[find(x)],W1[find(x)])

    print(ANS)


B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs:  buy one bus ticket to get from 11 to 33,  buy one tram ticket to get from 33 to 66,  buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB
OutputCopy2
1
3
1
6

import sys, math

import heapq

from collections import deque

from bisect import bisect_left, bisect_right

input = sys.stdin.readline

pop = heapq.heappop

push = heapq.heappush

# input

def ip(): return int(input())

def sp(): return str(input().rstrip())

def mip(): return map(int, input().split())

def msp(): return map(str, input().split())

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

def lmsp(): return list(map(str, input().split()))

# gcd, lcm

def gcd(x, y):

    while y:

        x, y = y, x % y

    return x

def lcm(x, y):

    return x * y // gcd(x, y)

# prime

def isPrime(x):

    if x <= 1: return False

    for i in range(2, int(x ** 0.5) + 1):

        if x % i == 0:

            return False

    return True

def getPow(a, x):

    ret = 1

    while x:

        if x & 1:

            ret = (ret * a) % mod

        a = (a * a) % mod

        x >>= 1

    return ret

############ Main! #############

for tc in range(ip()):

    a, b, p = mip()

    s = sp()

    n = len(s)

    i = n - 2

    c = [0 for _ in range(n - 1)]

    x = 0

    while i >= 0:

        now = s[i]

        while i >= 0 and now == s[i]:

            if now == "A":

                c[i] = x + a

            else:

                c[i] = x + b

            i -= 1

        if now == "A":

            x += a

        else:

            x += b

    ans = 0

    while ans < n - 1:

        if c[ans] > p:

            ans += 1

        else:

            break

    print(ans + 1)

######## Praise greedev ########


D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array;  for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array;  for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3
0
1
2
2
0
0
10
OutputCopy1
2
3
3
4
4
7
InputCopy4 3
1
2
1
2
OutputCopy0
0
0
0
NoteIn the first example:  After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11.  After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22.  After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33.  After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations).  After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44.  After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44.  After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations:   a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5,  a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3,  a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3,  a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6,  a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7,  a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4.  The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.

import sys, threading

import math

from os import path

from collections import defaultdict, Counter, deque

from bisect import *

from string import ascii_lowercase

from functools import cmp_to_key

import heapq

def readInts():

    x = list(map(int, (sys.stdin.readline().rstrip().split())))

    return x[0] if len(x) == 1 else x

def readList(type=int):

    x = sys.stdin.readline()

    x = list(map(type, x.rstrip('\n\r').split()))

    return x

def readStr():

    x = sys.stdin.readline().rstrip('\r\n')

    return x

write = sys.stdout.write

read = sys.stdin.readline

MAXN = 1123456

class mydict:

    def __init__(self, func):

        self.random = randint(0, 1 << 32)

        self.default = func

        self.dict = {}

    def __getitem__(self, key):

        mykey = self.random ^ key

        if mykey not in self.dict:

            self.dict[mykey] = self.default()

        return self.dict[mykey]

    def get(self, key, default):

        mykey = self.random ^ key

        if mykey not in self.dict:

            return default

        return self.dict[mykey]

    def __setitem__(self, key, item):

        mykey = self.random ^ key

        self.dict[mykey] = item

    def getkeys(self):

        return [self.random ^ i for i in self.dict]

    def __str__(self):

        return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'

def lcm(a, b):

    return (a*b)//(math.gcd(a,b))

def mod(n):

    return n%(998244353)

def solve(t):

    # print(f'Case #{t}: ', end = '')

    n, x = readInts()

    mp = defaultdict(lambda: 0)

    ar = []

    for _ in range(n):

        ar.append(readInts())

    mexr = [0]

    cur = 0

    for num in ar:

        if num == cur:

            cur += 1

        mexr.append(cur)

    res = []

    cur = -1

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

        mp[ar[i-1]%x] += 1

        while mp[(cur+1)%x] > 0:

            cur += 1

            mp[cur%x] -= 1

        res.append(cur+1)

    for num in res:

        print(num)

def main():

    t = 1

    if path.exists("F:/Comp Programming/input.txt"):

        sys.stdin = open("F:/Comp Programming/input.txt", 'r')

        sys.stdout = open("F:/Comp Programming/output1.txt", 'w')

    # sys.setrecursionlimit(10**5)

    # t = readInts()

    for i in range(t):

        solve(i+1)

if __name__ == '__main__':

    main()


D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that:  each array contains nn elements;  each element is an integer from 11 to mm;  for each array, there is exactly one pair of equal elements;  for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are:  [1,2,1][1,2,1];  [1,3,1][1,3,1];  [1,4,1][1,4,1];  [2,3,2][2,3,2];  [2,4,2][2,4,2];  [3,4,3][3,4,3].

import os

import sys

from io import BytesIO, IOBase

from collections import Counter, defaultdict

from sys import stdin, stdout

import io

import math

import heapq

import bisect

import collections

def ceil(a, b):

    return (a + b - 1) // b

inf = float('inf')

def get():

    return stdin.readline().rstrip()

def modfac(n, MOD):

    f = 1

    factorials = [1]

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

        f *= m

        f %= MOD

        factorials.append(f)

    inv = pow(f, MOD - 2, MOD)

    invs = [1] * (n + 1)

    invs[n] = inv

    for m in range(n, 1, -1):

        inv *= m

        inv %= MOD

        invs[m - 1] = inv

    return factorials, invs

def modnCr(n,r):

    return fac[n] * inv[n-r] * inv[r] % mod

mod = 998244353

fac,inv = modfac(500000,mod)

def modFact(n, p):

    if n >= p:

        return 0

    result = 1

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

        result = (result * i) % p

    return result

def power(x, y, p):

    res = 1

    x = x % p

    if (x == 0):

        return 0

    while (y > 0):

        if ((y & 1) == 1):

            res = (res * x) % p

        y = y >> 1  # y = y/2

        x = (x * x) % p

    return res

# for _ in range(int(get())):

# n=int(get())

# l=list(map(int,get().split()))

# = map(int,get().split())

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

print(((modnCr(m,n-1)%mod)*((n-2)%mod)*(power(2,n-3,mod)%mod))%mod)


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 _ in range(int(input())):

    n=int(input())

    print(int(n//(9/10)))


B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows:  The coordinates of the 00-th node is (x0,y0)(x0,y0)  For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions:  From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second.  If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows:   Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds.  Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows:   Collect the 33-rd node. This requires no seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.

#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me,

import sys

#then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize,

import os

#just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails

from io import BytesIO, IOBase

BUFSIZE = 8192

#every now and then. Just keep coding, just keep working and you'll keep progressing at speed-

# -forcing.

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")

#code by _Frust(CF)/Frust(AtCoder)

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

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

from os import path

if(path.exists('input.txt')):

    sys.stdin = open("input.txt","r")

    sys.stdout = open("output.txt","w")

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

import math

import heapq as hq

def check(p1, p2):

    p=tm(p1[0], p1[1], p2[0], p2[1])

    return (min(tm(p1[0], p1[1], xs, ys), tm(p2[0], p2[1], xs, ys))+p)<=t

def tm(x1, y1, x2, y2):

    return (abs(x2-x1) + abs(y2-y1))

x0 , y0, ax, ay, bx, by=map(int, input().split())

xs , ys, t=map(int, input().split())

xp=x0

yp=y0

# print(x0, y0)

# for i in range(40):

#     xp=(xp*ax) + bx

#     yp=(yp*ay) + by

#     print(xp, yp)

l=1

xc, yc=x0, y0

prev=float("inf")

flag=False

while True:

    k=tm(xc, yc, xs, ys)

    if k<prev:

        if k<=t:

            break

        else:

            l+=1

            xc=(xc*ax) + bx

            yc=(yc*ay) + by

            prev=k

    else:

        flag=True

        break

if flag:

    print(0)

else:

    r=l

    while tm(xc, yc, xs, ys)<=t:

        r+=1

        xc=(xc*ax) + bx

        yc=(yc*ay) + by

    # print(l, r)

    xc=x0

    yc=y0

    points=[[x0, y0]]

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

        x0=(x0*ax) + bx

        y0=(y0*ay) + by

        points.append([x0, y0])

    # print(points)

    ans=[0, 0]

    for i in range(r+1):

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

            # print(i, j)

            if check(points[i], points[j]) and (j-i+1)>(ans[1]-ans[0]+1):

                # print(i, j)

                ans=[i, j]

    print(ans[1]-ans[0]+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)

import sys, os, io

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

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

x = pow(10, 8)

ans = []

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

    c = len(ans) // 2

    if not m:

        ans.append(x + 3 * i * n)

    elif m >= c:

        m -= c

        ans.append(i)

    else:

        u = 2 * m

        m = 0

        ans.append(ans[-1] + ans[-u])

if m:

    ans = [-1]

sys.stdout.write(" ".join(map(str, ans)))


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:

#!/usr/bin/env python3
import sys
from math import *
from collections import defaultdict
from queue import deque                # Queues
from heapq import heappush, heappop    # Priority Queues

# parse
lines = [line.strip() for line in sys.stdin.readlines()]
n, m = list(map(int, lines[0].split()))
edges = [set() for i in range(n)]

for i in range(1, m+1):
  u, v = list(map(int, lines[i].split()))
  u -= 1
  v -= 1
  edges[u].add(v)
  edges[v].add(u)

nn = int(ceil(sqrt(n)))

def find_cycle(v, forbidden):
  used = set([v])
  forbidden = set(forbidden)
  ret = [v]
  while True:
    v = ret[-1]
    ss = edges[v] - used - forbidden
    nxt = None
    for s in ss:
      nxt = s
      break

    if nxt is None:
      break
    ret += [nxt]
    used.add(nxt)

  i = 0
  while ret[i] not in edges[ret[-1]]:
    i += 1

  return ret[i:]

q = []
for v in range(n):
  heappush(q, (len(edges[v]), v))

# find indep set
ind = set()
covered = set()
while q:
  d, v = heappop(q)

  if v in covered:
    continue

  ind.add(v)
  ss = set(edges[v])
  ss.add(v)

  if len(ind) == nn:
    # found an indep set
    print(1)
    print(' '.join('%s' % (i+1) for i in ind))
    break
  if d >= nn - 1:
    # found a cycle
    ys = find_cycle(v, list(covered))
    print(2)
    print(len(ys))
    print(' '.join('%s' % (i+1) for i in ys))
    break

  covered |= ss

  ws = set()
  for u in edges[v]:
    for w in edges[u]:
      ws.add(w)

  ws -= ss
  for w in ws:
    edges[w] -= ss
    heappush(q, (len(edges[w]), w))


B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).

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

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

    print(a*(len(str(b+1))-1))


B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES


C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.

from pprint import pprint

import sys

read = sys.stdin.buffer.read

n,m,p, *dat = map(int, read().split())

data = dat[:n]

datb = dat[n:]

for i in range (n):

    if data[i]%p != 0:

        inda = i

        break

for i in range (m):

    if datb[i]%p != 0:

        indb = i

        break

print(indb + inda)


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

t = int(input())

for i in range(t):

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

  if (a==b):

    print(0)

  elif (a< b and a%2 == b%2) or (a>b and a%2 != b%2):

    print(2)

  else:

    print(1)


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

from bisect import bisect_left

n = int(input())

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

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

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

c.sort()

ans = 0

for i in range(n):

    if c[i] <= 0:

        continue

    pos = bisect_left(c, -c[i]+1)

    ans += i - pos

print(ans)


E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch♪ - 彩This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: "C" (as in Carbon), "H" (as in Hydrogen), and "O" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific:  The artifact only contains 7575 units of energy.  For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy.  If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1≤t≤5001≤t≤500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4≤n≤504≤n≤50), the length of the string pp.Then you can make queries of type "? s" (1≤|s|≤n1≤|s|≤n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (−1≤k≤n−1≤k≤n). If k=−1k=−1, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a "Wrong answer" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,…,aka1,a2,…,ak (1≤a1<a2<…<ak≤n1≤a1<a2<…<ak≤n) denote the starting positions of the substrings that match the string ss.When you find out the string pp, print "! pp" to finish a test case. This query doesn't consume any energy. The interactor will return an integer 11 or 00. If the interactor returns 11, you can proceed to the next test case, or terminate the program if it was the last testcase.If the interactor returns 00, it means that your guess is incorrect, and you should to terminate to guarantee a "Wrong answer" verdict.Note that in every test case the string pp is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksFor hack, use the following format. Note that you can only hack with one test case:The first line should contain a single integer tt (t=1t=1).The second line should contain an integer nn (4≤n≤504≤n≤50) — the string's size.The third line should contain a string of size nn, consisting of characters "C", "H" and "O" only. This is the string contestants will have to find out.ExamplesInputCopy1
4

2 1 2

1 2

0

1OutputCopy

? C

? CH

? CCHO

! CCHH

InputCopy2
5

0

2 2 3

1
8

1 5

1 5

1 3

2 1 2

1OutputCopy

? O

? HHH

! CHHHH

? COO

? COOH

? HCCOO

? HH

! HHHCCOOH

NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.

import sys

t = int(input())

def get():

	ans = ""

	for i in range(n): ans = ans + S[i]

	return ans

def query(pat):

	print("Querying ", pat, file = sys.stderr)

	print("? " + pat, flush = True)

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

	for k in A[1:]:

		for i in range(len(pat)):

			S[k-1+i] = pat[i]

	return A[0]

def answer():

	ans = "! "

	for i in range(n): ans = ans + S[i]

	print("Answering ", ans, file = sys.stderr)

	print(ans, flush = True)

	input()

for q in range(t):

	n = int(input())

	S = ['?'] * n

	Ptrns = [ "CO", "CH", "HO", "HC" ]

	for pat in Ptrns: query(pat)

	print("After initial queries ", get(), file = sys.stderr)

	known = None

	for i in range(n):

		if S[i]!='?':

			known = i

			break

	if known is None:

		if query("OOO")>0:

			if query("OOOC")>0:

				for i in range(n):

					if S[i]=='?': S[i] = 'C'

			else:

				for i in range(n):

					if S[i]=='?': S[i] = 'H'

		else:

			if query("CCC")>0:

				for i in range(n):

					if S[i]=='?': S[i] = 'O'

			elif query("HHH")>0:

				for i in range(n):

					if S[i]=='?': S[i] = 'O'

			else:

				S[0] = S[1] = 'O'

				if query("OOHH")>0:

					S[2] = S[3] = 'H'

				else:

					S[2] = S[3] = 'C'

		answer()

		continue

	suf = S[known] + S[known+1]

	while known > 0:

		query(S[known] + suf)

		if S[known-1]=='?':

			for i in range(known):

				S[i] = 'O'

			break

		known-=1

		suf = S[known] + suf

	r = known

	while r < n and S[r]!='?': r+=1

	pref = ""

	for i in range(r): pref = pref + S[i]

	while r < n:

		print("I have now ", pref, file = sys.stderr)

		if S[r-1]=='O':

			query(pref + "O")

			if S[r]=='?':

				if r==n-1: # ostatni znak

					if query(pref + "C")==0:

						S[r] = 'H'

				else: # jeszcze nie

					query(pref+ "CC")

					if S[r]=='?': S[r] = S[r+1] = 'H'

		else:

			S[r]=S[r-1]

		while r < n and S[r]!='?':

			pref = pref + S[r]

			r+=1

	answer()