D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48

import random, sys, os, math, gc

from collections import Counter, defaultdict, deque

from functools import lru_cache, reduce, cmp_to_key

from itertools import accumulate, combinations, permutations, product

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

from io import BytesIO, IOBase

from copy import deepcopy

from bisect import bisect_left, bisect_right

from math import factorial, gcd

from operator import mul, xor

from types import GeneratorType

# if "PyPy" in sys.version:

#     import pypyjit; pypyjit.set_param('max_unroll_recursion=-1')

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

BUFSIZE = 8192

MOD = 10**9 + 7

MODD = 998244353

INF = float('inf')

D4 = [(1, 0), (0, 1), (-1, 0), (0, -1)]

D8 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]

N = 2*10**4+10

# 对正整数n，欧拉函数是小于n的正整数中与n互质的数的数目

# x = d∣x ∑ φ(d)

phi = [0] * N

phi[1] = 1

pfact = [0] * N

fact = [[] for _ in range(N)]

primes = []

# 1）莫比乌斯函数μ(n)的定义域是N；

# 2）μ(1)=1；

# 3）当n存在平方因子时，μ(n)=0；

# 4）当n是素数或奇数个不同素数之积时，μ(n)=-1；

# 5）当n是偶数个不同素数之积时，μ(n)=1。

# d∣n ∑ μ(d) = [n == 1]

# d∣n ∑ μ(d) * (n / d) = φ(n)

# g(n) = d∣n ∑ f(d) <---> f(n) = d∣n ∑ μ(d) g(n/d)

# g(n) = d∣n ∑ f(n) <---> f(n) = d∣n ∑ μ(n/d) g(n)

# mobious = [0] * N

# mobious[1] = 1

for i in range(1, N):

    if not phi[i]:

        primes.append(i)

        phi[i] = i-1

        # mobious[i] = -1

        for j in range(1, N):

            if i * j >= N:

                break

            pfact[i*j] = i

    for j in primes:

        if i * j >= N:

            break

        if i % j == 0:

            phi[i*j] = phi[i] * j

            # mobious[i*j] = 0

            break

        phi[i*j] = phi[i] * (j-1)

        # mobious[i*j] = mobious[i] * mobious[j]

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

        fact[j].append(i)

def getfact(x):

    res = defaultdict(int)

    while x != 1:

        res[pfact[x]] += 1

        x //= pfact[x]

    return res

def factlist(x):

    res = [1]

    while x != 1:

        k = pfact[x]

        c = 0

        while x % k == 0:

            c += 1

            x //= k

        tmp = []

        for i in res:

            for j in range(1, c+1):

                tmp.append(i * pow(k, j))

        res += tmp

    return res

def solve():

    a, b, c = LII()

    ans = INF

    ansl = [0, 0, 0]

    for i in range(1, N):

        res = abs(b - i)

        t = INF

        aa = 0

        for j in fact[i]:

            if t > abs(a - j):

                t = abs(a - j)

                aa = j

        res += t

        t = INF

        cc = 0

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

            if t > abs(c - j):

                t = abs(c - j)

                cc = j

        res += t

        if res < ans:

            ans = res

            ansl = [aa, i, cc]

    print(ans)

    print(*ansl)

def main():

    t = 1

    t = II()

    for _ in range(t):

        solve()

def bootstrap(f, stack=[]):

    def wrappedfunc(*args, **kwargs):

        if stack:

            return f(*args, **kwargs)

        else:

            to = f(*args, **kwargs)

            while True:

                if type(to) is GeneratorType:

                    stack.append(to)

                    to = next(to)

                else:

                    stack.pop()

                    if not stack:

                        break

                    to = stack[-1].send(to)

            return to

    return wrappedfunc

def bitcnt(n):

    c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)

    c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333)

    c = (c & 0x0F0F0F0F0F0F0F0F) + ((c >> 4) & 0x0F0F0F0F0F0F0F0F)

    c = (c & 0x00FF00FF00FF00FF) + ((c >> 8) & 0x00FF00FF00FF00FF)

    c = (c & 0x0000FFFF0000FFFF) + ((c >> 16) & 0x0000FFFF0000FFFF)

    c = (c & 0x00000000FFFFFFFF) + ((c >> 32) & 0x00000000FFFFFFFF)

    return c

def lcm(x, y):

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

def lowbit(x):

    return x & -x

def perm(n, r):

    return factorial(n) // factorial(n - r) if n >= r else 0

def comb(n, r):

    return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0

def probabilityMod(x, y, mod):

    return x * pow(y, mod-2, mod) % mod

