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);
		}
	}
}


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

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();
        char[] s = fillArray();
        int max = 0;
        int lastAngry = -1;
        for(int i = 0; i < n; i++) {
            if(s[i] == 'A') {
                lastAngry = i;
                continue;
            }

            if(lastAngry == -1) {
                continue;
            }

            max = Math.max(max, i - lastAngry);
        }

        out.print(max);
    }

    //-------------- 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;
        }
    }
    //--------------------------------------------------------
}


C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.

import java.util.*;

import java.awt.PrintGraphics;

import java.io.*;

import java.math.*;

import java.sql.Array;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.SQLIntegrityConstraintViolationException;

public class Main {

	 private static class MyScanner {

	        private static final int BUF_SIZE = 2048;

	        BufferedReader br;

	        private MyScanner() {

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

	        }

	        private boolean isSpace(char c) {

	            return c == '\n' || c == '\r' || c == ' ';

	        }

	        String next() {

	            try {

	                StringBuilder sb = new StringBuilder();

	                int r;

	                while ((r = br.read()) != -1 && isSpace((char)r));

	                if (r == -1) {

	                    return null;

	                }

	                sb.append((char) r);

	                while ((r = br.read()) != -1 && !isSpace((char)r)) {

	                    sb.append((char)r);

	                }

	                return sb.toString();

	            } catch (IOException e) {

	                e.printStackTrace();

	            }

	            return null;

	        }

	        int nextInt() {

	            return Integer.parseInt(next());

	        }

	        long nextLong() {

	            return Long.parseLong(next());

	        }

	        double nextDouble() {

	            return Double.parseDouble(next());

	        }

	    }

	  static class Reader{

			BufferedReader br;

			StringTokenizer st;

			public Reader() {

				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 long mod = (long)(1e9 + 7);

	static void sort(long[] arr ) {

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

		 for(long e:arr) al.add(e);

		 Collections.sort(al);

		 for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);

	 }

	static void sort(int[] arr ) {

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

		 for(int e:arr) al.add(e);

		 Collections.sort(al);

		 for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);

	 }

