B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

import java.io.*;

import java.lang.reflect.Array;

import java.math.BigInteger;

import java.util.*;

public class Main {

    static class Pair {

        double l,r;

        public Pair(double l,double r) {

            this.l=l;

            this.r=r;

        }

    }

    static int mod=1073741824;

    public static void main(String[] args) throws IOException

    {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        InputReader in = new InputReader(inputStream);

        OutputWriter out = new OutputWriter(outputStream);

        TaskC solver = new TaskC();

        solver.solve(1, in, out);

        out.close();

    }

    static class TaskC

    {

        public static void solve(int testNumber, InputReader in, OutputWriter out)

        {

            String s=in.readString();

            int n=s.length(),flag=0;

            ArrayList<Integer> al=new ArrayList<>();

            int l=0,r=n-1,k=0;

            while(l<r)

            {

                if(s.charAt(l)=='(' && s.charAt(r)==')')

                {

                    al.add(l+1);

                    al.add(r+1);

                    ++l;

                    --r;

                }

                else if(s.charAt(l)=='(' && s.charAt(r)!=')')

                {

                    --r;

                }

                else if(s.charAt(l)!='(' && s.charAt(r)==')')

                {

                    ++l;

                }

                else

                {

                    ++l;

                    --r;

                }

            }

            if(al.size()==0)

            {

                out.printLine(0);

            }

            else

            {

                out.printLine(1);

                out.printLine(al.size());

                Collections.sort(al);

                for(int i=0;i<al.size();++i)

                {

                    out.print(al.get(i)+" ");

                }

                out.printLine();

            }

        }

    }

    static class InputReader {

        private InputStream stream;

        private byte[] buf = new byte[1024];

        private int curChar;

        private int numChars;

        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {

            this.stream = stream;

        }

        public int read() {

            if (numChars == -1) {

                throw new InputMismatchException();

            }

            if (curChar >= numChars) {

                curChar = 0;

                try {

                    numChars = stream.read(buf);

                } catch (IOException e) {

                    throw new InputMismatchException();

                }

                if (numChars <= 0) {

                    return -1;

                }

            }

            return buf[curChar++];

        }

        public int readInt() {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            int sgn = 1;

            if (c == '-') {

                sgn = -1;

                c = read();

            }

            int res = 0;

            do {

                if (c < '0' || c > '9') {

                    throw new InputMismatchException();

                }

                res *= 10;

                res += c - '0';

                c = read();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public int[] nextIntArray(int arraySize) {

            int[] array = new int[arraySize];

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

                array[i] = readInt();

            }

            return array;

        }

        public String readString() {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            StringBuilder res = new StringBuilder();

            do {

                if (Character.isValidCodePoint(c)) {

                    res.appendCodePoint(c);

                }

                c = read();

            } while (!isSpaceChar(c));

            return res.toString();

        }

        public boolean isNewLine(int c) {

            return c == '\n';

        }

        public String nextLine() {

            int c = read();

            StringBuilder result = new StringBuilder();

            do {

                result.appendCodePoint(c);

                c = read();

            } while (!isNewLine(c));

            return result.toString();

        }

        public long nextLong() {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            int sign = 1;

            if (c == '-') {

                sign = -1;

                c = read();

            }

            long result = 0;

            do {

                if (c < '0' || c > '9') {

                    throw new InputMismatchException();

                }

                result *= 10;

                result += c & 15;

                c = read();

            } while (!isSpaceChar(c));

            return result * sign;

        }

        public long[] nextLongArray(int arraySize) {

            long array[] = new long[arraySize];

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

                array[i] = nextLong();

            }

            return array;

        }

        public double nextDouble() {

            double ret = 0, div = 1;

            byte c = (byte) read();

            while (c <= ' ') {

                c = (byte) read();

            }

            boolean neg = (c == '-');

            if (neg) {

                c = (byte) read();

            }

            do {

                ret = ret * 10 + c - '0';

            } while ((c = (byte) read()) >= '0' && c <= '9');

            if (c == '.') {

                while ((c = (byte) read()) >= '0' && c <= '9') {

                    ret += (c - '0') / (div *= 10);

                }

            }

            if (neg) {

                return -ret;

            }

            return ret;

        }

        public boolean isSpaceChar(int c) {

            if (filter != null) {

                return filter.isSpaceChar(c);

            }

            return isWhitespace(c);

        }

        public static boolean isWhitespace(int c) {

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

        }

        public interface SpaceCharFilter {

            public boolean isSpaceChar(int ch);

        }

    }

    static class CP {

        static boolean isPrime(long n) {

            if (n <= 1)

                return false;

            if (n == 2 || n == 3)

                return true;

            if (n % 2 == 0 || n % 3 == 0)

                return false;

            for (int i = 5; (long) i * i <= n; i += 6) {

                if (n % i == 0 || n % (i + 2) == 0)

                    return false;

            }

            return true;

        }

        static String addChar(String s, int n, String ch) {

            String res =s+String.join("", Collections.nCopies(n, ch));

            return res;

        }

        static int ifnotPrime(int[] prime, int x) {

            return (prime[x / 64] & (1 << ((x >> 1) & 31)));

        }

        static void makeComposite(int[] prime, int x) {

            prime[x / 64] |= (1 << ((x >> 1) & 31));

        }

        static ArrayList<Integer> bitWiseSieve(int n) {

            ArrayList<Integer> al = new ArrayList<>();

            int prime[] = new int[n / 64 + 1];

            for (int i = 3; i * i <= n; i += 2) {

                if (ifnotPrime(prime, i) == 0)

                    for (int j = i * i, k = i << 1;

                         j < n; j += k)

                        makeComposite(prime, j);

            }

            al.add(2);

            for (int i = 3; i <= n; i += 2)

                if (ifnotPrime(prime, i) == 0)

                    al.add(i);

            return al;

        }

        public static long[] sort(long arr[]){

            List<Long> list = new ArrayList<>();

            for(long n : arr){list.add(n);}

            Collections.sort(list);

            for(int i=0;i<arr.length;i++){

                arr[i] = list.get(i);

            }

            return arr;

        }

        static ArrayList<Integer> sieve(long size) {

            ArrayList<Integer> pr = new ArrayList<Integer>();

            boolean prime[] = new boolean[(int) size];

            for (int i = 2; i < prime.length; i++) prime[i] = true;

            for (int i = 2; i * i < prime.length; i++) {

                if (prime[i]) {

                    for (int j = i * i; j < prime.length; j += i) {

                        prime[j] = false;

                    }

                }

            }

            for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);

            return pr;

        }

        static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {

            ArrayList<Integer> al=new ArrayList<>();

            if (l == 1) ++l;

            int max = r - l + 1;

            int arr[] = new int[max];

            for (int p : primes) {

                if (p * p <= r) {

                    int i = (l / p) * p;

                    if (i < l) i += p;

                    for (; i <= r; i += p) {

                        if (i != p) {

                            arr[i - l] = 1;

                        }

                    }

                }

            }

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

                if (arr[i] == 0) {

                    al.add(l+i);

                }

            }