class SortedList:

    def __init__(self, iterable=[], _load=200):

        """Initialize sorted list instance."""

        values = sorted(iterable)

        self._len = _len = len(values)

        self._load = _load

        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]

        self._list_lens = [len(_list) for _list in _lists]

        self._mins = [_list[0] for _list in _lists]

        self._fen_tree = []

        self._rebuild = True

    def _fen_build(self):

        """Build a fenwick tree instance."""

        self._fen_tree[:] = self._list_lens

        _fen_tree = self._fen_tree

        for i in range(len(_fen_tree)):

            if i | i + 1 < len(_fen_tree):

                _fen_tree[i | i + 1] += _fen_tree[i]

        self._rebuild = False

    def _fen_update(self, index, value):

        """Update `fen_tree[index] += value`."""

        if not self._rebuild:

            _fen_tree = self._fen_tree

            while index < len(_fen_tree):

                _fen_tree[index] += value

                index |= index + 1

    def _fen_query(self, end):

        """Return `sum(_fen_tree[:end])`."""

        if self._rebuild:

            self._fen_build()

        _fen_tree = self._fen_tree

        x = 0

        while end:

            x += _fen_tree[end - 1]

            end &= end - 1

        return x

    def _fen_findkth(self, k):

        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""

        _list_lens = self._list_lens

        if k < _list_lens[0]:

            return 0, k

        if k >= self._len - _list_lens[-1]:

            return len(_list_lens) - 1, k + _list_lens[-1] - self._len

        if self._rebuild:

            self._fen_build()

        _fen_tree = self._fen_tree

        idx = -1

        for d in reversed(range(len(_fen_tree).bit_length())):

            right_idx = idx + (1 << d)

            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:

                idx = right_idx

                k -= _fen_tree[idx]

        return idx + 1, k

    def _delete(self, pos, idx):

        """Delete value at the given `(pos, idx)`."""

        _lists = self._lists

        _mins = self._mins

        _list_lens = self._list_lens

        self._len -= 1

        self._fen_update(pos, -1)

        del _lists[pos][idx]

        _list_lens[pos] -= 1

        if _list_lens[pos]:

            _mins[pos] = _lists[pos][0]

        else:

            del _lists[pos]

            del _list_lens[pos]

            del _mins[pos]

            self._rebuild = True

    def _loc_left(self, value):

        """Return an index pair that corresponds to the first position of `value` in the sorted list."""

        if not self._len:

            return 0, 0

        _lists = self._lists

        _mins = self._mins

        lo, pos = -1, len(_lists) - 1

        while lo + 1 < pos:

            mi = (lo + pos) >> 1

            if value <= _mins[mi]:

                pos = mi

            else:

                lo = mi

        if pos and value <= _lists[pos - 1][-1]:

            pos -= 1

        _list = _lists[pos]

        lo, idx = -1, len(_list)

        while lo + 1 < idx:

            mi = (lo + idx) >> 1

            if value <= _list[mi]:

                idx = mi

            else:

                lo = mi

        return pos, idx

    def _loc_right(self, value):

        """Return an index pair that corresponds to the last position of `value` in the sorted list."""

        if not self._len:

            return 0, 0

        _lists = self._lists

        _mins = self._mins

        pos, hi = 0, len(_lists)

        while pos + 1 < hi:

            mi = (pos + hi) >> 1

            if value < _mins[mi]:

                hi = mi

            else:

                pos = mi

        _list = _lists[pos]

        lo, idx = -1, len(_list)

        while lo + 1 < idx:

            mi = (lo + idx) >> 1

            if value < _list[mi]:

                idx = mi

            else:

                lo = mi

        return pos, idx

    def add(self, value):

        """Add `value` to sorted list."""

        _load = self._load

        _lists = self._lists

        _mins = self._mins

        _list_lens = self._list_lens

        self._len += 1

        if _lists:

            pos, idx = self._loc_right(value)

            self._fen_update(pos, 1)

            _list = _lists[pos]

            _list.insert(idx, value)

            _list_lens[pos] += 1

            _mins[pos] = _list[0]

            if _load + _load < len(_list):

                _lists.insert(pos + 1, _list[_load:])

                _list_lens.insert(pos + 1, len(_list) - _load)

                _mins.insert(pos + 1, _list[_load])

                _list_lens[pos] = _load

                del _list[_load:]

                self._rebuild = True

        else:

            _lists.append([value])

            _mins.append(value)

            _list_lens.append(1)

            self._rebuild = True

    def discard(self, value):

        """Remove `value` from sorted list if it is a member."""

        _lists = self._lists

        if _lists:

            pos, idx = self._loc_right(value)

            if idx and _lists[pos][idx - 1] == value:

                self._delete(pos, idx - 1)

    def remove(self, value):

        """Remove `value` from sorted list; `value` must be a member."""

        _len = self._len

        self.discard(value)

        if _len == self._len:

            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):

        """Remove and return value at `index` in sorted list."""

        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)

        value = self._lists[pos][idx]

        self._delete(pos, idx)

        return value

    def bisect_left(self, value):

        """Return the first index to insert `value` in the sorted list."""

        pos, idx = self._loc_left(value)

        return self._fen_query(pos) + idx

    def bisect_right(self, value):

        """Return the last index to insert `value` in the sorted list."""

        pos, idx = self._loc_right(value)

        return self._fen_query(pos) + idx

    def count(self, value):

        """Return number of occurrences of `value` in the sorted list."""

        return self.bisect_right(value) - self.bisect_left(value)

    def __len__(self):

        """Return the size of the sorted list."""

        return self._len

    def __getitem__(self, index):

        """Lookup value at `index` in sorted list."""

        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)

        return self._lists[pos][idx]

    def __delitem__(self, index):

        """Remove value at `index` from sorted list."""

        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)

        self._delete(pos, idx)

    def __contains__(self, value):

        """Return true if `value` is an element of the sorted list."""

        _lists = self._lists

        if _lists:

            pos, idx = self._loc_left(value)

            return idx < len(_lists[pos]) and _lists[pos][idx] == value

        return False

    def __iter__(self):

        """Return an iterator over the sorted list."""

        return (value for _list in self._lists for value in _list)

    def __reversed__(self):

        """Return a reverse iterator over the sorted list."""

        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):

        """Return string representation of sorted list."""

        return 'SortedList({0})'.format(list(self))

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 = IOWrapper(sys.stdin)

