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

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

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

    static final FastReader sc = new FastReader();

    public static boolean sorted(int a[])

    {

        int n=a.length,i;

        int b[]=new int[n];

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

        b[i]=a[i];

        Arrays.sort(b);

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

        {

            if(a[i]!=b[i])

            return false;

        }

        return true;

    }

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

	{

	   int tes=sc.nextInt();

	   label:while(tes-->0)

	   {

	       int n=sc.nextInt();

	       int s=sc.nextInt();

	       int k=sc.nextInt();

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

	       int i;

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

	       arr.add(sc.nextInt());

	       if(!arr.contains(s))

	       {

	           System.out.println(0);

	           continue;

	       }

	       for(i=1;i<=k;i++)

	       {

	           if(s+i<=n && !arr.contains(s+i))

	           {

	               System.out.println(i);

	               continue label;

	           }

	           if(s-i>=1 && !arr.contains(s-i))

	           {

	               System.out.println(i);

	               continue label;

	           }

	       }

	   }

	}

	public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)

    {

        if (high >= low) {

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

            if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)

                return mid;

            else if (x > arr.get(mid))

                return first(arr, (mid + 1), high, x, n);

            else

                return first(arr, low, (mid - 1), x, n);

        }

        return -1;

    }

	public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)

    {

        if (high >= low) {

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

            if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)

                return mid;

            else if (x < arr.get(mid))

                return last(arr, low, (mid - 1), x, n);

            else

                return last(arr, (mid + 1), high, x, n);

        }

        return -1;

    }

	public static int lis(int[] arr) {

	int n = arr.length;

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

	al.add(arr[0]);

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

		int x = al.get(al.size()-1);

		if(arr[i]>=x) {

			al.add(arr[i]);

		}else {

			int v = upper_bound(al, 0, al.size(), arr[i]);

			al.set(v, arr[i]);

		}

	}

	return al.size();

}

	public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

        if (ar.get((int)mid) <k)

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

        if (ar.get(mid) <=k)

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