	static void sort(char[] arr) {

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

		for(char cc:arr) al.add(cc);

		Collections.sort(al);

		for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);

	}

	static long mod_mul(  long... a) {

		long ans = a[0]%mod;

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

			ans = (ans * (a[i]%mod))%mod;

		}

		return ans;

	}

	static long mod_sum( long... a) {

		long ans = 0;

		for(long e:a) {

			ans = (ans + e)%mod;

		}

		return ans;

	}

	 static long gcd(long a, long b)

	  {

	     if (b == 0)

	        return a;

	     return gcd(b, a % b);

	  }

	 static void print(long[] arr) {

		 System.out.println("---print---");

		 for(long e:arr) System.out.print(e+" ");

		 System.out.println("-----------");

	 }

	 static void print(int[] arr) {

		 System.out.println("---print---");

		 for(long e:arr) System.out.print(e+" ");

		 System.out.println("-----------");

	 }

	 static boolean[] prime(int num) {

			boolean[] bool = new boolean[num];

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

		         bool[i] = true;

		      }

		      for (int i = 2; i< Math.sqrt(num); i++) {

		         if(bool[i] == true) {

		            for(int j = (i*i); j<num; j = j+i) {

		               bool[j] = false;

		            }

		         }

		      }

		      if(num >= 0) {

		    	  bool[0] = false;

		    	  bool[1] = false;

		      }

		      return bool;

		}

	 static long modInverse(long a, long m)

	    {

	        long g = gcd(a, m);

	          return   power(a, m - 2);

	    }

	   static long lcm(long a , long b) {

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

	   }

	   static int lcm(int a , int b) {

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

	   }

	 static long power(long x, long y){

		 if(y<0) return 0;

		 long m = mod;

	        if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);

	        if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }

     static class Combinations{

	    	 private long[] z;  // factorial

	    	 private long[] z1; // inverse factorial

	    	 private long[] z2; // incerse number

	    	 private long mod;

	    	  public Combinations(long N , long mod) {

	    		  this.mod = mod;

				z = new long[(int)N+1];

				z1 = new long[(int)N+1];

				z[0] = 1;

				for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;

			     z2 = new long[(int)N+1];

				z2[0] = z2[1] = 1;

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

			        z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;

			    z1[0] = z1[1] = 1;

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

			        z1[i] = (z2[i] * z1[i - 1]) % mod;

			}

	    	  long fac(long n) {

	    		  return z[(int)n];

	    	  }

	    	  long invrsNum(long n) {

	    		  return z2[(int)n];

	    	  }

	    	  long invrsFac(long n) {

	    		  return z1[(int)n];

	    	  }

	    	  long ncr(long N, long R)

	    	  {		if(R<0 || R>N ) return 0;

	    		    long ans = ((z[(int)N] * z1[(int)R])

	    		              % mod * z1[(int)(N - R)])

	    		             % mod;

	    		    return ans;

	    		}

	      }

	      static class DisjointUnionSets {

			    int[] rank, parent;

			    int n;

			    public DisjointUnionSets(int n)

			    {

			        rank = new int[n];

			        parent = new int[n];

			        this.n = n;

			        makeSet();

			    }

			    void makeSet()

			    {

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

			            parent[i] = i;

			        }

			    }

			    int find(int x)

			    {

			        if (parent[x] != x) {

			            parent[x] = find(parent[x]);

			        }

			        return parent[x];

			    }

			    void union(int x, int y)

			    {

			        int xRoot = find(x), yRoot = find(y);

			        if (xRoot == yRoot)

			            return;

			        if (rank[xRoot] < rank[yRoot])

			            parent[xRoot] = yRoot;

			        else if (rank[yRoot] < rank[xRoot])

			            parent[yRoot] = xRoot;

			        else

			        {

			            parent[yRoot] = xRoot;

			            rank[xRoot] = rank[xRoot] + 1;

			        }

			    }

			}

	      static int max(int... a ) {

	    	  int max = a[0];

	    	  for(int e:a) max = Math.max(max, e);

	    	  return max;

	      }

	      static long max(long... a ) {

	    	  long max = a[0];

	    	  for(long e:a) max = Math.max(max, e);

	    	  return max;

	      }

	      static int min(int... a ) {

	    	  int min = a[0];

	    	  for(int e:a) min = Math.min(e, min);

	    	  return min;

	      }

	      static long min(long... a ) {

	    	  long min = a[0];

	    	  for(long e:a) min = Math.min(e, min);

	    	  return min;

	      }

	      static int[] KMP(String str) {

	    	  int n = str.length();

	    	  int[] kmp = new int[n];

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

	    		  int j = kmp[i-1];

	    		  while(j>0 && str.charAt(i) != str.charAt(j)) {

	    			  j = kmp[j-1];

	    		  }

	    		  if(str.charAt(i) == str.charAt(j)) j++;

	    		  kmp[i] = j;

	    	  }

	    	  return kmp;

	      }

/************************************************ Query **************************************************************************************/

/***************************************** 		Sparse Table	********************************************************/

	      static class SparseTable{

	    		private long[][] st;

	    		SparseTable(long[] arr){

	    			int n = arr.length;

	    			st = new long[n][25];

	    			log = new int[n+2];

	    			build_log(n+1);

	    			build(arr);

	    		}

	    		private void build(long[] arr) {

	    			int n = arr.length;

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

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

	    					int r = i + (1<<j)-1;

	    					if(r>=n) break;

	    					if(j == 0 ) st[i][j] = arr[i];

	    					else st[i][j] = gcd(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );

	    				}

	    			}

	    		}

	    		public long gcd(long a  ,long b) {

	    			if(a == 0) return b;

	    			return gcd(b%a , a);

	    		}

	    		public long query(int l ,int r) {

	    			int w = r-l+1;

	    			int power = log[w];

	    			return gcd(st[l][power],st[r - (1<<power) + 1][power]);

	    		}

	    		private int[] log;

	    		void build_log(int n) {

	    			log[1] = 0;

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

	    				log[i] = 1 + log[i/2];

	    			}

	    		}

	    	}