# sys.stdout = IOWrapper(sys.stdout)

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

def I():

    return input()

def II():

    return int(input())

def MI():

    return map(int, input().split())

def LI():

    return list(input().split())

def LII():

    return list(map(int, input().split()))

def GMI():

    return map(lambda x: int(x) - 1, input().split())

def LGMI():

    return list(map(lambda x: int(x) - 1, input().split()))

def getGraph(n, m, directed=False):

    d = [[] for _ in range(n)]

    for _ in range(m):

        u, v = LGMI()

        d[u].append(v)

        if not directed:

            d[v].append(u)

    return d

def getWeightedGraph(n, m, directed=False):

    d = [[] for _ in range(n)]

    for _ in range(m):

        u, v, w = LII()

        u -= 1; v -= 1

        d[u].append((v, w))

        if not directed:

            d[v].append((u, w))

    return d

if __name__ == "__main__":

    main()


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


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 bisect

import collections

import heapq

import io

import math

import os

import random

import sys

LO = 'abcdefghijklmnopqrstuvwxyz'

# Mod = 1000000007

Mod = 998244353

def gcd(x, y):

    while y:

        x, y = y, x % y

    return x

# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()

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

T = 1

# T = int(_input())

for _ in range(T):

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

    if n > 2:

        p = 1

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

            p = p * i % Mod

        q = 1

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

            q = q * i % Mod

        print(p * pow(q, Mod - 2, Mod) % Mod * pow(2, n - 3, Mod) * (n - 2) % Mod)

    else:

        print(0)


B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.

n=int(input())

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

m=0

temp=0

for i in range(n):

    if (lst[i] ==1 and temp==0) or lst[i]==1 and lst[i-1]==1:

        temp+=1

    else:

        m=max(temp,m)

        temp=0

first=0

for ele in lst:

    if ele==0:

        break

    else:

        first+=1

second=0

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

    if lst[i]==0:

        break

    else:

        second+=1

tot=first+second

print(max(m,tot))


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. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

#import io, os

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

n = int(input())

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

connections = {}

for i in range(len(lis)):

  if str(lis[i] - i) in connections:

    a = connections[str(lis[i] - i)]

    a.append(lis[i])

    connections[str(lis[i] - i)] = a

  else:

    connections[str(lis[i] - i)] = [lis[i]]

maxi = 0

for i in connections:

  b = sum(connections[i])

  maxi = max(maxi,b)

print(maxi)


A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3
3
1 4 3
1
15
2
3 5
OutputCopy1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

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

    n = int(input())

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

    if n == 1:

        if a[0] % 2 == 0:

            print(1)

            print(1)

        else:

            print(-1)

    else:

        j = 0

        for i in range(n):

            if a[i] % 2 == 0:

                j = i+1

                break

        if j > 0:

            print(1)

            print(j)

        else:

            print(2)

            print(1, 2)


E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.

import sys
from array import array  # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union  # noqa: F401

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

class UnionFind(object):
    __slots__ = ['nodes']

    def __init__(self, n: int):
        self.nodes = [-1] * n

    def find(self, x: int) -> int:
        if self.nodes[x] < 0:
            return x
        else:
            self.nodes[x] = self.find(self.nodes[x])
            return self.nodes[x]

    def unite(self, x: int, y: int) -> bool:
        root_x, root_y, nodes = self.find(x), self.find(y), self.nodes

        if root_x != root_y:
            if nodes[root_x] > nodes[root_y]:
                root_x, root_y = root_y, root_x
            nodes[root_x] += nodes[root_y]
            nodes[root_y] = root_x

        return root_x != root_y

    def size(self, x: int) -> int:
        return -self.nodes[self.find(x)]