            return al;

        }

        static boolean isfPrime(long n, int iteration) {

            if (n == 0 || n == 1)

                return false;

            if (n == 2)

                return true;

            if (n % 2 == 0)

                return false;

            Random rand = new Random();

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

                long r = Math.abs(rand.nextLong());

                long a = r % (n - 1) + 1;

                if (modPow(a, n - 1, n) != 1)

                    return false;

            }

            return true;

        }

        static long modPow(long a, long b, long c) {

            long res = 1;

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

                res *= a;

                res %= c;

            }

            return res % c;

        }

        private static long binPower(long a, long l, long mod) {

            long res = 0;

            while (l > 0) {

                if ((l & 1) == 1) {

                    res = mulmod(res, a, mod);

                    ;

                    l >>= 1;

                }

                a = mulmod(a, a, mod);

            }

            return res;

        }

        private static long mulmod(long a, long b, long c) {

            long x = 0, y = a % c;

            while (b > 0) {

                if (b % 2 == 1) {

                    x = (x + y) % c;

                }

                y = (y * 2L) % c;

                b /= 2;

            }

            return x % c;

        }

        static long binary_Expo(long a, long b) {

            long res = 1;

            while (b != 0) {

                if ((b & 1) == 1) {

                    res *= a;

                    --b;

                }

                a *= a;

                b /= 2;

            }

            return res;

        }

        static long Modular_Expo(long a, long b) {

            long res = 1;

            while (b != 0) {

                if ((b & 1) == 1) {

                    res = (res * a) % 1000000007 ;

                    --b;

                }

                a = (a * a) % 1000000007;

                b /= 2;

            }

            return res%1000000007;

        }

        static int i_gcd(int a, int b) {

            while (true) {

                if (b == 0)

                    return a;

                int c = a;

                a = b;

                b = c % b;

            }

        }

        static long gcd(long a, long b) {

            if (b == 0)

                return a;

            return gcd(b, a % b);

        }

        static long ceil_div(long a, long b) {

            return (a + b - 1) / b;

        }

        static int getIthBitFromInt(int bits, int i) {

            return (bits >> (i - 1)) & 1;

        }

        private static TreeMap<Long, Long> primeFactorize(long n) {

            TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());

            long cnt = 0;

            long total = 1;

            for (long i = 2; (long) i * i <= n; ++i) {

                if (n % i == 0) {

                    cnt = 0;

                    while (n % i == 0) {

                        ++cnt;

                        n /= i;

                    }

                    pf.put(cnt, i);

                    //total*=(cnt+1);

                }

            }

            if (n > 1) {

                pf.put(1L, n);

                //total*=2;

            }

            return pf;

        }

        static long upper_Bound(long a[], long x) {

            long l = -1, r = a.length;

            while (l + 1 < r) {

                long m = (l + r) >>> 1;

                if (a[(int) m] <= x)

                    l = m;

                else

                    r = m;

            }

            return l + 1;

        }

        static int lower_Bound(ArrayList<Integer> a,int x) {

            int l = 0, r = a.size()-1,ans=-1,mid=0;

            while(l<=r)

            {

                mid=(l+r)>>1;

                if(a.get(mid)<=x)

                {

                    ans=mid;

                    l=mid+1;

                }

                else

                {

                    r=mid-1;

                }

            }

            return ans;

        }

        static int lower_Bound(int a[],int x) {

            int l = -1, r = a.length;

            while (l + 1 < r) {

                int m = (l + r) >>> 1;

                if (a[(int) m] >= x)

                    r = m;

                else

                    l = m;

            }

            return r;

        }

        static int upperBound(int a[], int x) {// x is the key or target value

            int l=-1,r=a.length;

            while(l+1<r) {

                int m=(l+r)>>>1;

                if(a[m]<=x) l=m;

                else r=m;

            }

            return l+1;

        }

        static int bsh(int  a[],int t) {

            int ans =-1;

            int i = 0, j = a.length - 1;

            while (i <= j) {

                int mid = i + (j - i) / 2;

                if (a[mid] > t) {

                    ans = mid;

                    //System.out.print("uppr "+a[ans]);

                    j=mid-1;

                }

                else{

                    //System.out.print("less "+a[mid]);

                    i=mid+1;

                }

            }

            return ans;

        }

        static int bsl(int a[],int t) {

            int ans =-1;

            int i = 0, j = a.length-1;

            while (i <= j) {

                int mid = i + (j - i) / 2;

                if (a[mid] <= t) {

                    ans = mid;

                    i=mid+1;

                } else if (a[mid] > t) {

                    j = mid - 1;

                }

            }

            return ans;

        }

        static int upper_Bound(ArrayList<Integer> a,int x)  //closest to the right

        {

            int l = 0, r = a.size()-1,ans=-1,mid=0;

            while(l<=r)

            {

                mid=(l+r)>>1;

                if(a.get(mid)>x)

                {

                    ans=mid;

                    r=mid-1;

                }

                else

                {

                    l=mid+1;

                }

            }

            return ans;

        }

        static boolean isSquarefactor(int x, int factor, int target) {

            int s = (int) Math.round(Math.sqrt(x));

            return factor * s * s == target;

        }

        static boolean isSquare(int x) {

            int s = (int) Math.round(Math.sqrt(x));

            return x * x == s;

        }

        static void sort(int a[]) // heap sort

        {

            PriorityQueue<Integer> q = new PriorityQueue<>();

            for (int i = 0; i < a.length; i++)

                q.add(a[i]);

            for (int i = 0; i < a.length; i++)

                a[i] = q.poll();

        }

        static void shuffle(int[] in) {

            for (int i = 0; i < in.length; i++) {

                int idx = (int) (Math.random() * in.length);

                fast_swap(in, idx, i);

            }

        }

        static boolean isPalindrome(String s)

        {

            StringBuilder sb=new StringBuilder(s);

            sb.reverse();

            if(s.equals(sb.toString()))

            {

                return true;

            }

            return false;

        }

        static int[] computeLps(String pat) {

            int len = 0, i = 1, m = pat.length();

            int lps[] = new int[m];

            lps[0] = 0;

            while (i < m) {

                if (pat.charAt(i) == pat.charAt(len)) {

                    ++len;

                    lps[i] = len;

                    ++i;

                } else {

                    if (len != 0) {

                        len = lps[len - 1];

                    } else {

                        lps[i] = len;

                        ++i;

                    }

                }

            }

            return lps;

        }

        static void kmp(String s, String pat,int[] prf,int[] st) {

            int n = s.length(), m = pat.length();

            int lps[] = computeLps(pat);

            int i = 0, j = 0;

            while (i < n) {

                if (s.charAt(i) == pat.charAt(j)) {

                    i++;

                    j++;

                    if (j == m) {

                        ++prf[(i-j)+m];

                        ++st[(i-j)+1];

                        j=lps[j - 1];

                    }

                } else {

                    if (j != 0) {

                        j = lps[j - 1];

                    } else {

                        i++;

                    }

                }

            }

        }

        static void reverse_ruffle_sort(int a[]) {

            shuffle(a);

            Arrays.sort(a);

            for (int l = 0, r = a.length - 1; l < r; ++l, --r)

                fast_swap(a, l, r);

        }

        static void ruffle_sort(int a[]) {

            shuffle(a);

            Arrays.sort(a);

        }

        static int getMax(int arr[], int n) {

            int mx = arr[0];

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

                if (arr[i] > mx)

                    mx = arr[i];

            return mx;

        }

        static ArrayList<Long> primeFactors(long n) {

            ArrayList<Long> al = new ArrayList<>();

            al.add(1L);

            while (n % 2 == 0) {

                if(!al.contains(2L))

                {

                    al.add(2L);

                }

                n /= 2L;

            }

            for (int i = 3; (long) i * i <= n; i += 2) {

                while ((n % i == 0)) {

                    if(!al.contains((long)i))

                    {

                        al.add((long) i);

                    }

                    n /= i;

                }

            }

            if (n > 2) {

                if(!al.contains(n))

                {

                    al.add(n);

                }

            }

            return al;

        }

        static int[] z_function(String s) {

            int n = s.length(), z[] = new int[n];

            for (int i = 1, l = 0, r = 0; i < n; ++i) {

                if (i <= r)

                    z[i] = Math.min(z[i - l], r - i + 1);

                while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))

                    ++z[i];

                if (i + z[i] - 1 > r) {

                    l = i;

                    r = i + z[i] - 1;

                }

            }

            return z;

        }

        static void swap(int a[], int idx1, int idx2) {

            a[idx1] += a[idx2];

            a[idx2] = a[idx1] - a[idx2];

            a[idx1] -= a[idx2];

        }

        static void fast_swap(int[] a, int idx1, int idx2) {

            if (a[idx1] == a[idx2])

                return;

            a[idx1] ^= a[idx2];

            a[idx2] ^= a[idx1];

            a[idx1] ^= a[idx2];

        }

        public static void fast_sort(long[] array) {

            ArrayList<Long> copy = new ArrayList<>();

            for (long i : array)

                copy.add(i);

            Collections.sort(copy);

            for (int i = 0; i < array.length; i++)

                array[i] = copy.get(i);

        }

        static int divCount(int n) {

            boolean hash[] = new boolean[n + 1];

            Arrays.fill(hash, true);

            for (int p = 2; p * p < n; p++)

                if (hash[p] == true)

                    for (int i = p * 2; i < n; i += p)

                        hash[i] = false;

            int total = 1;

            for (int p = 2; p <= n; p++) {

                if (hash[p]) {

                    int count = 0;

                    if (n % p == 0) {

                        while (n % p == 0) {

                            n = n / p;

                            count++;

                        }

                        total = total * (count + 1);

                    }

                }

            }

            return total;

        }

        static long binomialCoeff(long n,long k)

        {

            long res = 1;

            // Since C(n, k) = C(n, n-k)

            if (k > n - k)

                k = n - k;

            // Calculate value of

            // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]

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

                res = (res*(n - i));

                res /= (i + 1);

            }

            return res;

        }

        static long c(long fact[],long n,long k)

        {

            if(k>n) return 0;

            long res=fact[(int)n];

            res= (int) ((res * Modular_Expo(fact[(int)k], mod - 2))%mod);

            res= (int) ((res * Modular_Expo(fact[(int)n - (int)k], mod - 2))%mod);

            return res%mod;

        }

        public static ArrayList<Long> getFactors(long x) {

            ArrayList<Long> facts=new ArrayList<>();

            for(long i=2;i*i<=x;++i)

            {

                if(x%i==0)

                {

                    facts.add(i);

                    if(i!=x/i)

                    {

                        facts.add(x/i);

                    }

                }

            }

            return facts;

        }

        public static HashMap<Integer, Integer> sortMap(HashMap<Integer, Integer> map) {

            List<Map.Entry<Integer,Integer>> list=new LinkedList<>(map.entrySet());

            Collections.sort(list,(o1,o2)->o2.getValue()-o1.getValue());

            HashMap<Integer,Integer> temp=new LinkedHashMap<>();

            for(Map.Entry<Integer,Integer> i:list)

            {

                temp.put(i.getKey(),i.getValue());

            }

            return temp;

        }

        public static long lcm(long l,long l2) {

            long val=CP.gcd(l,l2);

            return (l*l2)/val;

        }

    }

    static void py() {

        System.out.println("YES");

    }

    static void pn() {

        System.out.println("NO");

    }

    static class OutputWriter {

        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {

            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));

        }

        public OutputWriter(Writer writer) {

            this.writer = new PrintWriter(writer);

        }

        public void print(int[] array) {

            for (int i = 0; i < array.length; i++) {

                if (i != 0) {

                    writer.print(' ');

                }

                writer.print(array[i]);

            }

        }

        public void printLine(int[] array) {

            print(array);

            writer.println();

        }

        public void close() {

            writer.close();

        }

        public void printLine(long i) {

            writer.println(i);

        }

        public void printLine(int i) {

            writer.println(i);

        }

        public void printLine(char c)

        {

            writer.println(c);

        }

        public void print(Object... objects) {

            for (int i = 0; i < objects.length; i++) {

                if (i != 0) {

                    writer.print(' ');

                }

                writer.print(objects[i]);

            }

        }

        public void printLine(Object... objects) {

            print(objects);

            writer.println();

        }

    }

}