/********************************************************	Segement Tree	*****************************************************/

	 	 static class SegmentTree{

			 long[] tree;

			 long[] arr;

			 int n;

			 SegmentTree(long[] arr){

				 this.n = arr.length;

				 tree = new long[4*n+1];

				 this.arr = arr;

				 buildTree(0, n-1, 1);

			 }

			  void buildTree(int s ,int e  ,int index ) {

					if(s == e) {

						tree[index] = arr[s];

						return;

					}

					int mid = (s+e)/2;

					buildTree( s,  mid, 2*index);

					buildTree( mid+1, e, 2*index+1);

					tree[index] = gcd(tree[2*index] , tree[2*index+1]);

				}

			 long query(int si ,int ei) {

				 return query(0 ,n-1 , si ,ei , 1   );

			 }

			 private long query( int ss ,int se ,int qs , int qe,int index) {

					if(ss>=qs && se<=qe) return tree[index];

					if(qe<ss || se<qs) return (long)(0);

					int mid = (ss + se)/2;

					long left = query( ss , mid , qs ,qe , 2*index);

					long right= query(mid + 1 , se , qs ,qe , 2*index+1);

					return gcd(left, right);

				}

			 public void update(int index , int val) {

				 arr[index] = val;

//				 for(long e:arr) System.out.print(e+" ");

				 update(index , 0 , n-1 , 1);

			 }

			 private void update(int id ,int si , int ei , int index) {

				 if(id < si || id>ei) return;

				 if(si == ei ) {

					 tree[index] = arr[id];

					 return;

				 }

				 if(si > ei) return;

				 int mid = (ei + si)/2;

					update( id,  si, mid , 2*index);

					update( id , mid+1, ei , 2*index+1);

					tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);

			 }

		 }

/* ***************************************************************************************************************************************************/

//	      static MyScanner sc = new MyScanner(); // only in case of less memory

	      static Reader sc = new Reader();

	      static int TC;

	 static StringBuilder sb = new StringBuilder();

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

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

		 int tc = 1;

		 tc = sc.nextInt();

		 TC = 0;

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

			 TC++;

//			 sb.append("Case #" + i + ": "  );	// During KickStart && HackerCup

			 TEST_CASE();

		 }

		 System.out.print(sb);

	 }

	 static void TEST_CASE() throws IOException {

		long n = sc.nextLong() , m = sc.nextLong();

		long tot = sum(n);

		long min = min(n , m);

		long z = (n-m);

		if(z<=m+1) {

			tot -= z;

			sb.append(tot+"\n");

			return;

		}else {

			long gaps = m+1;

			long ele = z/(m+1);

			long ext = z%(m+1);

			long g1 = m+1-ext;

			long eleOfGap1 = ele;

			long g2 = ext;

			long eleOfGap2 = ele+1;

			long sub1 = sum(eleOfGap1) * g1;

			long sub2 = sum(eleOfGap2) * g2;

			tot -= sub1;

			tot -= sub2;

			sb.append(tot+"\n");

		}

	 }

	 static long sum(long n) {

		 long sum = 0 ;

		 sum += n*(n+1);

		 return sum/2;

	 }

	}

/*******************************************************************************************************************************************************/

/**

  R -> 1

  B -> 1

  k -> 2

 */


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

import java.util.Arrays;

import java.util.Scanner;

public class sol {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while (t-- > 0) {

			int n = sc.nextInt();

			int[][] arr = new int[n][2];

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

				arr[i][0] = sc.nextInt();

				arr[i][1] = sc.nextInt();

			}

			Arrays.sort(arr, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));

			StringBuilder sb = new StringBuilder();

			boolean ok = true;

			int x = 0, y = 0;

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

				if (arr[i][1] < y) {

					ok = false;

					break;

				}

				while (x < arr[i][0]) {

					sb.append("R");

					x++;

				}

				while (y < arr[i][1]) {

					sb.append("U");

					y++;

				}

			}

			if (ok) {

				System.out.println("YES");

				System.out.println(sb);

			} else {

				System.out.println("NO");

			}

		}

	}

}


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