border = 1 << 30
mask = border - 1

def add(x1, y1, x2, y2):
    x, y = x1 + x2, y1 + y2
    if y >= border:
        x += 1
        y &= mask
    return x, y

def main():
    n, p, k = map(int, input().split())
    a = list(map(int, input().split()))
    matrix = [list(map(int, input().split())) for _ in range(n)]
    m = 1 << p
    popcnt = [bin(bit).count('1') for bit in range(m)]
    dests = [[i for i in range(p) if ((1 << i) & bit) == 0] for bit in range(m)]
    minf = -10**9

    dp_up = array('i', [0] + [minf] * (m - 1))
    dp_lo = array('i', [0] + [minf] * (m - 1))
    for cnt, i in enumerate(sorted(range(n), key=lambda i: -a[i])):
        ndp_up = dp_up[:]
        ndp_lo = dp_lo[:]

        for bit in range(m):
            if cnt - popcnt[bit] < k:
                up, lo = add(dp_up[bit], dp_lo[bit], 0, a[i])
                if ndp_up[bit] < up or ndp_up[bit] == up and ndp_lo[bit] < lo:
                    ndp_up[bit], ndp_lo[bit] = up, lo
            for j in dests[bit]:
                up, lo = add(dp_up[bit], dp_lo[bit], 0, matrix[i][j])
                if ndp_up[bit | (1 << j)] < up or ndp_up[bit | (1 << j)] == up and ndp_lo[bit | (1 << j)] < lo:
                    ndp_up[bit | (1 << j)], ndp_lo[bit | (1 << j)] = up, lo

        dp_up, dp_lo = ndp_up, ndp_lo

    print(dp_up[-1] * border + dp_lo[-1])

if __name__ == '__main__':
    main()


D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10

import os

import sys

from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

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

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

    def read(self):

        while True:

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

            if not b:

                break

            ptr = self.buffer.tell()

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

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

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

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

            ptr = self.buffer.tell()

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

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

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

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

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

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

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

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

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

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

from math import *

from collections import defaultdict

def solve():

    n=int(input())

    a=input()

    b=input()

    dl=defaultdict(list)

    dr=defaultdict(list)

    left=[]

    right=[]

    ans=[]

    for i in range(n):

        dl[a[i]].append(i+1)

        dr[b[i]].append(i+1)

    for i in range(97,123):

        char=chr(i)

        for j in range(min(len(dl[char]),len(dr[char]))):

            ans.append([dl[char][-1],dr[char][-1]])

            dl[char].pop()

            dr[char].pop()

        if len(dl[char])>0:

            for j in dl[char]:

                left.append(j)

        else:

            for j in dr[char]:

                right.append(j)

    for j in range(min(len(left),len(dr['?']))):

        ans.append([left[-1],dr['?'][-1]])

        left.pop()

        dr['?'].pop()

    for j in range(min(len(right),len(dl['?']))):

        ans.append([dl['?'][-1],right[-1]])

        right.pop()

        dl['?'].pop()

    char='?'

    for i in range(min(len(dl[char]),len(dr[char]))):

        ans.append([dl[char][-1],dr[char][-1]])

        dl[char].pop()

        dr[char].pop()

    print(len(ans))

    for x,y in ans:

        print(x,y)

for _ in range(1):

    solve()


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

import functools

import math

import random

from collections import defaultdict,deque

from heapq import  heapify,heappop,heappush

import bisect

from collections import Counter

import collections

from functools import lru_cache

import time

from typing import List

from math import log

from  random import  randint,seed

from time import time

import os,sys

from io import BytesIO, IOBase

# Fast IO Region

BUFSIZE = 8192

class FastIO(IOBase):

    newlines = 0

    def __init__(self, file):

        self._fd = file.fileno()

        self.buffer = BytesIO()

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

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

    def read(self):

        while True:

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

            if not b:

                break

            ptr = self.buffer.tell()

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

        self.newlines = 0

        return self.buffer.read()

    def readline(self):

        while self.newlines == 0:

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

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

            ptr = self.buffer.tell()

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

        self.newlines -= 1

        return self.buffer.readline()

    def flush(self):

        if self.writable:

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

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

class IOWrapper(IOBase):

    def __init__(self, file):

        self.buffer = FastIO(file)

        self.flush = self.buffer.flush

        self.writable = self.buffer.writable

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

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

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

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

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

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

# n,a,t=5,[3,7,9,7,8],[5,2,5,7,5]

dt=defaultdict(list)