A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6
8 8 0 0
1 10 0 3
17 31 10 4
2 1 0 0
5 10 3 9
10 10 4 8
OutputCopy56
6
442
1
45
80
NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

import java.util.*;

import java.io.*;

import java.lang.*;

import java.math.*;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.StringTokenizer;

import java.math.BigInteger;

import static java.lang.Math.max;

public class HelloWorld {

    public static void main(String[] args) throws IOException {

        Scanner input=new Scanner(System.in);

        //static FastReader input=new FastReader();

        //static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

        int t=input.nextInt();

        while(t>0) {

            int n,i,m,j,k,f;

            long count=0,a,b,x,y,s1,s2,s3,s4,s;

            a=input.nextInt();

            b=input.nextInt();

            x=input.nextInt();

            y=input.nextInt();

            x++;

            y++;

            //ArrayList<Long>ara= new ArrayList<>();

            //long ara[]=new long[i];

            //Collections.sort(ara1);

            s1=(x-1)*b;

            s2=a*(y-1);

            s3=(a-x)*b;

            s4=a*(b-y);

            s=max(s4,max(s3,max(s2,s1)));

            System.out.println(s);

            //System.out.println(s1+" "+s2+" "+s3+" "+s4);

            t--;

        }

        input.close();

        System.out.close();

    }