//package com.company;//Read minute details if coming wrong for no idea questions

import com.sun.source.tree.ArrayAccessTree;

import javax.swing.*;

import java.beans.IntrospectionException;

import java.math.BigInteger;

import java.util.*;

import java.io.*;

public class Main {

    static class pair implements Comparable<pair> {

        long a = 0;

        long b = 0;

        // int cnt;

        pair(long b, long a) {

            this.a = b;

            this.b = a;

            // cnt = x;

        }

        @Override

        public int compareTo(pair o) {

            if(this.a != o.a)

                return (int) (this.a - o.a);

            else

                return (int) (this.b - o.b);

        }

        public boolean equals(Object o) {

            if (o instanceof pair) {

                pair p = (pair) o;

                return p.a == a && p.b == b;

            }

            return false;

        }

        public int hashCode() {

            return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode());

        }

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

                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().trim();

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

            this.bw = new BufferedWriter(new OutputStreamWriter(System.out));

        }

        public void prlong(Object object) throws IOException {

            bw.append("" + object);

        }

        public void prlongln(Object object) throws IOException {

            prlong(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

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

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    //HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS

//    HashSet<Long> set = new HashSet<>();

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

//        int b = 0;

//        long h = 1;

//        for(int j=i; j<s.length(); j++){

//            h = 131*h + (int)s.charAt(j);

//            b += bad[(int)(s.charAt(j)-'a')];

//            if(b<=k){

//                set.add(h);

//            }

//        }

//    }

//                System.out.println(set.size());

    //dsu

    static int[] par, rank;

    public static void dsu(int n) {

        par = new int[n];

        rank = new int[n];

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

            par[i] = i;

            rank[i] = 1;

        }

    }

    static int find(int u) {

        return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u]));

    }

    static void union(int u, int v) {

        int a = find(u), b = find(v);

        if (a != b && a != -1 && b != -1) {

            par[b] = a;

            rank[a] += rank[b];

        }

    }

    static void disunion(int u, int v) {

        int a = find(u), b = find(v);

        if (a != -1 && a == b) {

            par[a] = -1;

        }

    }

    static class Calc_nCr {

        private final long[] fact;

        private final long[] invfact;

        private final int p;

        Calc_nCr(int n, int prime) {

            fact = new long[n + 5];

            invfact = new long[n + 5];

            p = prime;

            fact[0] = 1;

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

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

            }

            invfact[n] = pow(fact[n], p - 2, p);

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

                invfact[i] = (invfact[i + 1] * (i + 1)) % p;

            }

        }

        private long nCr(int n, int r) {

            if (r > n || n < 0 || r < 0) return 0;

            return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p;

        }

        private static long pow(long a, long b, int mod) {

            long result = 1;

            while (b > 0) {

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

                    result = (result * a) % mod;

                }

                a = (a * a) % mod;

                b >>= 1;

            }

            return result;

        }

    }

    static void sort(long[] a ) {

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

        for(long i: a) {

            l.add(i);

        }

        Collections.sort(l);

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

            a[i] = l.get(i);

        }

    }

    public static void main(String[] args) {

        try {

            FastReader in = new FastReader();

            FastWriter out = new FastWriter();

//            int mx=10000000;

//            boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5];

//            for (int i = 0; i <= mx; i++) {

//                isPrime[i] = true;

//            }

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

//                primeDiv[i]=i;

//            isPrime[0] = isPrime[1] = false;

//            for (long i = 2; i <= mx; i++) {

//                if (isPrime[(int)i]) {

//                    for (long j = i*i; j <= mx; j += i) {

//                        if (primeDiv[(int)j] == j) {

//                            primeDiv[(int)j] = (int)i;

//                        }

//                        isPrime[(int)j] = false;

//                    }

//                }

//            }

//            System.out.println(

//                    String.format("%.12f", x));

            int testCases=in.nextInt();

//            int n =in.nextInt();

//            long  arr[]=new long[n];

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

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

//

//

//            }       ans.add(in.nextLong());

//            Collections.sort(ans);

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

//                arr[i]=ans.get(i);

            int mod =1000000007;

            fl:

            while (testCases-- > 0) {

                int n =in.nextInt();

                String s =in.next();

                HashMap<pair,Integer>map=new HashMap<>();

                int min =100000000;

                int a=-1;

                int b =-1;

                int x =0;

                int y =0;

map.put(new pair(0,0),-1);

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

                {

                    if(s.charAt(i)=='U')

                        y++;

                    if(s.charAt(i)=='D')

                        y--;

                    if(s.charAt(i)=='L')

                        x--;

                    if(s.charAt(i)=='R')

                        x++;

                    pair p =new pair(x,y);

                  //  System.out.println(x+" "+y+" "+i);

                    if(map.containsKey(p))

                    {   //System.out.println(x+" boom "+y+" "+i);

                        int len =i-map.get(p);

                        if(len<min)

                        {

                            min=len;

                            a=map.get(p)+1;

                            b=i;

                        }

                    }

                    map.put(p,i);

                }

if(a==-1||b==-1)

{

    System.out.println(-1);

    continue fl;

}

                System.out.println((a+1)+" "+(b+1));

            }

            out.close();

        } catch (Exception e) {

            return;

        }

    }

    public static double dfs(ArrayList<ArrayList<Integer>>adj, int curr, int par) {

        double len = 0;

        for(int child: adj.get(curr)) {

            if(child == par)

                continue;

            len += dfs(adj, child, curr)+1;

        }

        //System.out.println(curr+" "+len);

        if(len == 0) // leaf node

            return 0;

        if(par == -1) // root node

            return len/adj.get(curr).size();

        return len/(adj.get(curr).size()-1);

    }

    static long comb(int r, int n)

    {

        long result;

        result = factorial(n)/(factorial(r)*factorial(n-r));

        return result;

    }

    static long factorial(int n) {

        int c;

        long result = 1;

        for (c = 1; c <= n; c++)

            result = result*c;

        return result;

    }

    static void  LongestPalindromicPrefix(String str,int lps[]){

//        String temp = str + '/';

//        str = reverse(str);

//        temp += str;

        String temp =str;

        int n = temp.length();

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

        {

            int len = lps[i - 1];

            while (len > 0 && temp.charAt(len) !=

                    temp.charAt(i))

            {

                len = lps[len - 1];

            }

            if (temp.charAt(i) == temp.charAt(len))

            {

                len++;

            }

            lps[i] = len;

        }

//        return temp.substring(0, lps[n - 1]);

    }

    static String reverse(String input)

    {

        char[] a = input.toCharArray();

        int l, r = a.length - 1;

        for(l = 0; l < r; l++, r--)

        {

            char temp = a[l];

            a[l] = a[r];

            a[r] = temp;

        }

        return String.valueOf(a);

    }

}

/*

 *

 *　　┏┓　　　┏┓+ +

 *　┏┛┻━━━┛┻┓ + +

 *　┃　　　　　　　┃

 *　┃　　　━　　　┃ ++ + + +

 *   ████━████+

 *  ◥██◤　◥██◤ +

 *　┃　　　┻　　　┃

 *　┃　　　　　　　┃ + +

 *　┗━┓　　　┏━┛

 *　　　┃　　┃      JACKS PET FROM ANOTHER WORLD

 *　　　┃　　┃

 *　　　┃　 　 ┗━━━┓

 *　　　┃ 　　　　　　 ┣┓-------

 *　　  ┃ 　　　　　 　┏┛-------

 *　    ┗┓┓┏━┳┓┏┛ + + + +

 *　　　　┃┫┫　┃┫┫

 *　　　　┗┻┛　┗┻┛+ + + +

 */

//RULES

//TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array

//Always use stringbuilder of out.println for strinof out.println for string or high level output

// IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN

//Read minute details if coming wrong for no idea questions