for i in range(n):

    dt[a[i]].append(t[i])

data=sorted(dt.items(),key=lambda x:x[0])

# print(data)

ans,cur,sum,n=0,[],0,len(data)

for i,(x,lst) in enumerate(data):

    for cost in lst:

        heappush(cur,-cost)

        sum+=cost

    top=heappop(cur)

    sum-=-top

    x+=1

    while i<n-1 and x<data[i+1][0] and cur:

        ans+=sum

        x+=1

        sum-=-heappop(cur)

    ans+=sum

while cur:

    sum-=-heappop(cur)

    ans += sum

print(ans)


A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

def checker(n,s):

    l = 0

    r = 0

    i = 0

    ans = 0

    while i < n:

        while s[i] =="(":

            if l!= 0:

                l -= 1

                i += 1

            else:

                r += 1

                i += 1

            if i == n:

                break

        if i == n:

            break

        while s[i] == ")":

            l += 1

            if l > r:

                ans += 1

            else:

                r -= 1

                l -= 1

            i += 1

            if i == n:

                break

    if (l!=0) or (r != 0):

        return -1

    else:

        return 2*ans

# print(checker(8,"))((())("))

n = int(input())

s = str(input())

print(checker(n,s))


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

def solve():

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

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

    for i in range(0, k + 1):

        if s - i >= 1 and not s - i in a:

            print(i);

            break

        if s + i <= n and not s + i in a:

            print(i);

            break

    else:

        assert False

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

    solve()


B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.

I=input

for _ in[0]*int(I()):n=int(I());a=sorted(map(int,I().split()));print(a[n]-a[n-1])


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:

#coding:utf8
import math

n, m, = [int(x) for x in input().split()]
cons = math.ceil(pow(n, 0.5))

adj_mat = [[] for x in range(n + 1)]
pre_node, cur_deepth = [0] * (n + 1), [0] * (n + 1)

for i in range(m):
    node1, node2 = [int(x) for x in input().split()]
    adj_mat[node1].append(node2)
    adj_mat[node2].append(node1)

tmp_rec, deep_path = [node1], []

while tmp_rec != []:
    n1 = tmp_rec.pop()
    if cur_deepth[n1] > 0:
        continue
    deep_path.append(n1)
    cur_deepth[n1] = cur_deepth[pre_node[n1]] + 1
    for n2 in adj_mat[n1]:
        if not cur_deepth[n2]:
            pre_node[n2] = n1
            tmp_rec.append(n2)
        elif cur_deepth[n1] - cur_deepth[n2] + 1 >= cons:
            circle = []
            while n1 != pre_node[n2]:
                circle.append(n1)
                n1 = pre_node[n1]
            if len(circle) >= cons:
                print("2")
                print(len(circle))
                print(" ".join([str(x) for x in circle]))
                exit(0)

cur_deepth = [0] * (n + 1)
tmp_arr = []
while deep_path != []:
    n1 = deep_path.pop()
    if not cur_deepth[n1]:
        tmp_arr.append(n1)
        for n2 in adj_mat[n1]:
            cur_deepth[n2] = 1
print("1")
print(" ".join([str(x) for x in tmp_arr[:cons]]))


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 sys import stdin

input=lambda :stdin.readline()[:-1]

n=int(input())

s=[ord(i)-97 for i in input()]

c=[-1]*27

ans=[]

for i in s:

  mx=max(c[i+1:])

  c[i]=mx+1

  ans.append(mx+1)

if max(ans)<=1:

  print('YES')

  print(*ans,sep='')

else:

  print('NO')


B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2
1 2
OutputCopy3InputCopy3
1 2 3
OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.

import sys

input = sys.stdin.buffer.readline

from collections import deque

def countingSort(arr, exp1):

    n = len(arr)

    output = [0] * (n)

    count = [0] * (10)

    for i in range(0, n):

        index = arr[i] // exp1

        count[index % 10] += 1

    for i in range(1, 10):

        count[i] += count[i - 1]

    i = n - 1

    while i >= 0:

        index = arr[i] // exp1

        output[count[index % 10] - 1] = arr[i]

        count[index % 10] -= 1

        i -= 1

    i = 0

    for i in range(0, len(arr)):

        arr[i] = output[i]

def radixSort(arr):

    max1 = max(arr)

    exp = 1

    while max1 / exp >= 1:

        countingSort(arr, exp)

        exp *= 10

N = int(input())

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

res = 0

radixSort(a)

for k in range(max(a).bit_length(), -1, -1):

    z = 1 << k

    c = 0

    j = jj = jjj = N - 1

    for i in range(N):

        while j >= 0 and a[i] + a[j] >= z: j -= 1

        while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1

        while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1

        c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj)

    res += z * (c & 1)

    for i in range(N): a[i] = min(a[i] ^ z, a[i])

    a.sort()

      #print(res, a, c)