    /*static class FastReader

    {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(new InputStreamReader(System.in));

        }

        String next()

        {

            while (st == null || !st.hasMoreElements())

            {

                try

                {

                    st = new StringTokenizer(br.readLine());

                }

                catch (IOException  e)

                {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        int[] readIntArray(int n)

        {

            int a[]=new int[n];

            for(int i=0;i<n;i++)a[i]=nextInt();

            return a;

        }

        long[] readLongArray(int n)

        {

            long a[]=new long[n];

            for(int i=0;i<n;i++)a[i]=nextLong();

            return a;

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException e)

            {

                e.printStackTrace();

            }

            return str;

        }

    }*/

}


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

			 import java.util.*;

			 import java.math.*;

			 import java.io.*;

			 import java.util.stream.Collectors;

	import java.text.DecimalFormat;

		       public class A{

		              static FastScanner scan=new FastScanner();

		              public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));

		static int n;

		static long PS[];

		static long MIN[];

		static boolean check(long x,long TH)

		{

			TH+=(PS[n-1]*((x-(x%n))/n));

		//	TH+=(PS[n-1]*((x-(x%n))/n));

			x=x%n;

			x--;

		//	out.println(x);

			if(x>=0)

			TH+=MIN[(int)x];

			return TH<=0;

		}

				public static void main(String[] args)  throws Exception

				     {

					int tt=1;

		//	System.out.println(check(0));

		//			tt=scan.nextInt();

			//	scan=new FastScanner("clumsy.in");

				//out=new PrintWriter("clumsy.out");

				outer:while(tt-->0)

					{

long H=scan.nextLong();

long TH=H;

						 n=scan.nextInt();

						 long arr[]=new long[n];

						 MIN=new long[n];

						 PS=new long[n];

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

						 {

						 	arr[i]=scan.nextLong();

						 	TH+=arr[i];

						 	if(TH<=0)

						 	{

						 		out.println(i+1);

						 		out.close();

						 		return;

						 	}

						 }

						 PS[0]=arr[0];

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

						 {

						 	PS[i]=arr[i];

						 	PS[i]+=PS[i-1];

						 }

						 MIN[0]=PS[0];

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

						 {

						 	MIN[i]=Math.min(PS[i],MIN[i-1]);

						 }

						 if(PS[n-1]>=0)

						 {

						 	out.println(-1);

						 	out.close();

						 	return;

						 }

						 long l=1,r=(long)1e18,ans=(long)1e18+5;

//out.println(PS[n-1]);

//out.println(H)

					//out.println(check(4301,H));

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

						{

							TH=H;

							TH+=PS[i];

							l=1;

							r=(long)(1e12);

						//	if(i==2)

						//		out.println(TH+PS[n-1]);

							while(l<=r)

							{

								long mid=(l+r)/2;

								if(check(mid*n,TH))

								{

									//if(i==3)

									///out.println(mid*n);

									r=mid-1;

									ans=Math.min(ans,(i+1)+mid*n);

								}

								else l=mid+1;

							}

						}

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

						{

							TH=H;

							TH+=PS[i];

							l=1;

							r=(long)(1e9);

						//	if(i==2)

						//		out.println(TH+PS[n-1]);

							while(l<=r)

							{

								long mid=(l+r)/2;

								if(check(mid*n,TH))

								{

									//if(i==3)

									///out.println(mid*n);

									r=mid-1;

									ans=Math.min(ans,(i+1)+mid*n);

								}

								else l=mid+1;

							}

						}

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

						{

							TH=H;

							TH+=PS[i];

							l=1;

							r=(long)(1e7);

						//	if(i==2)

						//		out.println(TH+PS[n-1]);

							while(l<=r)

							{

								long mid=(l+r)/2;

								if(check(mid*n,TH))

								{

									//if(i==3)

									///out.println(mid*n);

									r=mid-1;

									ans=Math.min(ans,(i+1)+mid*n);

								}

								else l=mid+1;

							}

						}

						 out.println(ans);

	}

				out.close();

							}

										     static class FastScanner

								{

								    private int BS = 1 << 16;

								    private char NC = (char) 0;

								    private byte[] buf = new byte[BS];

								    private int bId = 0, size = 0;

								    private char c = NC;

								    private double cnt = 1;

								    private BufferedInputStream in;

								    public FastScanner() {

								        in = new BufferedInputStream(System.in, BS);

								    }

								    public FastScanner(String s) {

								        try {

								            in = new BufferedInputStream(new FileInputStream(new File(s)), BS);

								        } catch (Exception e) {

								            in = new BufferedInputStream(System.in, BS);

								        }

								    }

								    private char getChar() {

								        while (bId == size) {

								            try {

								                size = in.read(buf);

								            } catch (Exception e) {

								                return NC;

								            }

								            if (size == -1) return NC;

								            bId = 0;

								        }

								        return (char) buf[bId++];

								    }

								    public int nextInt() {

								        return (int) nextLong();

								    }

								    public int[] nextInts(int N) {

								        int[] res = new int[N];

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

								            res[i] = (int) nextLong();

								        }

								        return res;

								    }

								    public long[] nextLongs(int N) {

								        long[] res = new long[N];

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

								            res[i] = nextLong();

								        }

								        return res;

								    }

								    public long nextLong() {

								        cnt = 1;

								        boolean neg = false;

								        if (c == NC) c = getChar();

								        for (; (c < '0' || c > '9'); c = getChar()) {

								            if (c == '-') neg = true;

								        }

								        long res = 0;

								        for (; c >= '0' && c <= '9'; c = getChar()) {

								            res = (res << 3) + (res << 1) + c - '0';

								            cnt *= 10;

								        }

								        return neg ? -res : res;

								    }

								    public double nextDouble() {

								        double cur = nextLong();

								        return c != '.' ? cur : cur + nextLong() / cnt;

								    }

								    public double[] nextDoubles(int N) {

								        double[] res = new double[N];

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

								            res[i] = nextDouble();

								        }

								        return res;

								    }

								    public String next() {

								        StringBuilder res = new StringBuilder();

								        while (c <= 32) c = getChar();

								        while (c > 32) {

								            res.append(c);

								            c = getChar();

								        }

								        return res.toString();

								    }

								    public String nextLine() {

								        StringBuilder res = new StringBuilder();

								        while (c <= 32) c = getChar();

								        while (c != '\n') {

								            res.append(c);

								            c = getChar();

								        }

								        return res.toString();

								    }

								    public boolean hasNext() {

								        if (c > 32) return true;

								        while (true) {

								            c = getChar();

								            if (c == NC) return false;

								            else if (c > 32) return true;

								        }

								    }

								}

										     static class Pair implements Comparable<Pair>{

										            public long x, y,z;

										            public Pair(long x1, long y1,long z1) {

										                x=x1;

										                y=y1;

										                z=z1;

										            }

										             public Pair(long x1, long y1) {

										                x=x1;

										                y=y1;

										            }

										            @Override

										            public int hashCode() {

										                return (int)(x + 31 * y);

										            }

										            public String toString() {

										                return x + " " + y+" "+z;

										            }

										            @Override

										            public boolean equals(Object o){

										                if (o == this) return true;

										                if (o.getClass() != getClass()) return false;

										                Pair t = (Pair)o;

										                return t.x == x && t.y == y&&t.z==z;

										            }

										    public int compareTo(Pair o)

										    {

										return (int)(o.x-x);

										        }

										    }

										}


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.

import java.util.*;

import java.io.*;

public class Main {

		static long mod = 1000000007;

		static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

		public static void main(String[] args) throws IOException  {

			FastReader sc = new FastReader();

					int n = sc.nextInt();

					char arr[] = sc.next().toCharArray();

					int fst = 0;

					int scnd = 0;

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

						if( arr[i] == '(') {

							fst++;

						}

						else {

							scnd++;

						}

					}

					if( fst!= scnd) {

						out.println(-1);

					}

					else {

						fst = 0;

						scnd = 0;

						int cost = 0;

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

							if( arr[i] == '(') {

								fst++;

							}

							else {

								scnd++;

							}

							if( scnd > fst) {

								int len = 1;

								int count = 1;

								while( i < n-1 && arr[i+1] == ')') {

									i++;

									len++;

									count++;

								}

								while( count!= 0) {

									i++;

									len++;

									if( arr[i] == ')') {

										count++;

									}

									else {

										count--;

									}

								}

								cost+=len;

								fst = scnd;

							}

						}

						out.println(cost);

					}

				out.flush();

		}

		public static int[] nextLargerElement(int[] arr, int n)	{

			Stack<Integer> stack = new Stack<>();

			int rtrn[] = new int[n];

			rtrn[n-1] = -1;

	        stack.push( n-1);

	        for( int i = n-2 ;i >= 0 ; i--){

	            int temp = arr[i];

	            int lol = -1;

	            while( !stack.isEmpty() && arr[stack.peek()] <= temp){

	            	if(arr[stack.peek()] == temp ) {

	            		lol = stack.peek();

	            	}

	                stack.pop();

	            }

	            if( stack.isEmpty()){

	            	if( lol != -1) {

	            		rtrn[i] = lol;

	            	}

	            	else {

	            		rtrn[i] = -1;

	            	}

	            }

	            else{

	            	rtrn[i] = stack.peek();

	            }

	            stack.push( i);

	        }

	        return rtrn;

		}

		static int gcd(int a, int b)

		{

			if (a == 0)

				return b;

			return gcd(b % a, a);

		}

		 static int lcm(int a, int b)

		 {

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

		 }

		 static HashMap<Long,Long> primefactor( long n){

			 HashMap<Long ,Long> hm = new HashMap<>();

			 long temp = 0;

			 while( n%2 == 0) {

				 temp++;

				 n/=2;

			 }

			 if( temp!= 0) {

				 hm.put( 2L, temp);

			 }

			 long c = (long)Math.sqrt(n);

			 for( long i = 3 ; i <= c ; i+=2) {

				 temp = 0;

				 while( n% i == 0) {

					 temp++;

					 n/=i;

				 }

				 if( temp!= 0) {

					 hm.put( i, temp);

				 }

	 		 }

	 		 if( n!= 1) {

	 			 hm.put( n , 1L);

	 		 }

	 		 return hm;

		 }

		 static class FastReader {

			 BufferedReader br;

			 StringTokenizer st;

			 public FastReader()

			 {

				 br = new BufferedReader(new InputStreamReader(System.in));

			 }

			 String next()

			 {

				 while (st == null || !st.hasMoreElements()) {

					 try {

						 st = new StringTokenizer(br.readLine());

					 }

					 catch (IOException e) {

						 e.printStackTrace();

					 }

				 }

				 return st.nextToken();

			 }

			 int nextInt() { return Integer.parseInt(next()); }

			 long nextLong() { return Long.parseLong(next()); }

			 double nextDouble()

			 {

				 return Double.parseDouble(next());

			 }

			 String nextLine()

			 {

				 String str = "";

				 try {

					 str = br.readLine();

				 }

				 catch (IOException e) {

					 e.printStackTrace();

				 }

				 return str;

			 }

		 }

}


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