static boolean isPrime(long N)

    {

        if (N<=1)  return false;

        if (N<=3)  return true;

        if (N%2 == 0 || N%3 == 0) return false;

        for (int i=5; i*i<=N; i=i+6)

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

                return false;

        return true;

    }

    static int countBits(long a)

    {

        return (int)(Math.log(a)/Math.log(2)+1);

    }

    static long fact(long N)

    {

        long mod=1000000007;

        long n=2;

        if(N<=1)return 1;

        else

        {

            for(int i=3; i<=N; i++)n=(n*i)%mod;

        }

        return n;

    }

    private static boolean isInteger(String s) {

        try {

            Integer.parseInt(s);

        } catch (NumberFormatException e) {

            return false;

        } catch (NullPointerException e) {

            return false;

        }

        return true;

    }

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

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

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

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

    }

    private static boolean isPalindrome(String str) {

        int i = 0, j = str.length() - 1;

        while (i < j)

            if (str.charAt(i++) != str.charAt(j--))

                return false;

        return true;

    }

    private static String reverseString(String str) {

        StringBuilder sb = new StringBuilder(str);

        return sb.reverse().toString();

    }

	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;

        }

    }

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

    static long mod = (int)1e9+7;

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

	{

		FastReader sc =new FastReader();

	    int t=sc.nextInt();

	   // int t=1;

	    while(t-->0)

	    {

	        int n=sc.nextInt();

	        int d=sc.nextInt();

	        int arr[] = sc.readArray(n);

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

	        {

	            int k = Math.min(arr[i] , d/i);

	            d-=k*i;

	            arr[0]+=k;

	        }

	        System.out.println(arr[0]);

	    }

	}

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

        }

        float nextFloat()

        {

            return Float.parseFloat(next());

        }

        String nextLine()

        {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long[] readArrayLong(int n) {

			long[] a=new long[n];

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

			return a;

		}

    }

    public static int[] radixSort2(int[] a)

	{

		int n = a.length;

		int[] c0 = new int[0x101];

		int[] c1 = new int[0x101];

		int[] c2 = new int[0x101];

		int[] c3 = new int[0x101];

		for(int v : a) {

			c0[(v&0xff)+1]++;

			c1[(v>>>8&0xff)+1]++;

			c2[(v>>>16&0xff)+1]++;

			c3[(v>>>24^0x80)+1]++;

		}

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

			c0[i+1] += c0[i];

			c1[i+1] += c1[i];

			c2[i+1] += c2[i];

			c3[i+1] += c3[i];

		}

		int[] t = new int[n];

		for(int v : a)t[c0[v&0xff]++] = v;

		for(int v : t)a[c1[v>>>8&0xff]++] = v;

		for(int v : a)t[c2[v>>>16&0xff]++] = v;

		for(int v : t)a[c3[v>>>24^0x80]++] = v;

		return a;

	}

    public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)

    {

        // Create a list from elements of HashMap

        List<Map.Entry<Integer, Integer> > list =

               new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());

        // Sort the list

        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {

            public int compare(Map.Entry<Integer, Integer> o1,

                               Map.Entry<Integer, Integer> o2)

            {

                return (o1.getValue()).compareTo(o2.getValue());

            }

        });

        // put data from sorted list to hashmap

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

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

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

        }

        return temp;

    }

    static void leftRotate(int arr[], int d, int n)

    {

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

            leftRotatebyOne(arr, n);

    }

    static void leftRotatebyOne(int arr[], int n)

    {

        int i, temp;

        temp = arr[0];

        for (i = 0; i < n - 1; i++)

            arr[i] = arr[i + 1];

        arr[n-1] = temp;

    }

    static boolean isPalindrome(String str)

    {

        // Pointers pointing to the beginning

        // and the end of the string

        int i = 0, j = str.length() - 1;

        // While there are characters to compare

        while (i < j) {

            // If there is a mismatch

            if (str.charAt(i) != str.charAt(j))

                return false;

            // Increment first pointer and

            // decrement the other

            i++;

            j--;

        }

        // Given string is a palindrome

        return true;

    }

    static boolean palindrome_array(char arr[], int n)

    {

        // Initialise flag to zero.

        int flag = 0;

        // Loop till array size n/2.

        for (int i = 0; i <= n / 2 && n != 0; i++) {

            // Check if first and last element are different

            // Then set flag to 1.

            if (arr[i] != arr[n - i - 1]) {

                flag = 1;

                break;

            }

        }

        // If flag is set then print Not Palindrome

        // else print Palindrome.

        if (flag == 1)

            return false;

        else

            return true;

    }

	static boolean allElementsEqual(int[] arr,int n)

	{

	    int z=0;

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

		    {

		        if(arr[i]==arr[i+1])

		        {

		            z++;

		        }

		    }

		    if(z==n-1)

		    {

		        return true;

		    }

		    else

		    {

		        return false;

		    }

	}

	static boolean allElementsDistinct(int[] arr,int n)

	{

	    int z=0;

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

		    {

		        if(arr[i]!=arr[i+1])

		        {

		            z++;

		        }

		    }

		    if(z==n-1)

		    {

		        return true;

		    }

		    else

		    {

		        return false;

		    }

	}

	public static void reverse(int[] array)

    {

        // Length of the array

        int n = array.length;

        // Swaping the first half elements with last half

        // elements

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

            // Storing the first half elements temporarily

            int temp = array[i];

            // Assigning the first half to the last half

            array[i] = array[n - i - 1];

            // Assigning the last half to the first half

            array[n - i - 1] = temp;

        }

    }

    public static void reverse_Long(long[] array)

    {

        // Length of the array

        int n = array.length;

        // Swaping the first half elements with last half

        // elements

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

            // Storing the first half elements temporarily

            long temp = array[i];

            // Assigning the first half to the last half

            array[i] = array[n - i - 1];

            // Assigning the last half to the first half

            array[n - i - 1] = temp;

        }

    }

	static boolean isSorted(int[] a)

    {

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

        {

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

                return false;

            }

        }

        return true;

    }

    static boolean isReverseSorted(int[] a)

    {

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

        {

            if (a[i] < a[i + 1]) {

                return false;

            }

        }

        return true;

    }

    static int[] rearrangeEvenAndOdd(int arr[], int n)

    {

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

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

		    {

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

		        {

		            list.add(arr[i]);

		        }

		    }

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

		    {

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

		        {

		            list.add(arr[i]);

		        }

		    }

		    int len = list.size();

		    int[] array = list.stream().mapToInt(i->i).toArray();

		    return array;

    }

    static long[] rearrangeEvenAndOddLong(long arr[], int n)

    {

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

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

		    {

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

		        {

		            list.add(arr[i]);

		        }

		    }

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

		    {

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

		        {

		            list.add(arr[i]);

		        }

		    }

		    int len = list.size();

		    long[] array = list.stream().mapToLong(i->i).toArray();

		    return array;

    }

    static boolean isPrime(long n)

    {

        // Check if number is less than

        // equal to 1

        if (n <= 1)

            return false;

        // Check if number is 2

        else if (n == 2)

            return true;

        // Check if n is a multiple of 2

        else if (n % 2 == 0)

            return false;

        // If not, then just check the odds

        for (long i = 3; i <= Math.sqrt(n); i += 2)

        {

            if (n % i == 0)

                return false;

        }

        return true;

    }

    static int getSum(int n)

    {

        int sum = 0;

        while (n != 0)

        {

            sum = sum + n % 10;

            n = n/10;

        }

    return sum;

    }

    static int gcd(int a, int b)

    {

      if (b == 0)

        return a;

      return gcd(b, a % b);

    }

    static long gcdLong(long a, long b)

    {

        if (b == 0)

        return a;

      return gcdLong(b, a % b);

    }

    static void swap(int i, int j)

    {

        int temp = i;

        i = j;

        j = temp;

    }

	static int countDigit(long n)

    {

        return (int)Math.floor(Math.log10(n) + 1);

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class MemeProb {

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

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

        var st = new StringTokenizer(r.readLine());

        var t = Integer.parseInt(st.nextToken());

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

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

            var first = Integer.parseInt(st.nextToken());

            var str = st.nextToken();

            var len = Long.valueOf(str.length()-1);

            var count = 0;

            for (char j : str.toCharArray()) {

                if (j=='9') {

                    count++;

                }

            }

            if(count==str.length()) {

                len++;

            }

            System.out.println(first*len);

        }

    }

}


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class D_Fight_with_Monsters {

    static long mod = Long.MAX_VALUE;

    public static void main(String[] args) {

        OutputStream outputStream = System.out;

        PrintWriter out = new PrintWriter(outputStream);

        FastReader f = new FastReader();

        int t = 1;

        while(t-- > 0){

            solve(f, out);

        }

        out.close();

    }

    public static void solve(FastReader f, PrintWriter out) {

        int n = f.nextInt();

        long a = f.nextLong();

        long b = f.nextLong();

        long k = f.nextLong();

        long arr[] = f.nextArray(n);

        long used[] = new long[n];

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

            long rem = arr[i]%(a+b);

            if(rem == 0) {

                rem = a+b;

            }

            used[i] = (rem+a-1)/a - 1;

        }

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

        //     out.print(used[i] + " ");

        // }

        // out.println();

        sort(used);

        int point = 0;

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

            if(k-used[i] >= 0) {

                point++;

                k -= used[i];

            } else {

                break;

            }

        }

        out.println(point);

    }

    // Sort an array

    public static void sort(long arr[]) {

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

        for(long i: arr) {

            al.add(i);

        }

        Collections.sort(al);

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

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

        }

    }

    // Find all divisors of n

    public static void allDivisors(int n) {

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

            if(n%i == 0) {

                System.out.println(i + " ");

                if(i != n/i) {

                    System.out.println(n/i + " ");

                }

            }

        }

    }

    // Check if n is prime or not

    public static boolean isPrime(int n) {

        if(n < 1) return false;

        if(n == 2 || n == 3) return true;

        if(n % 2 == 0 || n % 3 == 0) return false;

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

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

                return false;

            }

        }

        return true;

    }

    // Find gcd of a and b

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

        long dividend = a > b ? a : b;

        long divisor =  a < b ? a : b;

        while(divisor > 0) {

            long reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

    // Find lcm of a and b

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

        long lcm = gcd(a, b);

        long hcf = (a * b) / lcm;

        return hcf;

    }

    // Find factorial in O(n) time

    public static long fact(int n) {

        long res = 1;

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

            res = res * i;

        }

        return res;

    }

    // Find power in O(logb) time

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

        long res = 1;

        while(b > 0) {

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

                res = (res * a)%mod;

            }

            a = (a * a)%mod;

            b >>= 1;

        }

        return res;

    }

    // Find nCr

    public static long nCr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / (fact(r) * fact(n-r));

        return ans;

    }

    // Find nPr

    public static long nPr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / fact(r);

        return ans;

    }

    // sort all characters of a string

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    // User defined class for fast I/O

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

        }

        boolean hasNext() {

            if (st != null && st.hasMoreTokens()) {

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        long[] nextArray(int n) {

            long[] a = new long[n];

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

                a[i] = nextLong();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

---------                           ---------     ---------     ----------

  0  NUL (null)                      32  SPACE     64  @         96  `

  1  SOH (start of heading)          33  !         65  A         97  a

  2  STX (start of text)             34  "         66  B         98  b

  3  ETX (end of text)               35  #         67  C         99  c

  4  EOT (end of transmission)       36  $         68  D        100  d

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

  9  TAB (horizontal tab)            41  )         73  I        105  i

 10  LF  (NL line feed, new line)    42  *         74  J        106  j

 11  VT  (vertical tab)              43  +         75  K        107  k

 12  FF  (NP form feed, new page)    44  ,         76  L        108  l

 13  CR  (carriage return)           45  -         77  M        109  m

 14  SO  (shift out)                 46  .         78  N        110  n

 15  SI  (shift in)                  47  /         79  O        111  o

 16  DLE (data link escape)          48  0         80  P        112  p

 17  DC1 (device control 1)          49  1         81  Q        113  q

 18  DC2 (device control 2)          50  2         82  R        114  r

 19  DC3 (device control 3)          51  3         83  S        115  s

 20  DC4 (device control 4)          52  4         84  T        116  t

 21  NAK (negative acknowledge)      53  5         85  U        117  u

 22  SYN (synchronous idle)          54  6         86  V        118  v

 23  ETB (end of trans. block)       55  7         87  W        119  w

 24  CAN (cancel)                    56  8         88  X        120  x

 25  EM  (end of medium)             57  9         89  Y        121  y

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

 28  FS  (file separator)            60  <         92  \        124  |

 29  GS  (group separator)           61  =         93  ]        125  }

 30  RS  (record separator)          62  >         94  ^        126  ~

 31  US  (unit separator)            63  ?         95  _        127  DEL

 */

// (a/b)%mod == (a * moduloInverse(b)) % mod;

// moduloInverse(b) = power(b, mod-2);


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

import java.io.*;

import java.util.*;

public class  Main{

	static class node implements Comparable<node>{

		int i,val;

		node(int ii,int v){

			i=ii;val=v;

		}

		@Override

		public int compareTo(node o) {

			if(val==o.val)return i-o.i;

			return val-o.val;

		}

		public String toString() {return i+" "+val;}

	}

	static LinkedList<Integer>children[];

	static int[]cnt;

	static boolean ok=true;

	static int[]empty=new int[1];

	static ArrayList<node> dfs(int i) {

		if(!ok) {

			return new ArrayList<node>();

		}

		if(children[i].size()==0) {

			if(cnt[i]>0) {

				ok=false;

				return new ArrayList<node>();

			}

			ArrayList<node>arr=new ArrayList<Main.node>();

			arr.add(new node(i, 1));

			return arr;

		}

		ArrayList<node>arr=new ArrayList<Main.node>();

		for(int j:children[i]) {

			ArrayList<node>child=dfs(j);

			for(node n:child) {

				arr.add(n);

			}

		}

		if(cnt[i]>arr.size()) {

			ok=false;

			return new ArrayList<node>();

		}

		Collections.sort(arr);

		//System.out.println(i+" "+arr);

		int val;

		if(cnt[i]==0)val=1;

		else {

			val=arr.get(cnt[i]-1).val+1;

		}

		if(cnt[i]<arr.size() && arr.get(cnt[i]).val<=val) {

			int dif=val-arr.get(cnt[i]).val+1;

			for(int idx=cnt[i];idx<arr.size();idx++) {

					node cur=arr.get(idx);

					arr.set(idx, new node(cur.i, cur.val+dif));

			}

		}

		arr.add(new node(i, val));

		return arr;

	}

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

		MScanner sc=new MScanner(System.in);

		PrintWriter pw=new PrintWriter(System.out);

		int n=sc.nextInt();

		children=new LinkedList[n];

		cnt=new int[n];

		int root=-1;

		for(int i=0;i<n;i++)children[i]=new LinkedList<Integer>();

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

			int par=sc.nextInt()-1;cnt[i]=sc.nextInt();

			if(par!=-1) {

				children[par].add(i);

			}

			else {

				root=i;

			}

		}

		ArrayList<node>ans=dfs(root);

		//System.out.println(ans);

		if(!ok) {

			pw.println("NO");

			pw.flush();

			return;

		}

		pw.println("YES");

		int[]vals=new int[n];

		for(node x:ans) {

			vals[x.i]=x.val;

		}

		for(int i:vals)pw.println(i);

		pw.flush();

	}

	static class MScanner {

		StringTokenizer st;

		BufferedReader br;

		public MScanner(InputStream system) {

			br = new BufferedReader(new InputStreamReader(system));

		}

		public MScanner(String file) throws Exception {

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

		}

		public String next() throws IOException {

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

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

			return st.nextToken();

		}

		public int[] takearr(int n) throws IOException {

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

	        return in;

		}

		public long[] takearrl(int n) throws IOException {

	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();

	        return in;

		}

		public Integer[] takearrobj(int n) throws IOException {

	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();

	        return in;

		}

		public Long[] takearrlobj(int n) throws IOException {

	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();

	        return in;

		}

		public String nextLine() throws IOException {

			return br.readLine();

		}

		public int nextInt() throws IOException {

			return Integer.parseInt(next());

		}

		public double nextDouble() throws IOException {

			return Double.parseDouble(next());

		}

		public char nextChar() throws IOException {

			return next().charAt(0);

		}

		public Long nextLong() throws IOException {

			return Long.parseLong(next());

		}

		public boolean ready() throws IOException {

			return br.ready();

		}

		public void waitForInput() throws InterruptedException {

			Thread.sleep(3000);

		}

	}

}


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

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import static java.lang.System.out;

import java.util.*;

import java.io.*;

import java.math.*;

/*

-> Give your 100%, that's it!

-> Rule To Solve Any Problem:

    1. Read the problem.

    2. Think About It.

    3. Solve it!

*/

public class Template {

	static int mod = 1000000007;

	public static void main(String[] args){

        FastScanner sc = new FastScanner();

        PrintWriter out = new PrintWriter(System.out);

        int yo = sc.nextInt();

        while (yo-- > 0) {

            int a = sc.nextInt(), b = sc.nextInt();

            int x = sc.nextInt(), y = sc.nextInt();

            int up = x * b;

            int down =(a-x-1) * b;

            int left = a * y;

            int right = a * (b-y-1);

            out.println(max(max(up,down),max(left,right)));

        }

        out.close();

	}

    /*

    Source: hu_tao

         Random stuff to try when stuck:

            -if it's 2C then it's dp

            -for combo/probability problems, expand the given form we're interested in

            -make everything the same then build an answer (constructive, make everything 0 then do something)

            -something appears in parts of 2 --> model as graph

            -assume a greedy then try to show why it works

            -find way to simplify into one variable if multiple exist

            -treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)

            -find lower and upper bounds on answer

            -figure out what ur trying to find and isolate it

            -see what observations you have and come up with more continuations

            -work backwards (in constructive, go from the goal to the start)

            -turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)

            -instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)

            -draw something

            -simulate a process

            -dont implement something unless if ur fairly confident its correct

            -after 3 bad submissions move on to next problem if applicable

            -do something instead of nothing and stay organized

            -write stuff down

         Random stuff to check when wa:

            -if code is way too long/cancer then reassess

            -switched N/M

            -int overflow

            -switched variables

            -wrong MOD

            -hardcoded edge case incorrectly

         Random stuff to check when tle:

            -continue instead of break

            -condition in for/while loop bad

         Random stuff to check when rte:

            -switched N/M

            -long to int/int overflow

            -division by 0

            -edge case for empty list/data structure/N=1

      */

	public static class Pair {

		int x;

		int y;

		public Pair(int x, int y) {

			this.x = x;

			this.y = y;

		}

	}

	public static void sort(int[] arr) {

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

		for (int x : arr)

			ls.add(x);

		Collections.sort(ls);

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

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

	}

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

		if (b == 0)

			return a;

		return gcd(b, a % b);

	}

	static boolean[] sieve(int N) {

		boolean[] sieve = new boolean[N + 1];

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

			sieve[i] = true;

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

			if (sieve[i]) {

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

					sieve[j] = false;

				}

			}

		}

		return sieve;

	}

	public static long power(long x, long y, long p) {

		long res = 1L;

		x = x % p;

		while (y > 0) {

			if ((y & 1) == 1)

				res = (res * x) % p;

			y >>= 1;

			x = (x * x) % p;

		}

		return res;

	}

	public static void print(int[] arr) {

		//for debugging only

		for (int x : arr)

			out.print(x + " ");

		out.println();

	}

	static class FastScanner {

		private int BS = 1 << 16;

		private char NC = (char) 0;

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

		private int bId = 0, size = 0;

		private char c = NC;

		private double cnt = 1;

		private BufferedInputStream in;

		public FastScanner() {

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

		}

		public FastScanner(String s) {

			try {

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

			} catch (Exception e) {

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

			}

		}

		private char getChar() {

			while (bId == size) {

				try {

					size = in.read(buf);

				} catch (Exception e) {

					return NC;

				}

				if (size == -1)

					return NC;

				bId = 0;

			}

			return (char) buf[bId++];

		}

		public int nextInt() {

			return (int) nextLong();

		}

		public int[] readInts(int N) {

			int[] res = new int[N];

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

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

			}

			return res;

		}

		public long[] readLongs(int N) {

			long[] res = new long[N];

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

				res[i] = nextLong();

			}

			return res;

		}

		public long nextLong() {

			cnt = 1;

			boolean neg = false;

			if (c == NC)

				c = getChar();

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

				if (c == '-')

					neg = true;

			}

			long res = 0;

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

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

				cnt *= 10;

			}

			return neg ? -res : res;

		}

		public double nextDouble() {

			double cur = nextLong();

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

		}

		public double[] readDoubles(int N) {

			double[] res = new double[N];

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

				res[i] = nextDouble();

			}

			return res;

		}

		public String next() {

			StringBuilder res = new StringBuilder();

			while (c <= 32)

				c = getChar();

			while (c > 32) {

				res.append(c);

				c = getChar();

			}

			return res.toString();

		}

		public String nextLine() {

			StringBuilder res = new StringBuilder();

			while (c <= 32)

				c = getChar();

			while (c != '\n') {

				res.append(c);

				c = getChar();

			}

			return res.toString();

		}

		public boolean hasNext() {

			if (c > 32)

				return true;

			while (true) {

				c = getChar();

				if (c == NC)

					return false;

				else if (c > 32)

					return true;

			}

		}

	}

	//	For Input.txt and Output.txt

	//	FileInputStream in = new FileInputStream("input.txt");

	//	FileOutputStream out = new FileOutputStream("output.txt");

	//	PrintWriter pw = new PrintWriter(out);

	//	Scanner sc = new Scanner(in);

}


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1

/*

    Author: Anthony Ngene

    Created: 06/10/2020 - 07:03

*/

import java.io.*;

import java.util.*;

public class G {

// checks: 1. edge cases   2. overflow   3. possible errors (e.g 1/0, arr[out])   4. time/space complexity

    void solver() throws IOException {

        int n = in.intNext(), k = in.intNext();

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

        ArrayList<Tuple>[] adj = new ArrayList[n + 1];

        Tuple[] roads = new Tuple[n - 1];

        for (int i = 1; i < n + 1; i++) adj[i] = new ArrayList<>();

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

            int a = in.intNext(), b = in.intNext();

            nodes[a]++;

            nodes[b]++;

            Tuple road = new Tuple(a, b);

            roads[i] = road;

            adj[a].add(road);

            adj[b].add(road);

        }

//        out.println(nodes);

        int lo = 0;

        int hi = n - 1;

        int valid = 0;

        while (lo <= hi) {

            int mid = (lo + hi) / 2;

            int over = 0;

            for (int i = 1; i < n + 1; i++) if (nodes[i] > mid) over++;

            if (over <= k) {

                valid = mid;

                hi = mid - 1;

            } else

                lo = mid + 1;

        }

        out.println(valid);

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

        Deque<Integer> deque = new ArrayDeque<>();

        deque.addLast(1);

        nodes[1] = -1;

        int owner = 0;

        while (!deque.isEmpty()) {

            int idx = deque.pollFirst();

            visited[idx] = true;

            int prev = nodes[idx];

            for (Tuple child : adj[idx]) {

                int other = child.a == idx ? child.b : child.a;

                if (visited[other]) continue;

                if (owner == prev) owner = (owner + 1) % valid;

                nodes[other] = owner;

                child.c = owner;

                owner = (owner + 1) % valid;

                deque.addLast(other);

            }

        }

        for (int i = 0; i < n - 1; i++) out.p(roads[i].c + 1).p(" ");

    }

// Generated Code Below:

private static final FastWriter out = new FastWriter();

private static FastScanner in;

static ArrayList<Integer>[] adj;

private static long e97 = (long)1e9 + 7;

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

    in = new FastScanner();

    new G().solver();

    out.close();

}

static class FastWriter {

    private static final int IO_BUFFERS = 128 * 1024;

    private final StringBuilder out;

    public FastWriter() { out = new StringBuilder(IO_BUFFERS); }

    public FastWriter p(Object object) { out.append(object); return this; }

    public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }

    public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" ");  } out.append("\n"); return this; }

    public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }

    public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }

    public void println(long[][] arr) {  for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public void println(int[][] arr) {  for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public void println(char[][] arr) {  for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public void println(double[][] arr) {  for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public <T>void println(T[][] arr) {  for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }

    public FastWriter println(Object object) { out.append(object).append("\n"); return this; }

    public void toFile(String fileName) throws IOException {

        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));

        writer.write(out.toString());

        writer.close();

    }

    public void close() throws IOException { System.out.print(out); }

}

static class FastScanner {

    private InputStream sin = System.in;

    private final byte[] buffer = new byte[1024];

    private int ptr = 0;

    private int buflen = 0;

    public FastScanner(){}

    public FastScanner(String filename) throws FileNotFoundException {

        File file = new File(filename);

        sin = new FileInputStream(file);

    }

    private boolean hasNextByte() {

        if (ptr < buflen) {

            return true;

        }else{

            ptr = 0;

            try {

                buflen = sin.read(buffer);

            } catch (IOException e) {

                e.printStackTrace();

            }

            if (buflen <= 0) {

                return false;

            }

        }

        return true;

    }

    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}

    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}

    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}

    public String next() {

        if (!hasNext()) throw new NoSuchElementException();

        StringBuilder sb = new StringBuilder();

        int b = readByte();

        while(isPrintableChar(b)) {

            sb.appendCodePoint(b);

            b = readByte();

        }

        return sb.toString();

    }

    public long longNext() {

        if (!hasNext()) throw new NoSuchElementException();

        long n = 0;

        boolean minus = false;

        int b = readByte();

        if (b == '-') {

            minus = true;

            b = readByte();

        }

        if (b < '0' || '9' < b) {

            throw new NumberFormatException();

        }

        while(true){

            if ('0' <= b && b <= '9') {

                n *= 10;

                n += b - '0';

            }else if(b == -1 || !isPrintableChar(b) || b == ':'){

                return minus ? -n : n;

            }else{

                throw new NumberFormatException();

            }

            b = readByte();

        }

    }

    public int intNext() {

        long nl = longNext();

        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();

        return (int) nl;

    }

    public double doubleNext() { return Double.parseDouble(next());}

    public long[] nextLongArray(final int n){

        final long[] a = new long[n];

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

            a[i] = longNext();

        return a;

    }

    public int[] nextIntArray(final int n){

        final int[] a = new int[n];

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

            a[i] = intNext();

        return a;

    }

    public double[] nextDoubleArray(final int n){

        final double[] a = new double[n];

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

            a[i] = doubleNext();

        return a;

    }

    public ArrayList<Integer>[] getAdj(int n) {

        ArrayList<Integer>[] adj = new ArrayList[n + 1];

        for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();

        return adj;

    }

    public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {

        return adjacencyList(nodes, edges, false);

    }

    public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {

        adj = getAdj(nodes);

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

            int a = intNext(), b = intNext();

            adj[a].add(b);

            if (!isDirected) adj[b].add(a);

        }

        return adj;

    }

}

static class u {

    public static int upperBound(long[] array, long obj) {

        int l = 0, r = array.length - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj < array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    public static int upperBound(ArrayList<Long> array, long obj) {

        int l = 0, r = array.size() - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj < array.get(c)) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    public static int lowerBound(long[] array, long obj) {

        int l = 0, r = array.length - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj <= array[c]) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    public static int lowerBound(ArrayList<Long> array, long obj) {

        int l = 0, r = array.size() - 1;

        while (r - l >= 0) {

            int c = (l + r) / 2;

            if (obj <= array.get(c)) {

                r = c - 1;

            } else {

                l = c + 1;

            }

        }

        return l;

    }

    static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }

    static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }

    static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }

    private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }

    private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }

    private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }

    private static void customSort(int[][] arr) {

        Arrays.sort(arr, new Comparator<int[]>() {

            public int compare(int[] a, int[] b) {

                if (a[0] == b[0]) return Integer.compare(a[1], b[1]);

                return Integer.compare(a[0], b[0]);

            }

        });

    }

    public static int[] swap(int[] arr, int left, int right) {

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

    public static char[] swap(char[] arr, int left, int right) {

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        return arr;

    }

    public static int[] reverse(int[] arr, int left, int right) {

        while (left < right) {

            int temp = arr[left];

            arr[left++] = arr[right];

            arr[right--] = temp;

        }

        return arr;

    }

    public static boolean findNextPermutation(int[] data) {

        if (data.length <= 1) return false;

        int last = data.length - 2;

        while (last >= 0) {

            if (data[last] < data[last + 1]) break;

            last--;

        }

        if (last < 0) return false;

        int nextGreater = data.length - 1;

        for (int i = data.length - 1; i > last; i--) {

            if (data[i] > data[last]) {

                nextGreater = i;

                break;

            }

        }

        data = swap(data, nextGreater, last);

        data = reverse(data, last + 1, data.length - 1);

        return true;

    }

    public static int biSearch(int[] dt, int target){

        int left=0, right=dt.length-1;

        int mid=-1;

        while(left<=right){

            mid = (right+left)/2;

            if(dt[mid] == target) return mid;

            if(dt[mid] < target) left=mid+1;

            else right=mid-1;

        }

        return -1;

    }

    public static int biSearchMax(long[] dt, long target){

        int left=-1, right=dt.length;

        int mid=-1;

        while((right-left)>1){

            mid = left + (right-left)/2;

            if(dt[mid] <= target) left=mid;

            else right=mid;

        }

        return left;

    }

    public static int biSearchMaxAL(ArrayList<Integer> dt, long target){

        int left=-1, right=dt.size();

        int mid=-1;

        while((right-left)>1){

            mid = left + (right-left)/2;

            if(dt.get(mid) <= target) left=mid;

            else right=mid;

        }

        return left;

    }

    private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(int[][] ob, int res){      for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(long[][] ob, long res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(char[][] ob, char res){    for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){  ob[i][j] = res; }}}

    private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}

    private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}

    private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}

    private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }

    private static boolean same3(long a, long b, long c){

        if(a!=b) return false;

        if(b!=c) return false;

        if(c!=a) return false;

        return true;

    }

    private static boolean dif3(long a, long b, long c){

        if(a==b) return false;

        if(b==c) return false;

        if(c==a) return false;

        return true;

    }

    private static double hypotenuse(double a, double b){

        return Math.sqrt(a*a+b*b);

    }

    private static long factorial(int n) {

        long ans=1;

        for(long i=n; i>0; i--){ ans*=i; }

        return ans;

    }

    private static long facMod(int n, long mod) {

        long ans=1;

        for(long i=n; i>0; i--) ans = (ans * i) % mod;

        return ans;

    }

    private static long lcm(long m, long n){

        long ans = m/gcd(m,n);

        ans *= n;

        return ans;

    }

    private static long gcd(long m, long n) {

        if(m < n) return gcd(n, m);

        if(n == 0) return m;

        return gcd(n, m % n);

    }

    private static boolean isPrime(long a){

        if(a==1) return false;

        for(int i=2; i<=Math.sqrt(a); i++){  if(a%i == 0) return false;  }

        return true;

    }

    static long modInverse(long a, long mod) {

    /* Fermat's little theorem: a^(MOD-1) => 1

    Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */

        return binpowMod(a, mod - 2, mod);

    }

    static long binpowMod(long a, long b, long mod) {

        long res = 1;

        while (b > 0) {

            if (b % 2 == 1) res = (res * a) % mod;

            a = (a * a) % mod;

            b /= 2;

        }

        return res;

    }

    private static int getDigit2(long num){

        long cf = 1;    int d=0;

        while(num >= cf){   d++;    cf = 1<<d;  }

        return d;

    }

    private static int getDigit10(long num){

        long cf = 1;    int d=0;

        while(num >= cf){   d++;    cf*=10;     }

        return d;

    }

    private static boolean isInArea(int y, int x, int h, int w){

        if(y<0) return false;

        if(x<0) return false;

        if(y>=h) return false;

        if(x>=w) return false;

        return true;

    }

    private static ArrayList<Integer> generatePrimes(int n) {

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

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

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

            if (lp[i] == 0) {

                lp[i] = i;

                pr.add(i);

            }

            for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {

                lp[i * pr.get(j)] = pr.get(j);

            }

        }

        return pr;

    }

    static long nPrMod(int n, int r, long MOD) {

        long res = 1;

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

            res = (res * i) % MOD;

        }

        return res;

    }

    static long nCr(int n, int r) {

        if (r > (n - r))

            r = n - r;

        long ans = 1;

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

            ans *= n;

            ans /= i;

            n--;

        }

        return ans;

    }

    static long nCrMod(int n, int r, long MOD) {

        long rFactorial = nPrMod(r, r, MOD);

        long first = nPrMod(n, r, MOD);

        long second = binpowMod(rFactorial, MOD-2, MOD);

        return  (first * second) % MOD;

    }

    static void printBitRepr(int n) {

        StringBuilder res = new StringBuilder();

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

            int mask = (1 << i);

            res.append((mask & n) == 0 ? "0" : "1");

        }

        out.println(res);

    }

    static String bitString(int n) {return Integer.toBinaryString(n);}

    static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed

    static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }

    static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }

    static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }

    static HashMap<Character, Integer> counts(String word) {

        HashMap<Character, Integer> counts = new HashMap<>();

        for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);

        return counts;

    }

    static HashMap<Integer, Integer> counts(int[] arr) {

        HashMap<Integer, Integer> counts = new HashMap<>();

        for (int value : arr) counts.merge(value, 1, Integer::sum);

        return counts;

    }

    static HashMap<Long, Integer> counts(long[] arr) {

        HashMap<Long, Integer> counts = new HashMap<>();

        for (long l : arr) counts.merge(l, 1, Integer::sum);

        return counts;

    }

    static HashMap<Character, Integer> counts(char[] arr) {

        HashMap<Character, Integer> counts = new HashMap<>();

        for (char c : arr) counts.merge(c, 1, Integer::sum);

        return counts;

    }

    static long hash(int x, int y) {

        return x* 1_000_000_000L +y;

    }

    static final Random random = new Random();

    static void sort(int[] a) {

        int n = a.length;// shuffle, then sort

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

            int oi = random.nextInt(n), temp = a[oi];

            a[oi] = a[i];

            a[i] = temp;

        }

        Arrays.sort(a);

    }

    static void sort(long[] arr) {

        shuffleArray(arr);

        Arrays.sort(arr);

    }

    static void shuffleArray(long[] arr) {

        int n = arr.length;

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

            long tmp = arr[i];

            int randomPos = i + random.nextInt(n-i);

            arr[i] = arr[randomPos];

            arr[randomPos] = tmp;

        }

    }

}

static class Tuple implements Comparable<Tuple> {

    int a;

    int b;

    int c;

    public Tuple(int a, int b) {

        this.a = a;

        this.b = b;

        this.c = 0;

    }

    public Tuple(int a, int b, int c) {

        this.a = a;

        this.b = b;

        this.c = c;

    }

    public int getA() { return a; }

    public int getB() { return b; }

    public int getC() { return c; }

    public int compareTo(Tuple other) {

        if (this.a == other.a) {

            if (this.b == other.b) return Long.compare(this.c, other.c);

            return Long.compare(this.b, other.b);

        }

        return Long.compare(this.a, other.a);

    }

    @Override

    public int hashCode() { return Arrays.deepHashCode(new Integer[]{a, b, c}); }

    @Override

    public boolean equals(Object o) {

        if (!(o instanceof Tuple)) return false;

        Tuple pairo = (Tuple) o;

        return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);

    }

    @Override

    public String toString() { return String.format("(%d %d %d)  ", this.a, this.b, this.c); }

}

private static int abs(int a){  return (a>=0) ? a: -a;  }

private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }

private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }

private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }

private static long abs(long a){    return (a>=0) ? a: -a;  }

private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }

private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }

private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }

private static double abs(double a){    return (a>=0) ? a: -a;  }

private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }

private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }

private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }

}


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 Main {

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

        for (Map.Entry<Long, List<int[]>> x : map.entrySet()) {

            List<int[]> cur = x.getValue();

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

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

            int prev =0;

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

                if (cur.get(i)[0] > prev) {

                    temp.add(cur.get(i));

                    prev = cur.get(i)[1];

                }

            }

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

                ans = temp;

            }

        }

        out.println(ans.size());

        for (int[] x : ans) {

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

    }

}


C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

import java.io.*;

import java.nio.file.FileStore;

import java.util.*;

 public class zia

 {

	static void BFS(ArrayList<ArrayList<Integer>> adj,int s, boolean[] visited)

	{

    	Queue<Integer> q=new LinkedList<>();

    	visited[s] = true;

    	q.add(s);

    	while(q.isEmpty()==false)

    	{

    		int u = q.poll();

    		for(int v:adj.get(u)){

    		    if(visited[v]==false){

    		        visited[v]=true;

    		        q.add(v);

    		    }

    		}

    	}

	}

	// static int BFS(ArrayList<ArrayList<Integer>> adj,pair s, boolean[] visited,int ar[],int m)

	// {

    // 	Queue<pair> q=new LinkedList<>();

    // 	visited[s.a] = true;

    // 	q.add(s);

	// 	int count=0;

    // 	while(q.isEmpty()==false)

    // 	{

    // 		pair u = q.poll();

	// 		// if(adj.get(u.a).size()==0)

	// 		// count++;

	// 		boolean end=true;

    // 		for(int v:adj.get(u.a)){

    // 		    if(visited[v]==false){

    // 		        visited[v]=true;

	// 				end=false;

	// 				int cat=ar[v]==0?0:ar[v]+u.b;

	// 				if(cat>m)

	// 				continue;

    // 		        q.add(new pair(v, cat));

	// 				// System.out.print("--"+v+" "+cat+"--");

    // 		    }

    // 		}

	// 		if(end)

	// 		count++;

	// 		// System.out.println(u.a+" "+adj.get(u.a).size()+" count "+count);

    // 	}

	// 	return count;

	// }

	static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v)

	{

		adj.get(u).add(v);

		adj.get(v).add(u);

	}

	static void ruffleSort(long[] a) {

        int n=a.length;

		Random random = new Random();

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

            int oi=random.nextInt(n);

			long temp=a[oi];

            a[oi]=a[i]; a[i]=temp;

        }

        Arrays.sort(a);

    }

	static void ruffleSort(int[] a) {

        int n=a.length;

		Random random = new Random();

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

            int oi=random.nextInt(n);

			int temp=a[oi];

            a[oi]=a[i]; a[i]=temp;

        }

        Arrays.sort(a);

    }

	public static int Lcm(int a,int b)

	{ int max=Math.max(a,b);

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

		{

			if((max*i)%a==0&&(max*i)%b==0)

			return (max*i);

		}

	}

  static void sieve(int n,boolean prime[])

    {

        // boolean prime[] = new boolean[n + 1];

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

            prime[i] = true;

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

            if (prime[p] == true) {

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

                    prime[i] = false;

            }

        }

    }

	// public static String run(int ar[],int n)

	// {

	// }

	public static int upperbound(int s,int e, long ar[],long x)

	{

		int res=-1;

		while(s<=e)

		{ int mid=((s-e)/2)+e;

			if(ar[mid]>x)

			{e=mid-1;res=mid;}

			else if(ar[mid]<x)

			{s=mid+1;}

			else

			{e=mid-1;res=mid;

			 if(mid>0&&ar[mid]==ar[mid-1])

			 e=mid-1;

			 else

			 break;

			}

		}

		return res;

	}

	public static long lowerbound(int s,int e, long ar[],long x)

	{

		long res=-1;

		while(s<=e)

		{ int mid=((s-e)/2)+e;

			if(ar[mid]>x)

			{e=mid-1;}

			else if(ar[mid]<x)

			{s=mid+1;res=mid;}

			else

			{res=mid;

				if(mid+1<ar.length&&ar[mid]==ar[mid+1])

			    s=mid+1;

			    else

				break;}

		}

		return res;

	}

	static long modulo=1000000007;

	public static long power(long a, long b)

	{

		if(b==0) return 1;

		long temp=power(a,b/2)%modulo;

		if((b&1)==0)

		return (temp*temp)%modulo;

		else

		return (((temp*temp)%modulo)*a)%modulo;

	}

	public static long powerwithoutmod(long a, long b)

	{

		if(b==0) return 1;

		long temp=power(a,b/2);

		if((b&1)==0)

		return (temp*temp);

		else

		return ((temp*temp)*a);

	}

	public static double log2(long a)

	{ double d=Math.log(a)/Math.log(2);

		return d;

	}

	public static int log10(long a)

	{ double d=Math.log(a)/Math.log(10);

		return (int)d;

	}

	public static long gcd(long a, long b)

    {

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

	public static void tree(int s,int e,int ar[],int c)

	{

	  if(s<=e)

	  {

		  int max=s;

		  for(int i=s;i<=e;i++)

		   if(ar[i]>ar[max])

			 max=i;

		  ar[max]=c++;

		  tree(s,max-1,ar,c);

		  tree(max+1,e,ar,c);

	  }

	}

 static int resturant=0;

 static void DFS(ArrayList<ArrayList<Integer>> al,boolean visited[],int s,int max,int curr,int ar[])

 {

	visited[s]=true;

	if(al.get(s).size()==1&&visited[al.get(s).get(0)]==true)

	{resturant++;return;}

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

	for(int x:al.get(s))

	{

		if(visited[x]==false)

		{

			if(ar[x]==0)

			DFS(al, visited, x, max, 0, ar);

			else if(curr+ar[x]<=max)

			DFS(al, visited, x, max, curr+ar[x], ar);

		}

	}

 }

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

   {

		FastIO sc = new FastIO();

		//sc.println();

//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

		int test=sc.nextInt();

		// // double c=Math.log(10);

		// boolean prime[]=new boolean[233334];

		// sieve(233334, prime);

		// HashMap<Character,Integer> hm=new HashMap<>(9);

		// char c='1';

		// for(int i=1;i<=9;i++)

		//  hm.put(c++,i);

		while(test-->0)

		{

			int n=sc.nextInt();

			long in=sc.nextLong();

			triplet ar[]=new triplet[n];

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

			  ar[i]=new triplet(sc.nextLong(),sc.nextLong(),sc.nextLong());

			Arrays.sort(ar);

			long s=in,e=in;

			String res="YES";

			// sc.println(s+"--"+e);

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

			{

				long deltaT=ar[i].first;

				if(i!=0)

				deltaT-=ar[i-1].first;

				long currs=s-deltaT,curre=e+deltaT;

				if(currs>ar[i].third||curre<ar[i].second)

				{

					res="NO";

					break;

				}

				s=Math.max(currs, ar[i].second);

				e=Math.min(curre, ar[i].third);

				// sc.println(s+" "+e);

			}

			sc.println(res);

		}

// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

sc.close();

}

}

class pair implements Comparable<pair>{

	int a;

	int b;

	pair(int a,int b)

	{this.a=a;

		this.b=b;

	}

	public int compareTo(pair p)

	{

		if(this.a-p.a==0)

		return this.b-p.b;

		return (this.a-p.a);

	}

}

class triplet implements Comparable<triplet>{

	long first,second,third;

	triplet(long first,long second,long third)

	{this.first=first;

		this.second=second;

		this.third=third;

	}

	public int compareTo(triplet p)

	{

		return (int)(this.first-p.first);

	}

}

// class triplet

// {

// 	int x1,x2,i;

// 	triplet(int a,int b,int c)

// 	{x1=a;x2=b;i=c;}

// }

 class FastIO extends PrintWriter {

	private InputStream stream;

	private byte[] buf = new byte[1<<16];

	private int curChar, numChars;

	// standard input

	public FastIO() { this(System.in,System.out); }

	public FastIO(InputStream i, OutputStream o) {

		super(o);

		stream = i;

	}

	// file input

	public FastIO(String i, String o) throws IOException {

		super(new FileWriter(o));

		stream = new FileInputStream(i);

	}

	// throws InputMismatchException() if previously detected end of file

	private int nextByte() {

		if (numChars == -1) throw new InputMismatchException();

		if (curChar >= numChars) {

			curChar = 0;

			try {

				numChars = stream.read(buf);

			} catch (IOException e) {

				throw new InputMismatchException();

			}

			if (numChars == -1) return -1; // end of file

		}

		return buf[curChar++];

	}

	public String nextLine() {

		int c; do { c = nextByte(); } while (c <= '\n');

		StringBuilder res = new StringBuilder();

		do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n');

		return res.toString();

	}

	public String next() {

		int c; do { c = nextByte(); } while (c <= ' ');

		StringBuilder res = new StringBuilder();

		do { res.appendCodePoint(c); c = nextByte(); } while (c > ' ');

		return res.toString();

	}

	public int nextInt() {

		int c; do { c = nextByte(); } while (c <= ' ');

		int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }

		int res = 0;

		do {

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

				throw new InputMismatchException();

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

			c = nextByte();

		} while (c > ' ');

		return res * sgn;

	}

  public long nextLong() {

		int c; do { c = nextByte(); } while (c <= ' ');

		long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); }

		long res = 0;

		do {

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

				throw new InputMismatchException();

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

			c = nextByte();

		} while (c > ' ');

		return res * sgn;

	}

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

}


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

import java.util.Scanner;

public class IntTree {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        int t = s.nextInt();

        while(t-->0){

            int n=s.nextInt();

            int x=s.nextInt();

            int y=s.nextInt();

            int min=Math.max(1,Math.min(n,x+y-n+1));

            int max=Math.min(n,x+y-1);

            System.out.println(min+" "+max);

        }

    }

}