print(res)


inf=float('inf')

from heapq import heapify,heappop,heappush

from collections import defaultdict

if __name__=='__main__':

   n=int(input())

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

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

   l=[]

   for i in range(n):

      l.append([lst[i],tm[i]])

   l.sort()

   l.append((10**12,0))

   cnt = 0

   prev=0

   now = []

   for x in l:

      a,t = x

      for ai in range(prev,a):

         if not now:

            break

         tm,am = heappop(now)

         tm = 10**5-tm

         cnt += (ai-am) * tm

      heappush(now,(10**5-t,a))

      prev=a

   print(cnt)


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

import math

import sys

input = sys.stdin.readline

############ ---- Input Functions ---- ############

def inp():

    return(int(input()))

def inlt():

    return(list(map(int,input().split())))

def insr():

    s = input()

    return(list(s[:len(s) - 1]))

def invr():

    return(map(int,input().split()))

for _ in range(inp()):

    n = inp()

    s = insr()

    coord = {(0,0):0}

    left = 0

    up = 0

    maxer = 999999999999999

    coords = None

    for i in range(n):

        if s[i] == 'L':

            left -= 1

        elif s[i] == 'R':

            left += 1

        elif s[i] == 'U':

            up += 1

        else:

            up -= 1

        if (left, up) in coord:

            if i+1 - coord[(left, up)] < maxer:

                maxer = i+1 - coord[(left, up)]

                coords = (coord[(left, up)], i+1)

        coord[(left, up)] = i+1

    if maxer == 999999999999999:

        print(-1)

    else:

        print(coords[0]+1, coords[1])


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

# import time
# start = time.time()

def checkBits(integers, bit):
    if bit < 0:
        return 0

    left = []
    right = []

    for i in integers:
        if ((i >> bit) & 1) == 0:
            left.append(i)
        else:
            right.append(i)
    if len(left) == 0:
        return checkBits(right, bit -1)
    if len(right) == 0:
        return checkBits(left, bit - 1)
    return min(checkBits(left, bit - 1), checkBits(right, bit - 1)) + (1 << bit)

if __name__ == '__main__':
    _ = input()
    integers = list(map(int, input().split()))

    print(checkBits(integers, 30))
    # print(f'end1 {time.time() - start}')


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

def gcd(a,b):

    if(b==0):

        return a

    else:

        return gcd(b,a%b)

from collections import Counter

import math

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

    n = int(input())

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

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

    x = []

    for i in range(n):

        x.append(l[i]%2)

    if(len(set(x))==1):

        print("YES")

    else:

        print("NO")


B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3
tab
one
bat
OutputCopy6
tabbat
InputCopy4 2
oo
ox
xo
xx
OutputCopy6
oxxxxo
InputCopy3 5
hello
codef
orces
OutputCopy0

InputCopy9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji
OutputCopy20
ababwxyzijjizyxwbaba
NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.

def solve():

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

    arr, pairs, single = [],[],[]

    ans = ''

    for i in range(n):

        arr.append(input())

    while arr:

        a = arr.pop()

        if a[::-1] in arr: # can be optimized with dict lookup

            pairs.append(a)

        else:

            single.append(a)

    while single:

        b = single.pop()

        if b[::-1] == b:

            ans = b

            break

    for i in pairs:

        ans = i + ans + i[::-1]

    print(len(ans))

    return ans

print(solve())


import sys

def II(): return int(sys.stdin.readline())

def LI(): return [int(num) for num in sys.stdin.readline().split()]

def SI(): return sys.stdin.readline().rstrip()

from collections import defaultdict

k = II()

l = defaultdict(list)

r = defaultdict(list)

for ind, char in enumerate(zip(SI(), SI())):

    l[char[0]].append(ind + 1)

    r[char[1]].append(ind + 1)

# print(l)

# print(r)

pairs = []

def func(seek_from, where, flag):

    for char in seek_from:

        if char != '?' and char in where:

            while seek_from[char] and where[char]:

                if flag:

                    pairs.append([seek_from[char].pop(), where[char].pop()])

                else:

                    pairs.append([where[char].pop(), seek_from[char].pop()])

            if not where[char]:

                del where[char]

# print(l)

# print(r)

func(l, r, 1)

func(r, l, 0)

# print(pairs)

def func2(where, seek_from, flag):

    for char in seek_from:

        if char != '?':

            while where['?'] and seek_from[char]:

                if flag:

                    pairs.append([where['?'].pop(), seek_from[char].pop()])

                else:

                    pairs.append([seek_from[char].pop(), where['?'].pop()])

# print(l)

# print(r)

func2(l, r, 1)

func2(r, l, 0)

# print(pairs)

# print(l)

# print(r)