import javax.sound.midi.Soundbank;

import javax.swing.*;

import javax.swing.text.rtf.RTFEditorKit;

import java.awt.*;

import java.io.*;

import java.lang.reflect.Array;

import java.math.BigDecimal;

import java.math.BigInteger;

import java.math.MathContext;

import java.math.RoundingMode;

import java.nio.charset.StandardCharsets;

import java.util.*;

import java.util.List;

import java.util.zip.InflaterInputStream;

public class Main {

    static int N = 100001;

    // Array to store inverse of 1 to N

    static long[] factorialNumInverse = new long[N + 1];

    // Array to precompute inverse of 1! to N!

    static long[] naturalNumInverse = new long[N + 1];

    // Array to store factorial of first N numbers

    static long[] fact = new long[N + 1];

    // Function to precompute inverse of numbers

    public static void InverseofNumber(int p)

    {

        naturalNumInverse[0] = naturalNumInverse[1] = 1;

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

            naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;

    }

    public static void InverseofFactorial(int p)

    {

        factorialNumInverse[0] = factorialNumInverse[1] = 1;

        // Precompute inverse of natural numbers

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

            factorialNumInverse[i] = (naturalNumInverse[i] *

                    factorialNumInverse[i - 1]) % p;

    }

    // Function to calculate factorial of 1 to N

    public static void factorial(int p)

    {

        fact[0] = 1;

        // Precompute factorials

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

        {

            fact[i] = (fact[i - 1] * (long)i) % p;

        }

    }

    public static long ncp(int N, int R, int p)

    {

        // n C r = n!*inverse(r!)*inverse((n-r)!)

        long ans = ((fact[N] * factorialNumInverse[R]) %

                p * factorialNumInverse[N - R]) % p;

        return ans;

    }

    public static void main(String[] args) throws IOException {

        Reader.init(System.in);

        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));

        int t = 1;

        while ( t > 0){

            int n = Reader.nextInt();

            int h = Reader.nextInt();

            int l = Reader.nextInt();

            int r = Reader.nextInt();

            int [] arr = new int[n];

            int i = 0;

            while ( i < n){

                arr[i] = Reader.nextInt();

                i++;

            }

            output.write(answer(arr,n,h,l,r)+"\n");

            t--;

        }

        output.flush();

    }

    private static int answer(int [] arr,int n,int h,int l,int r){

        int [][] dp = new int[n][h];

        boolean [][] dp2 = new boolean[n][h];

        int i = 0;

        int j = 0;

        while ( j < h){

            if ( j == arr[i] || (j == arr[i]-1)) {

                dp2[0][j] = true;

                if ( l <= j && j <= r){

                    dp[0][j] = 1;

                }

            }

            j++;

        }

        i = 1;

        while ( i < n){

            j = 0;

            while ( j < h){

                if ( dp2[i-1][j]){

                    int next = ( j + arr[i])%h;

                    int next2 = (j+(arr[i]-1))%h;

                    dp2[i][next] = true;

                    dp2[i][next2] = true;

                    if (  l <= next && r >= next){

                        dp[i][next] = (int)max(dp[i][next],1+dp[i-1][j]);

                    }

                    else{

                        dp[i][next] = (int)max(dp[i][next],dp[i-1][j]);

                    }

                    if ( l <= next2 && r >= next2){

                        dp[i][next2] = (int)max(dp[i][next2],1+dp[i-1][j]);

                    }

                    else{

                        dp[i][next2] = (int)max(dp[i][next2],dp[i-1][j]);

                    }

                }

                j++;

            }

            i++;

        }

        j = 0;

        int ans = 0;

        while ( j < h){

            if (dp[n-1][j] > ans){

                ans = dp[n-1][j];

            }

            j++;

        }

        return ans;

    }

    private static boolean knapsack01(ArrayList<Integer> arr,int size){

        boolean [][] dp = new boolean[arr.size()][size+1];

        int i  = 0;

        int j  = 0;

        while ( i <  arr.size() ){

            dp[i][0] = true;

            i++;

        }

        i = 0;

        while ( j <= size){

            if ( j == arr.get(0)){

                dp[0][j] = true;

            }

            j++;

        }

        i = 1;

        while ( i < arr.size()){

            j = 1;

            while ( j <= size){

                dp[i][j] = dp[i-1][j];

                if ( j >= arr.get(i)){

                    dp[i][j] = (dp[i][j] || dp[i-1][j-arr.get(i)]);

                }

                j++;

            }

            i++;

        }

        return dp[arr.size()-1][size];

    }

    public static void primeFactorisation(long n,HashMap<Long,Integer> map){

        long i = 2;

        while ( n%i == 0){

            if ( map.containsKey(i)){

                map.put(i,map.get(i)+1);

            }

            else{

                map.put(i,1);

            }

            n/=i;

        }

        i = 3;

        long last = (long)Math.pow(n,0.5);

        while ( i <= last){

            while ( n%i == 0){

                if ( map.containsKey(i)){

                    map.put(i,map.get(i)+1);

                }

                else{

                    map.put(i,1);

                }

                n/=i;

            }

            i++;

        }

        if ( n > 2){

            map.put(n,1);

        }

    }

    public  static  boolean prime(int n){

        int i = 2;

        int r = (int)Math.pow(n,0.5);

        boolean ans = true;

        while ( i<=r){

            if ( n%i == 0){

                ans = false;

                break;

            }

            i++;

        }

        return  ans;

    }

    public static long log2(long N)

    {

        long result = (long)(Math.log(N) / Math.log(2));

        return result;

    }

    private static int bs(int low,int high,int [] array,long find){

        if ( low <= high ){

            int  mid = low + (high-low)/2;

            if ( array[mid] > find){

                high = mid -1;

                return bs(low,high,array,find);

            }

            else if ( array[mid] < find){

                low = mid+1;

                return bs(low,high,array,find);

            }

            return mid;

        }

        return -1;

    }

    private static long max(long a, long b) {

        return  Math.max(a,b);

    }

    private static long min(long a,long b){

        return  Math.min(a,b);

    }

    public static long modularExponentiation(long a,long b,long mod){

        if ( b == 1){

            return a;

        }

        else{

            long ans = modularExponentiation(a,b/2,mod)%mod;

            if ( b%2 == 1){

                return (a*((ans*ans)%mod))%mod;

            }

            return ((ans*ans)%mod);

        }

    }

    public static long sum(long n){

        return  (n*(n+1))/2;

    }

    public static long abs(long a){

        return a < 0 ? (-1*a) : a;

    }

    public static long gcd(long a,long b){

        if ( a == 0){

            return b;

        }

        else{

            return gcd(b%a,a);

        }

    }

}

class DComparator implements Comparator<Integer>{

    @Override

    public int compare(Integer o1, Integer o2) {

        if ( o2 > o1){

            return 1;

        }

        else if ( o2 < o1){

            return -1;

        }

        else{

            return 0;

        }

    }

}

class NodeComparator implements Comparator<Node>{

    @Override

    public int compare(Node o1,Node o2){

        if ( o2.count < o1.count){

            return 1;

        }

        else{

            return -1;

        }

    }

}

class Node{

    int  value;

    int count;

    Node( int V,int C ){

        value = V;

        count = C;

    }

}

class Reader {

    static BufferedReader reader;

    static StringTokenizer tokenizer;

    static void init(InputStream input) {

        reader = new BufferedReader(

                new InputStreamReader(input));

        tokenizer = new StringTokenizer("");

    }

    static String next() throws IOException {

        while ( ! tokenizer.hasMoreTokens() ) {

            tokenizer = new StringTokenizer(

                    reader.readLine() );

        }

        return tokenizer.nextToken();

    }

    static int nextInt() throws IOException {

        return Integer.parseInt( next() );

    }