while l['?'] and r['?']:

    pairs.append([l['?'].pop(), r['?'].pop()])

print(len(pairs))

for pair in pairs:

    print(*pair)

    # for char in seek_from:

    #     if char == '?' and char in where:

    #         while seek_from[char] and where[char]:

    #             pairs.append([seek_from[char].pop(), where[char].pop()])

    #         if not where[char]:

    #             del where[char]

#

# pairs = []

# for char in l:

#     if char != '?' and char in r:

#         nexus = min(l[char], r[char])

#         pairs += nexus

#         l[char] -= nexus

#         r[char] -= nexus

#         if not r[char]:

#             del r[char]

#

#

# def func(where, from_counter):

#     global pairs

#     if '?' in where:

#         for char in from_counter:

#             if char != '?' and where['?']:

#                 nexus = min(from_counter[char], where['?'])

#                 pairs += nexus

#                 where['?'] -= nexus

#


C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

import sys

latin = "abcdefghijklmnopqrstuvwxyz"

n = int(input())

if n == 1:

    print("?", 1, n)

    sys.stdout.flush()

    a = input()

    print("!", a)

else:

    print("?",1,n)

    sys.stdout.flush()

    d1 = {}

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

        d1[i] = []

    for i in range((n+1)*n//2):

        s = input()

        dick = []

        for i in latin:

            dick.append(s.count(i))

        d1[len(s)].append(dick)

    print("?",2,n)

    sys.stdout.flush()

    d2 = {}

    for i in range(1,n):

        d2[i] = []

    for i in range((n-1)*n//2):

        s = input()

        dick = []

        for i in latin:

            dick.append(s.count(i))

        d2[len(s)].append(dick)

    odp = [0] * n

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

        d1[i].sort()

        if i < n:

            d2[i].sort()

    lewe = {}

    for i in range(1, n):

        kandydat = d1[i][-1]

        for j in range(len(d2[i])):

            if d1[i][j] != d2[i][j]:

                kandydat = d1[i][j]

                break

        lewe[i] = kandydat

    lewe[n] = d1[n][0]

    for i in range(26):

        if lewe[1][i] !=0:

            odp[0] = chr(97+i)

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

        for j in range(26):

            if lewe[i][j] > lewe[i-1][j]:

                odp[i-1] = chr(97 + j)

    print("!","".join(odp))


A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after 11 minute — AAPAAPPAAPPP  after 22 minutes — AAAAAAPAAAPP  after 33 minutes — AAAAAAAAAAAP  after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.

n = int(input())

for i in range(n):

    size = int(input())

    s = input()

    cnt = 0

    temp = s.replace('AP','AA')

    while(temp != s):

        cnt += 1

        s= temp

        temp = s.replace('AP','AA')

    print(cnt)


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

import itertools

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

    n = int(input())

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

    if min(a[:-1]) <= 0 or max(a[:-1]) >= a[-1]:

        print('NO')

    else:

        print('YES')


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.

def main():

    t = int(input())

    # Loop through each test case and compute

    for _ in range(t):

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

        if a == b:

            print(0)

            continue

        diff = abs(a-b)

        if diff % 2:

            if a < b:

                print(1)

            else:

                print(2)

        else:

            if a < b:

                print(2)

            else:

                print(1)

if __name__ == "__main__":

    main()


F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations:  Add 11 to the second element, making it equal to 99.  Subtract 11 from the third element, making it equal to 66.  Add 11 to the fifth element, making it equal to 22.  Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

import random

n = int(input())

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

limit = min(8, n)

iterations = [x for x in range(n)]

random.shuffle(iterations)

iterations = iterations[:limit]

def factorization(x):

	primes = []

	i = 2

	while i * i <= x:

		if x % i == 0:

			primes.append(i)

			while x % i == 0: x //= i

		i = i + 1

	if x > 1: primes.append(x)

	return primes

def solve_with_fixed_gcd(arr, gcd):

	result = 0

	for x in arr:

		if x < gcd: result += (gcd - x)

		else:

			remainder = x % gcd

			result += min(remainder, gcd - remainder)

	return result

answer = float("inf")

prime_list = set()

for index in iterations:

	for x in range(-1, 2):

		tmp = factorization(a[index]-x)

		for z in tmp: prime_list.add(z)

for prime in prime_list:

	answer = min(answer, solve_with_fixed_gcd(a, prime))

	if answer == 0: break

print(answer)


from collections import Counter

DEBUG = False

N = int(input())

if N == 1:

    print('? 1 {}'.format(N), flush = True)

    print('! ' + input(), flush = True)

else:

    LC = [Counter() for _ in range(N+1)]

    if not DEBUG:

        print('? 1 {}'.format(N), flush = True)

        for _ in range(N*(N+1)//2):

            K = list(map(lambda x: ord(x)-97, input().strip()))

            l = len(K)

            for k in K:

                LC[l][k] += 1

    else:

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

            for j in range(i):

                K = list(map(lambda x: ord(x)-97, S[j:i]))

                l = len(K)

                for k in K:

                    LC[l][k] += 1

    comp = [Counter() for _ in range(N+1)]

    pre = Counter()

    for k in range(26):

        comp[N][k] += LC[N][k]

        pre[k] += LC[N][k]

    for x in range(N-1, 0, -1):

        if N+1-x > x:

            break

        for k in range(26):

            comp[x][k] = LC[x][k] - pre[k]

            pre[k] += comp[x][k]

    LC2 = [Counter() for _ in range(N)]

    Ar = [None] * (N+1)

    if not DEBUG:

        print('? 1 {}'.format(N-1), flush = True)

        for _ in range((N-1)*N//2):

            K = list(map(lambda x: ord(x)-97, input().strip()))

            l = len(K)

            for k in K:

                LC2[l][k] += 1

    else:

        for i in range(1, N):

            for j in range(i):

                K = list(map(lambda x: ord(x)-97, S[j:i]))

                l = len(K)

                for k in K:

                    LC2[l][k] += 1

    comp2 = [Counter() for _ in range(N+1)]

    pre = Counter()

    for k in range(26):

        comp2[N-1][k] += LC2[N-1][k]

        pre[k] += LC2[N-1][k]

    for x in range(N-2, 0, -1):

        if N-x > x:

            break

        for k in range(26):

            comp2[x][k] = LC2[x][k] - pre[k]

            pre[k] += comp2[x][k]

    for i in range(N-1, -1, -1):

        if comp2[i] == Counter():

            break

        for st in range(26):

            if comp[i][st] != comp2[i][st]:

                Ar[N-i] = st

    for i in range(1, N):

        if comp[N+1-i] == Counter():

            break

        for st in range(26):

            if comp[N+1-i][st] != comp2[N-i][st]:

                Ar[N+1-i] = st

    print('! ' + ''.join(map(lambda x:chr(x+97), Ar[1:])), flush = True)


C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

from sys import stdin

input = stdin.readline

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

def answer():

    left , s = [-1 for i in range(n)] , []

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

        while(len(s) and a[s[-1]] >= a[i]):

            left[s.pop()] = i

        s.append(i)

    right , s = [n for i in range(n)] , []

    for i in range(n):

        while(len(s) and a[s[-1]] >= a[i]):

            right[s.pop()] = i

        s.append(i)

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

    for i in range(n):

        sumval[i + 1] = sumval[i] + a[i]

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

    for i in range(n):

        sval = sumval[i] - sumval[left[i] + 1]

        prefix[i + 1] = prefix[left[i] + 1] + sval - (i - left[i] - 1) * a[i]

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

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

        sval = sumval[right[i]] - sumval[i + 1]

        suffix[i] = suffix[right[i]] + sval - (right[i] - i - 1) * a[i]

    best = float('inf')

    for i in range(n):

        value = prefix[i + 1] + suffix[i]

        if(best > value):

            best = value

            peak = i

    for i in range(peak - 1 , -1 , -1):

        if(a[i] > a[i + 1]):

            a[i] = a[i + 1]

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

        if(a[i] > a[i - 1]):

            a[i] = a[i - 1]

    return a

for T in range(1):

    n = int(input())

    a = inp()

    print(*answer())


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

from math import lcm, ceil

# primes = []

# def seive(lim):

#   lim = ceil(lim ** 0.5) + 10

#   p = [True] * lim

#   p[0] = p[1] = False

#   i = 2

#   while i < lim:

#     if p[i]:

#       primes.append(i)

#       j = i*i

#       while j < lim:

#         p[j] = False

#         j += i

#     i += 1

min = n = int(input())

sq = ceil(n ** 0.5) + 100

# seive(n)

x = 1

while x <= sq:

  if n % x == 0:

    y = n // x

    if lcm(x, y) != n:

      x += 1

      continue

    m = max(x, y)

    if m < min:

      min = m

  x += 1

a, b = sorted([min, n // min])

print(a, b)


D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

import sys

input = sys.stdin.readline

def inp():

	return (int(input()))

def inlt():

	return (list(map(int, input().split())))

def insr():

	s = input()

	return (list(s[:len(s) - 1]))

def invr():

	return (map(int, input().split()))

n,k=invr()

if(k<n or abs(k-n)%2!=0):

    print(-1)

else:

    if(n==0==k):

        print(0)

    elif(n==k):

        print(1)

        print(n)

    else:

        mp={}

        nd=(k-n)//2

        a=nd+n

        if(a^nd==n):

            print(2)

            print(a,nd)

        else:

            print(3)

            print(n,(k-n)//2,((k-n)//2))