    static double nextDouble() throws IOException {

        return Double.parseDouble( next() );

    }

    static long nextLong() throws IOException{

        return Long.parseLong(next());

    }

}

class SegTree{

    int [] min;

    int [] max;

    SegTree(int s){

        min  = new int[s];

        max  = new int[s];

    }

    public void build(int [] arr, int v,int l,int r){

        if ( l == r){

            min[v] = arr[l];

            max[v] = arr[r];

        }

        else{

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

            build(arr,2*v+1,l,mid);

            build(arr,2*v+2,mid+1,r);

            min[v] = min[2*v+1];

            max[v] = max[2*v+1];

            if ( min[v]> min[2*v+2]){

                min[v] = min[2*v+2];

            }

            if ( max[v] < max[2*v+2]){

                max[v] = max[2*v+2];

            }

        }

    }

    public int findMin(int v,int l,int r,int x,int y){

        if ( x > r || y < l){

            return Integer.MAX_VALUE;

        }

        else if ( x <= l && r <= y){

            return min[v];

        }

        else{

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

            int a = findMin(2*v+1,l,mid,x,y);

            int b = findMin(2*v+2,mid+1,r,x,y);

            return a < b ? a: b;

        }

    }

    public int findMax(int v,int l,int r,int x,int y){

        if ( x > r || y < l){

            return Integer.MIN_VALUE;

        }

        else if ( x <= l && r <= y){

            return max[v];

        }

        else{

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

            int a = findMax(2*v+1,l,mid,x,y);

            int b = findMax(2*v+2,mid+1,r,x,y);

            return a < b ? b: a;

        }

    }

}


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 java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (t.me/musin_acm)
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    OutputWriter out = new OutputWriter(outputStream);
    BPodarok solver = new BPodarok();
    solver.solve(1, in, out);
    out.close();
  }

  static class BPodarok {
    Random rnd = new Random(239);

    public void solve(int testNumber, InputReader in, OutputWriter out) {
      if (false) {
        test3();
      }
      int n = in.readInt();
      int[] a = in.readIntArray(n);
//    out.print(naive(a));
      out.print(newSolve(a));
    }

    int newSolve(int[] a) {
      int res = 0;
      for (int b = 0; b < 30; b++) {
        if (newSolve(a, b) % 2 == 1) {
          res |= 1 << b;
        }
      }
      return res;
    }

    long newSolve(int[] a, int bit) {
      int[] b = new int[a.length];
      for (int i = 0; i < a.length; i++) {
        b[i] = a[i] % (1 << (bit + 1));
      }
      Arrays.sort(b);
      int L1 = 1 << bit;
      int R1 = (L1 << 1) - 1;
      int L2 = (L1 << 1) | L1;
      int R2 = (L1 << 1) | R1;
      long count = 0;
      for (int x : b) {
        count += getCount(b, L1 - x, R1 - x);
        count += getCount(b, L2 - x, R2 - x);
        if (inside(L1 - x, R1 - x, x)) {
          count--;
        }
        if (inside(L2 - x, R2 - x, x)) {
          count--;
        }
      }
      return count >> 1;
    }

    boolean inside(int l, int r, int x) {
      return l <= x && x <= r;
    }

    int getCount(int[] a, int l, int r) {
      return getCount(a, r) - getCount(a, l - 1);
    }

    int getCount(int[] a, int x) {
      int l = -1;
      int r = a.length;
      while (r - l > 1) {
        int m = l + r >> 1;
        if (a[m] <= x) {
          l = m;
        } else {
          r = m;
        }
      }
      return l;
    }

    int naive(int[] a) {
      int res = 0;
      for (int i = 0; i < a.length; i++) {
        for (int j = i + 1; j < a.length; j++) {
          res ^= a[i] + a[j];
        }
      }
      return res;
    }

    void test3() {
      for (int t = 0; ; t++) {
        int n = 10;
        int m = 5;
        int[] a = genArray(n, m);
        int naive = naive(a);
        int sol = newSolve(a);
        if (naive != sol) {
          System.err.println("FF");
          naive = naive(a);
          sol = newSolve(a);
        }
      }
    }

    int[] genArray(int n, int m) {
      int[] a = new int[n];
      for (int i = 0; i < n; i++) {
        a[i] = rnd.nextInt(m);
      }
      return a;
    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
      this.writer = new PrintWriter(writer);
    }

    public void close() {
      writer.close();
    }

    public void print(int i) {
      writer.print(i);
    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int[] readIntArray(int size) {
      int[] array = new int[size];
      for (int i = 0; i < size; i++) {
        array[i] = readInt();
      }
      return array;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public int readInt() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int res = 0;
      do {
        if (c < '0' || c > '9') {
          throw new InputMismatchException();
        }
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }
}


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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;

public class Codeforces {
	// static int mod = 998244353;
	static int mod = 1000000007;

	public static void main(String[] args) {
		FastReader fastReader = new FastReader();
		PrintWriter out = new PrintWriter(System.out);
		int t = 1;

		/*
		 * n = 1500 , k = 30;
		 *
		 *
		 */
		while (t-- > 0) {
			int n = fastReader.nextInt();
			int k = fastReader.nextInt();
			HashMap<String, Integer> map = new HashMap<>();
			String arr[] = new String[n];
			for (int i = 0; i < n; i++) {
				String cur = fastReader.nextLine();
				arr[i] = cur;
				map.put(cur, map.getOrDefault(cur, 0) + 1);
			}
			long ans = 0;
			for (int i = 0; i < n; i++) {
				for (int j = i + 1; j < n; j++) {
					char cur[] = new char[k];
					for (int node = 0; node < k; node++) {
						if (arr[i].charAt(node) == arr[j].charAt(node)) {
							cur[node] = arr[i].charAt(node);
						} else {
							if (arr[i].charAt(node) != 'T' && arr[j].charAt(node) != 'T') {
								cur[node] = 'T';
							} else if (arr[i].charAt(node) != 'E' && arr[j].charAt(node) != 'E') {
								cur[node] = 'E';
							} else {
								cur[node] = 'S';
							}
						}

					}
					String sr_cur = String.valueOf(cur);
					// out.println(sr_cur);
					if (map.containsKey(sr_cur)) {
						ans += map.get(sr_cur);
					}
				}
			}
			ans /= 3;
			out.println(ans);
		}
		out.close();
	}

	// constants
	static final int IBIG = 1000000007;
	static final int IMAX = 2147483647;
	static final long LMAX = 9223372036854775807L;
	static Random __r = new Random();

	// math util
	static int minof(int a, int b, int c) {
		return min(a, min(b, c));
	}

	static int minof(int... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return min(x[0], x[1]);
		if (x.length == 3)
			return min(x[0], min(x[1], x[2]));
		int min = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] < min)
				min = x[i];
		return min;
	}

	static long minof(long a, long b, long c) {
		return min(a, min(b, c));
	}

	static long minof(long... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return min(x[0], x[1]);
		if (x.length == 3)
			return min(x[0], min(x[1], x[2]));
		long min = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] < min)
				min = x[i];
		return min;
	}

	static int maxof(int a, int b, int c) {
		return max(a, max(b, c));
	}

	static int maxof(int... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return max(x[0], x[1]);
		if (x.length == 3)
			return max(x[0], max(x[1], x[2]));
		int max = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] > max)
				max = x[i];
		return max;
	}

	static long maxof(long a, long b, long c) {
		return max(a, max(b, c));
	}

	static long maxof(long... x) {
		if (x.length == 1)
			return x[0];
		if (x.length == 2)
			return max(x[0], x[1]);
		if (x.length == 3)
			return max(x[0], max(x[1], x[2]));
		long max = x[0];
		for (int i = 1; i < x.length; ++i)
			if (x[i] > max)
				max = x[i];
		return max;
	}

	static int powi(int a, int b) {
		if (a == 0)
			return 0;
		int ans = 1;
		while (b > 0) {
			if ((b & 1) > 0)
				ans *= a;
			a *= a;
			b >>= 1;
		}
		return ans;
	}

	static long powl(long a, int b) {
		if (a == 0)
			return 0;
		long ans = 1;
		while (b > 0) {
			if ((b & 1) > 0)
				ans *= a;
			a *= a;
			b >>= 1;
		}
		return ans;
	}

	static int fli(double d) {
		return (int) d;
	}

	static int cei(double d) {
		return (int) ceil(d);
	}

	static long fll(double d) {
		return (long) d;
	}

	static long cel(double d) {
		return (long) ceil(d);
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	static int lcm(int a, int b) {
		return (a / gcd(a, b)) * b;
	}

	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	static long lcm(long a, long b) {
		return (a / gcd(a, b)) * b;
	}

	static int[] exgcd(int a, int b) {
		if (b == 0)
			return new int[] { 1, 0 };
		int[] y = exgcd(b, a % b);
		return new int[] { y[1], y[0] - y[1] * (a / b) };
	}

	static long[] exgcd(long a, long b) {
		if (b == 0)
			return new long[] { 1, 0 };
		long[] y = exgcd(b, a % b);
		return new long[] { y[1], y[0] - y[1] * (a / b) };
	}

	static int randInt(int min, int max) {
		return __r.nextInt(max - min + 1) + min;
	}

	static long mix(long x) {
		x += 0x9e3779b97f4a7c15L;
		x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
		x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
		return x ^ (x >> 31);
	}

	public static boolean[] findPrimes(int limit) {
		assert limit >= 2;

		final boolean[] nonPrimes = new boolean[limit];
		nonPrimes[0] = true;
		nonPrimes[1] = true;

		int sqrt = (int) Math.sqrt(limit);
		for (int i = 2; i <= sqrt; i++) {
			if (nonPrimes[i])
				continue;
			for (int j = i; j < limit; j += i) {
				if (!nonPrimes[j] && i != j)
					nonPrimes[j] = true;
			}
		}

		return nonPrimes;
	}

	// array util
	static void reverse(int[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			int swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void reverse(long[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			long swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void reverse(double[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			double swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void reverse(char[] a) {
		for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
			char swap = a[i];
			a[i] = a[n - i - 1];
			a[n - i - 1] = swap;
		}
	}

	static void shuffle(int[] a) {
		int n = a.length - 1;
		for (int i = 0; i < n; ++i) {
			int ind = randInt(i, n);
			int swap = a[i];
			a[i] = a[ind];
			a[ind] = swap;
		}
	}

	static void shuffle(long[] a) {
		int n = a.length - 1;
		for (int i = 0; i < n; ++i) {
			int ind = randInt(i, n);
			long swap = a[i];
			a[i] = a[ind];
			a[ind] = swap;
		}
	}

	static void shuffle(double[] a) {
		int n = a.length - 1;
		for (int i = 0; i < n; ++i) {
			int ind = randInt(i, n);
			double swap = a[i];
			a[i] = a[ind];
			a[ind] = swap;
		}
	}

	static void rsort(int[] a) {
		shuffle(a);
		sort(a);
	}

	static void rsort(long[] a) {
		shuffle(a);
		sort(a);
	}

	static void rsort(double[] a) {
		shuffle(a);
		sort(a);
	}

	static int[] copy(int[] a) {
		int[] ans = new int[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static long[] copy(long[] a) {
		long[] ans = new long[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static double[] copy(double[] a) {
		double[] ans = new double[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static char[] copy(char[] a) {
		char[] ans = new char[a.length];
		for (int i = 0; i < a.length; ++i)
			ans[i] = a[i];
		return ans;
	}

	static class FastReader {

		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(
					new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] ria(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = Integer.parseInt(next());
			return a;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] rla(int n) {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = Long.parseLong(next());
			return a;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str;
		}
	}
}


E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.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 only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3
5 7
10 19
10 18
OutputCopyYES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
NotePictures corresponding to the first and the second test cases of the example:

import java.util.*;

import java.io.*;

import static java.lang.Math.*;

public class Main implements Runnable

{

    boolean multiple = true;

    long MOD;

    @SuppressWarnings("Duplicates")

    void solve() throws Exception

    {

        int n = sc.nextInt();

        int d = sc.nextInt();

        int N = n;

        int min = 0;

        for (int layer = 0; N > 0; layer++)

        {

            min += layer * min(N, 1 << layer);

            N -= 1 << layer;

        }

        if (min <= d && d <= (n * (n - 1)) / 2)

        {

            System.out.println("YES");

            PriorityQueue<Node>[] layer = new PriorityQueue[n + 1];

            layer[0] = new PriorityQueue<>();

            layer[1] = new PriorityQueue<>();

            layer[1].add(new Node(null, 1));

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

            {

                layer[i] = new PriorityQueue<>();

                layer[i].add(new Node(layer[i - 1].peek(), i));

            }

            int current = n;

            int lowest = n;

            for (int sum = (n * (n - 1)) / 2; sum > d; sum--)

            {

//                System.out.println(current);

                Node next = layer[current].poll();

                Node newParent = layer[current - 2].poll();

                next.parent.children--;

//                System.out.println(newParent.children);

                newParent.children++;

                next.parent = newParent;

                layer[current - 2].add(newParent);

                layer[current - 1].add(next);

                if (layer[lowest].isEmpty()) lowest--;

                current--;

                if (current == 2 || layer[current - 2].peek().children == 2) current = lowest;

            }

            int[] ans = new int[n + 1];

            for (PriorityQueue<Node> pq : layer)

                while (!pq.isEmpty())

                {

                    Node next = pq.poll();

                    if (next.idx == 1) continue;

                    ans[next.idx] = next.parent.idx;

                }

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

                System.out.print(ans[i] + " ");

            System.out.println();

        }

        else

            System.out.println("NO");

    }

    class Node implements Comparable<Node>

    {

        Node parent;

        int idx;

        int children = 1;

        Node(Node p, int i)

        {

            parent = p;

            idx = i;

        }

        @Override

        public int compareTo(Node o)

        {

            return children - o.children;

        }

    }

    long inv(long a, long b)

    {

        return 1 < a ? b - inv(b % a, a) * b / a : 1;

    }

    long gcd(long a, long b)

    {

        return a == 0 ? b : gcd(b % a, a);

    }

    long lcm(long a, long b) { return (a * b) / gcd(a , b); }

    class SegNode

    {

        int max;

        int L, R;

        SegNode left = null, right = null;

        int query(int queryL, int queryR)

        {

            if (queryL == L && queryR == R)

                return max;

            int leftAns = Integer.MIN_VALUE, rightAns = Integer.MIN_VALUE;

            if (left != null && queryL <= left.R)

                leftAns = left.query(queryL, min(queryR, left.R));

            if (right != null && queryR >= right.L)

                rightAns = right.query(max(queryL, right.L), queryR);

            return max(leftAns, rightAns);

        }

        SegNode(int[] arr, int l, int r)

        {

            L = l;

            R = r;

            max = arr[l];

            if (l == r) return;

            int mid = (l + r) / 2;

            left = new SegNode(arr, l, mid);

            right = new SegNode(arr, mid + 1, r);

            max = max(left.max, right.max);

        }

    }

    void print(long[] arr)

    {

        for (int i = 0; i < arr.length; i++)

            System.out.print(arr[i] + " ");

        System.out.println();

    }

    @Override

    public void run()

    {

        try

        {

            in = new BufferedReader(new InputStreamReader(System.in));

            out = new PrintWriter(System.out);

            sc = new FastScanner(in);

            if (multiple)

            {

                int q = sc.nextInt();

                for (int i = 0; i < q; i++)

                    solve();

            }

            else

                solve();

        }

        catch (Throwable uncaught)

        {

            Main.uncaught = uncaught;

        }

        finally

        {

            out.close();

        }

    }

    public static void main(String[] args) throws Throwable

    {

        Thread thread = new Thread(null, new Main(), "", (1 << 26));

        thread.start();

        thread.join();

        if (Main.uncaught != null) {

            throw Main.uncaught;

        }

    }

    static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out;

}

class FastScanner

{

    BufferedReader in;

    StringTokenizer st;

    public FastScanner(BufferedReader in)

    {

        this.in = in;

    }

    public String nextToken() throws Exception {

        while (st == null || !st.hasMoreTokens()) {

            st = new StringTokenizer(in.readLine());

        }

        return st.nextToken();

    }

    public int nextInt() throws Exception {

        return Integer.parseInt(nextToken());

    }

    public long nextLong() throws Exception {

        return Long.parseLong(nextToken());

    }

    public double nextDouble() throws Exception {

        return Double.parseDouble(nextToken());

    }

}


A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  0≤ai≤m0≤ai≤m  The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2
4 10
1 2 3 4
4 5
1 2 3 4
OutputCopy10
5
NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        in = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        try {
            int t = in.nextInt(); while(t-- > 0) { solve(); out.println();}
//            solve();
        } finally {
            out.close();
        }
        return;
    }

    public static void solve() {
        int n = in.nextInt();
        int m = in.nextInt();
        int[] a = fillArray(n);
        int sum = Arrays.stream(a).sum();

        out.print(Math.min(m, sum));
    }

    //-------------- Helper methods-------------------
    public static int[] fillArray(int n) {
        int[] array = new int[n];
        for(int i = 0; i < n; i++) {
            array[i] = in.nextInt();
        }
        return array;
    }

    public static char[] fillArray() {
        char[] array = in.next().toCharArray();
        return array;
    }

    //-----------PrintWriter for faster output---------------------------------

    public static PrintWriter out;
    public static MyScanner in;

    //-----------MyScanner class for faster input----------x§x
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    }

    static void shuffleArray(int[] arr){
        int n = arr.length;
        Random rnd = new Random();
        for(int i=0; i<n; ++i){
            int tmp = arr[i];
            int randomPos = i + rnd.nextInt(n-i);
            arr[i] = arr[randomPos];
            arr[randomPos] = tmp;
        }
    }
    //--------------------------------------------------------
}


F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

import java.util.*;

import java.io.*;

public class A {

    void solve() {

        int n = in.nextInt();

        int[] arr = new int[n + 1];

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

            arr[i] = in.nextInt();

        }

        HashMap<Long, List<int[]>> map = new HashMap<>();

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

            long sum = 0l;

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

                sum += arr[j];

                map.computeIfAbsent(sum, k -> new ArrayList<>()).add(new int[] {i, j});

            }

        }

//        List<int[]> ans = new ArrayList<>();

        ArrayList<List<int[]>> ans = new ArrayList<>();

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

            ans.add(new ArrayList<>());

        }

        for (List<int[]> cur : map.values()) {

//            List<int[]> cur = x;

//            cur.sort((a, b) -> a[1] - b[1]);

            cur.sort(Comparator.comparingInt(a -> a[1]));

//            List<int[]> temp = new ArrayList<>();

            int prev = 0;

            for (int[] y : cur) {

                if (y[0] > prev) {

//                    temp.add(y);

                    ans.get(1).add(y);

                    prev = y[1];

                }

            }

//            if (temp.size() > ans.size()) {

//                ans = temp;

//            }

            if (ans.get(1).size() > ans.get(0).size()) {

                Collections.swap(ans, 0, 1);

            }

            ans.get(1).clear();

        }

        out.println(ans.get(0).size());

        for (int[] x : ans.get(0)) {

            out.println(x[0] + " " + x[1]);

        }

    }

    FastScanner in;

    PrintWriter out;

    void run() {

        in = new FastScanner();

        out = new PrintWriter(System.out);

        solve();

        out.close();

    }

    class FastScanner {

        BufferedReader br;

        StringTokenizer st;

        public FastScanner() {

            br = new BufferedReader(new InputStreamReader(System.in));

        }

        public FastScanner(String s) {

            try {

                br = new BufferedReader(new FileReader(s));

            } catch (FileNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

        public String nextToken() {

            while (st == null || !st.hasMoreTokens()) {

                try {

                    st = new StringTokenizer(br.readLine());

                } catch (IOException e) {

                }

            }

            return st.nextToken();

        }

        public int nextInt() {

            return Integer.parseInt(nextToken());

        }

        public long nextLong() {

            return Long.parseLong(nextToken());

        }

        public double nextDouble() {

            return Double.parseDouble(nextToken());

        }

    }

    public static void main(String[] args) {

        new A().run();

    }

}


D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2
1 2 3 6
3 4 7 8
OutputCopyYES
InputCopy3
1 3 2 4
4 5 6 7
3 4 5 5
OutputCopyNO
InputCopy6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
OutputCopyYES
NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.

import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.lang.System.nanoTime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Random;
import java.util.StringTokenizer;

public class D {

	static void sortBy(int a[], int n, int v[]) {
		if (n == 0) {
			return;
		}
		for (int i = 1; i < n; i++) {
			int j = i;
			int ca = a[i];
			int cv = v[ca];
			do {
				int nj = (j - 1) >> 1;
				int na = a[nj];
				if (cv <= v[na]) {
					break;
				}
				a[j] = na;
				j = nj;
			} while (j != 0);
			a[j] = ca;
		}
		int ca = a[0];
		for (int i = n - 1; i > 0; i--) {
			int j = 0;
			while ((j << 1) + 2 + Integer.MIN_VALUE < i + Integer.MIN_VALUE) {
				j <<= 1;
				j += (v[a[j + 2]] > v[a[j + 1]]) ? 2 : 1;
			}
			if ((j << 1) + 2 == i) {
				j = (j << 1) + 1;
			}
			int na = a[i];
			a[i] = ca;
			ca = na;
			int cv = v[ca];
			while (j != 0 && v[a[j]] < cv) {
				j = (j - 1) >> 1;
			}
			while (j != 0) {
				na = a[j];
				a[j] = ca;
				ca = na;
				j = (j - 1) >> 1;
			}
		}
		a[0] = ca;
	}

	static void solve() throws Exception {
		int n = scanInt();
		int pa[] = new int[2 * n], pb[] = new int[2 * n], idxa[] = new int[2 * n], idxb[] = new int[2 * n];
		for (int i = 0; i < n; i++) {
			pa[2 * i] = 2 * scanInt();
			pa[2 * i + 1] = 2 * scanInt() + 1;
			pb[2 * i] = 2 * scanInt();
			pb[2 * i + 1] = 2 * scanInt() + 1;
			idxa[2 * i] = idxb[2 * i] = 2 * i;
			idxa[2 * i + 1] = idxb[2 * i + 1] = 2 * i + 1;
		}
		sortBy(idxa, 2 * n, pa);
		sortBy(idxb, 2 * n, pb);
		Random rng = new Random(nanoTime());
		long v[] = new long[n];
		for (int i = 0; i < n; i++) {
			v[i] = rng.nextLong() | 1;
		}
		long ans = 0, cur = 0;
		for (int i: idxa) {
			if ((i & 1) == 0) {
				ans += v[i >> 1] * cur;
				cur += v[i >> 1];
			} else {
				cur -= v[i >> 1];
			}
		}
		for (int i: idxb) {
			if ((i & 1) == 0) {
				ans -= v[i >> 1] * cur;
				cur += v[i >> 1];
			} else {
				cur -= v[i >> 1];
			}
		}
		out.print(ans == 0 ? "YES" : "NO");
	}

	static int scanInt() throws IOException {
		return parseInt(scanString());
	}

	static long scanLong() throws IOException {
		return parseLong(scanString());
	}

	static String scanString() throws IOException {
		while (tok == null || !tok.hasMoreTokens()) {
			tok = new StringTokenizer(in.readLine());
		}
		return tok.nextToken();
	}

	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

	public static void main(String[] args) {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			solve();
			in.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			exit(1);
		}
	}
}