F1. Same Sum Blocks (Easy)time limit per test2 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≤501≤n≤50) — 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.lang.*;

import java.io.*;

import java.awt.*;

// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................

//JUst keep faith in ur strengths ..................................................

// ASCII = 48 + i ;// 2^28 = 268,435,456  > 2* 10^8 // log 10 base 2 = 3.3219

// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1  x >=4

// FOR ANY ODD NO N : N,N-1,N-2

//ALL ARE PAIRWISE COPRIME

//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS

// two consecutive odds are always coprime to each other

// two consecutive even have always gcd  = 2 ;

// Rectangle r = new Rectangle(int x , int y,int widht,int height)

//Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))

//BY DEFAULT Priority Queue is MIN in nature in java

//to use as max , just push with negative sign and change sign after removal

// We can make a sieve of max size 1e7 .(no time or space issue)

// In 1e7 starting nos we have about 66*1e4 prime nos

 public class Main

{

    // static int[] arr = new int[100002] ;

    // static int[] dp = new int[100002] ;

     static PrintWriter out;

	static class FastReader{

		BufferedReader br;

		StringTokenizer st;

		public FastReader(){

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

			out=new PrintWriter(System.out);

		}

		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;

		}

	}

////////////////////////////////////////////////////////////////////////////////////

 public static int countDigit(long n)

    {

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

    }

/////////////////////////////////////////////////////////////////////////////////////////

 public static int sumOfDigits(long n)

 {

  if( n< 0)return -1 ;

  int sum = 0;

  while( n > 0)

  {

      sum = sum + (int)( n %10) ;

      n /= 10 ;

  }

  return sum ;

 }

 //////////////////////////////////////////////////////////////////////////////////////////////////

public static long arraySum(int[] arr , int start , int end)

{

    long ans = 0 ;

    for(int i = start ; i <= end  ; i++)ans += arr[i] ;

    return ans  ;

}

/////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

public static void swapArray(int[] arr , int start , int end)

{

    while(start < end)

    {

        int temp = arr[start] ;

        arr[start] = arr[end];

        arr[end] = temp;

        start++ ;end-- ;

    }

}

//////////////////////////////////////////////////////////////////////////////////

static long factorial(long a)

{

    if(a== 0L || a==1L)return 1L ;

    return a*factorial(a-1L) ;

}

///////////////////////////////////////////////////////////////////////////////

public static int[][] rotate(int[][] input){

int n =input.length;

int m = input[0].length ;

int[][] output = new int [m][n];

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

	for (int j=0;j<m; j++)

		output [j][n-1-i] = input[i][j];

return output;

}

///////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////// ////////////////////////////////////////////////

public static boolean isPowerOfTwo(long n)

{

    if(n==0)

    return false;

if(((n ) & (n-1)) == 0 ) return true ;

else return false  ;

}

/////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////

public static String reverse(String input)

{

  StringBuilder str  = new StringBuilder("") ;

    for(int i =input.length()-1 ; i >= 0  ; i-- )

    {

        str.append(input.charAt(i));

    }

return str.toString() ;

}

///////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////

public static boolean isPossibleTriangle(int a  ,int b , int c)

{

      if( a + b > c && c+b > a && a +c > b)return true  ;

      else return false  ;

}

////////////////////////////////////////////////////////////////////////////////////////////

static long xnor(long num1, long num2) {

		if (num1 < num2) {

			long temp = num1;

			num1 = num2;

			num2 = temp;

		}

		num1 = togglebit(num1);

		return num1 ^ num2;

	}

	static long togglebit(long n) {

		if (n == 0)

			return 1;

		long i = n;

		n |= n >> 1;

		n |= n >> 2;

		n |= n >> 4;

		n |= n >> 8;

		n |= n >> 16;

		return i ^ n;

	}

///////////////////////////////////////////////////////////////////////////////////////////////

public static int xorOfFirstN(int n)

{

 if( n % 4 ==0)return n ;

 else if( n % 4 == 1)return 1 ;

 else if( n % 4 == 2)return n+1 ;

 else return 0 ;

}

//////////////////////////////////////////////////////////////////////////////////////////////

public static int gcd(int a, int b )

{

if(b==0)return a ;

else return gcd(b,a%b) ;

}

public static long gcd(long a, long b )

{

if(b==0)return a ;

else return gcd(b,a%b) ;

}

////////////////////////////////////////////////////////////////////////////////////

public static int lcm(int a, int b ,int c , int d )

{

int temp = lcm(a,b , c) ;

 int ans = lcm(temp ,d ) ;

return ans  ;

}

///////////////////////////////////////////////////////////////////////////////////////////

public static int lcm(int a, int b ,int c )

{

int temp = lcm(a,b) ;

int ans =  lcm(temp ,c) ;

return ans  ;

}

////////////////////////////////////////////////////////////////////////////////////////

public static int lcm(int a , int b )

{

int gc = gcd(a,b);

return (a/gc)*b ;

}

public static long lcm(long a , long b )

{

long gc = gcd(a,b);

return (a/gc)*b;

}

///////////////////////////////////////////////////////////////////////////////////////////

static boolean isPrime(long n)

{

      if(n==1)

      {

            return false  ;

      }

      boolean ans =  true  ;

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

      {

            if(n% i ==0)

            {

                  ans = false  ;break ;

            }

      }

      return ans  ;

}

static boolean isPrime(int n)

{

      if(n==1)

      {

            return false  ;

      }

      boolean ans =  true  ;

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

      {

            if(n% i ==0)

            {

                  ans = false  ;break ;

            }

      }

      return ans  ;

}

///////////////////////////////////////////////////////////////////////////

static int sieve =  1000000 ;

static boolean[] prime =  new boolean[sieve + 1] ;

public static void sieveOfEratosthenes()

    {

        // FALSE == prime

        // TRUE ==  COMPOSITE

        // FALSE== 1

        // time complexity = 0(NlogLogN)== o(N)

        // gives prime nos bw 1 to N

        for(int i = 4; i<= sieve ; i++)

        {

            prime[i] = true  ;

            i++ ;

        }

        for(int p = 3; p*p <= sieve; p++)

        {

            if(prime[p] == false)

            {

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

                    prime[i] = true;

            }

            p++ ;

        }

    }

///////////////////////////////////////////////////////////////////////////////////

public static void sortD(int[] arr , int s  , int e)

{

      sort(arr ,s , e) ;

      int i =s ; int j = e  ;

      while( i < j)

      {

            int temp = arr[i] ;

            arr[i] =arr[j] ;

            arr[j] = temp ;

            i++ ; j-- ;

      }

      return ;

}

/////////////////////////////////////////////////////////////////////////////////////////

public static long countSubarraysSumToK(long[] arr ,long sum )

    {

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

      int n = arr.length ;

      long prefixsum = 0 ;

      long count = 0L ;

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

      {

          prefixsum  = prefixsum +  arr[i] ;

          if(sum == prefixsum)count = count+1 ;

          if(map.containsKey(prefixsum -sum))

          {

              count = count + map.get(prefixsum -sum) ;

          }

          if(map.containsKey(prefixsum ))

          {

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

          }

          else{

              map.put(prefixsum , 1L );

          }

      }

      return count  ;

    }

///////////////////////////////////////////////////////////////////////////////////////////////

// KMP ALGORITHM : TIME COMPL:O(N+M)

// FINDS THE OCCURENCES OF PATTERN AS A  SUBSTRING IN STRING

//RETURN THE ARRAYLIST OF INDEXES

// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING

public static ArrayList<Integer> kmpAlgorithm(String str , String pat)

     {

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

        int n = str.length() ;

        int m = pat.length() ;

        String q = pat + "#" + str ;

        int[] lps  =new int[n+m+1] ;

         longestPefixSuffix(lps, q,(n+m+1)) ;

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

         {

             if(lps[i] == m)

             {

                 list.add(i-2*m) ;

             }

         }

        return list ;

    }

public static void longestPefixSuffix(int[] lps ,String str , int n)

    {

        lps[0] =  0 ;

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

        {

          int l = lps[i-1] ;

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

          {

              l = lps[l-1] ;

          }

          if(str.charAt(i) == str.charAt(l))

          {

              l++ ;

          }

          lps[i] = l ;

        }

    }

///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////

 // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n

    // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1

    // or n and the no  will be coprime in nature

    //time : O(n*(log(logn)))

    public static void eulerTotientFunction(int[] arr ,int n )

    {

      for(int i = 1; i <= n  ;i++)arr[i] =i  ;

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

      {

          if(arr[i] == i)

          {

              arr[i] =i-1 ;

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

              {

                  arr[j] = (arr[j]*(i-1))/i ;

              }

          }

      }

      return  ;

    }

/////////////////////////////////////////////////////////////////////////////////////////////

public static long nCr(int n,int k)

{

    long ans=1L;

    k=k>n-k?n-k:k;

    int j=1;

    for(;j<=k;j++,n--)

    {

        if(n%j==0)

        {

            ans*=n/j;

        }else

        if(ans%j==0)

        {

            ans=ans/j*n;

        }else

        {

            ans=(ans*n)/j;

        }

    }

    return ans;

}

///////////////////////////////////////////////////////////////////////////////////////////

public static ArrayList<Integer> allFactors(int n)

{

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

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

    {

          if( n % i == 0)

          {

              if(i*i == n)

              {

                    list.add(i) ;

              }

              else{

                    list.add(i) ;

                    list.add(n/i) ;

              }

          }

    }

     return list ;

}

public static ArrayList<Long> allFactors(long n)

{

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

    for(long i = 1L; i*i <= n ;i++)

    {

          if( n % i == 0)

          {

              if(i*i == n)

              {

                    list.add(i) ;

              }

              else{

                    list.add(i) ;

                    list.add(n/i) ;

              }

          }

    }

     return list ;

}

////////////////////////////////////////////////////////////////////////////////////////////////////

  static final int MAXN = 1000001;

    static int spf[] = new int[MAXN];

    static void sieve()

    {

        spf[1] = 1;

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

            spf[i] = i;

        for (int i=4; i<MAXN; i+=2)

            spf[i] = 2;

        for (int i=3; i*i<MAXN; i++)

        {

            if (spf[i] == i)

            {

                for (int j=i*i; j<MAXN; j+=i)

                    if (spf[j]==j)

                        spf[j] = i;

            }

        }

    }

    static ArrayList<Integer> getPrimeFactorization(int x)

    {

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

        while (x != 1)

        {

            ret.add(spf[x]);

            x = x / spf[x];

        }

        return ret;

    }

 //////////////////////////////////////////////////////////////////////////////////////////////////

 //////////////////////////////////////////////////////////////////////////////////////////////////

public static void merge(int arr[], int l, int m, int r)

    {

        // Find sizes of two subarrays to be merged

        int n1 = m - l + 1;

        int n2 = r - m;

        /* Create temp arrays */

        int L[] = new int[n1];

        int R[] = new int[n2];

       //Copy data to temp arrays

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

            L[i] = arr[l + i];

        for (int j=0; j<n2; ++j)

            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays

        int i = 0, j = 0;

        // Initial index of merged subarry array

        int k = l;

        while (i < n1 && j < n2)

        {

            if (L[i] <= R[j])

            {

                arr[k] = L[i];

                i++;

            }

            else

            {

                arr[k] = R[j];

                j++;

            }

            k++;

        }

        /* Copy remaining elements of L[] if any */

        while (i < n1)

        {

            arr[k] = L[i];

            i++;

            k++;

        }

        /* Copy remaining elements of R[] if any */

        while (j < n2)

        {

            arr[k] = R[j];

            j++;

            k++;

        }

    }

    // Main function that sorts arr[l..r] using

    // merge()

  public static void sort(int arr[], int l, int r)

    {

        if (l < r)

        {

            // Find the middle point

            int m = (l+r)/2;

            // Sort first and second halves

            sort(arr, l, m);

            sort(arr , m+1, r);

            // Merge the sorted halves

            merge(arr, l, m, r);

        }

    }

public static void sort(long arr[], int l, int r)

    {

        if (l < r)

        {

            // Find the middle point

            int m = (l+r)/2;

            // Sort first and second halves

            sort(arr, l, m);

            sort(arr , m+1, r);

            // Merge the sorted halves

            merge(arr, l, m, r);

        }

    }

public static void merge(long arr[], int l, int m, int r)

    {

        // Find sizes of two subarrays to be merged

        int n1 = m - l + 1;

        int n2 = r - m;

        /* Create temp arrays */

        long L[] = new long[n1];

        long R[] = new long[n2];

        //Copy data to temp arrays

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

            L[i] = arr[l + i];

        for (int j=0; j<n2; ++j)

            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays

        int i = 0, j = 0;

        // Initial index of merged subarry array

        int k = l;

        while (i < n1 && j < n2)

        {

            if (L[i] <= R[j])

            {

                arr[k] = L[i];

                i++;

            }

            else

            {

                arr[k] = R[j];

                j++;

            }

            k++;

        }

        /* Copy remaining elements of L[] if any */

        while (i < n1)

        {

            arr[k] = L[i];

            i++;

            k++;

        }

        /* Copy remaining elements of R[] if any */

        while (j < n2)

        {

            arr[k] = R[j];

            j++;

            k++;

        }

    }

 /////////////////////////////////////////////////////////////////////////////////////////

	public static long knapsack(int[] weight,long value[],int maxWeight){

        int n=  value.length ;

	//dp[i] stores the profit with KnapSack capacity "i"

  long []dp = new long[maxWeight+1];

    //initially profit with 0 to W KnapSack capacity is 0

    Arrays.fill(dp, 0);

    // iterate through all items

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

        //traverse dp array from right to left

        for(int j = maxWeight; j >= weight[i]; j--)

            dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);

    /*above line finds out maximum of dp[j](excluding ith element value)

    and val[i] + dp[j-wt[i]] (including ith element value and the

    profit with "KnapSack capacity - ith element weight") */

    return dp[maxWeight];

	}

///////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////

// to return max sum of any subarray in given array

public static long kadanesAlgorithm(long[] arr)

{

    if(arr.length == 0)return  0 ;

      long[] dp = new long[arr.length] ;

      dp[0] = arr[0] ;

      long max =  dp[0] ;

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

      {

            if(dp[i-1] > 0)

            {

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

            }

            else{

                  dp[i] = arr[i] ;

            }

            if(dp[i] >  max)max = dp[i] ;

      }

      return max  ;

}

/////////////////////////////////////////////////////////////////////////////////////////////

public static long kadanesAlgorithm(int[] arr)

{

     if(arr.length == 0)return  0 ;

      long[] dp = new long[arr.length] ;

      dp[0] = arr[0] ;

      long max =  dp[0] ;

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

      {

            if(dp[i-1] > 0)

            {

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

            }

            else{

                  dp[i] = arr[i] ;

            }

            if(dp[i] >  max)max = dp[i] ;

      }

      return max  ;

}

///////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////

//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING

// JUST CALL generatePermutation( str,  start,  end) start :inclusive ,end : exclusive

//Function for swapping the characters at position I with character at position j

    public static String swapString(String a, int i, int j) {

        char[] b =a.toCharArray();

        char ch;

        ch = b[i];

        b[i] = b[j];

        b[j] = ch;

        return String.valueOf(b);

    }

//Function for generating different permutations of the string

    public static void generatePermutation(String str, int start, int end)

    {

        //Prints the permutations

        if (start == end-1)

            System.out.println(str);

        else

        {

            for (int i = start; i < end; i++)

            {

                //Swapping the string by fixing a character

                str = swapString(str,start,i);

                //Recursively calling function generatePermutation() for rest of the characters

                generatePermutation(str,start+1,end);

                //Backtracking and swapping the characters again.

                str = swapString(str,start,i);

            }

        }

    }

////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////

public static long factMod(long n, long mod) {

    if (n <= 1) return 1;

    long ans = 1;

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

      ans = (ans * i) % mod;

    }

    return ans;

  }

/////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////

public static long power(int a  ,int b)

    {

        //time comp : o(logn)

        long x = (long)(a) ;

         long n = (long)(b) ;

        if(n==0)return 1 ;

        if(n==1)return x;

        long ans =1L  ;

      while(n>0)

      {

          if(n % 2 ==1)

          {

              ans = ans *x ;

          }

          n = n/2L ;

          x =  x*x ;

      }

      return ans ;

    }

    public static long power(long a  ,long b)

    {

        //time comp : o(logn)

        long x = (a) ;

         long n = (b) ;

        if(n==0)return 1L ;

        if(n==1)return x;

        long ans =1L  ;

      while(n>0)

      {

          if(n % 2 ==1)

          {

              ans = ans *x ;

          }

          n = n/2L ;

          x =  x*x ;

      }

      return ans ;

    }

////////////////////////////////////////////////////////////////////////////////////////////////////

public static long powerMod(long x, long n, long mod) {

    //time comp : o(logn)

    if(n==0)return 1L ;

        if(n==1)return x;

    long ans = 1;

    while (n > 0) {

      if (n % 2 == 1) ans = (ans * x) % mod;

      x = (x * x) % mod;

      n /= 2;

    }

    return ans;

  }

//////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////

/*

lowerBound - finds largest element equal or less than value paased

upperBound - finds smallest element equal or more than value passed

if not present return -1;

*/

public static long lowerBound(long[] arr,long k)

	{

		long ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]<=k)

			{

				ans=arr[mid];

				start=mid+1;

			}

			else

			{

				end=mid-1;

			}

		}

		return ans;

	}

	public static int lowerBound(int[] arr,int k)

	{

		int ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]<=k)

			{

				ans=arr[mid];

				start=mid+1;

			}

			else

			{

				end=mid-1;

			}

		}

		return ans;

	}

	public static long upperBound(long[] arr,long k)

	{

		long ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]>=k)

			{

				ans=arr[mid];

				end=mid-1;

			}

			else

			{

				start=mid+1;

			}

		}

		return ans;

	}

	public static int upperBound(int[] arr,int k)

	{

		int ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]>=k)

			{

				ans=arr[mid];

				end=mid-1;

			}

			else

			{

				start=mid+1;

			}

		}

		return ans;

	}

//////////////////////////////////////////////////////////////////////////////////////////

public static void printArray(int[] arr , int si ,int ei)

{

    for(int i = si  ; i  <= ei ; i++)

    {

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

    }

}

public static void printArrayln(int[] arr , int si ,int ei)

{

    for(int i = si  ; i  <= ei ; i++)

    {

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

    }

    out.println() ;

}

public static void printLArray(long[] arr , int si , int ei)

{

    for(int i = si ; i  <= ei ; i++)

    {

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

    }

}

public static void printLArrayln(long[] arr , int si , int ei)

{

    for(int i = si ; i  <= ei ; i++)

    {

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

    }

    out.println() ;

}

public static void printtwodArray(int[][] ans)

{

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

    {

        for(int j  = 0 ; j <  ans[0].length ; j++)out.print(ans[i][j] +" ");

        out.println() ;

    }

    out.println() ;

}

   static long modPow(long a, long x, long p) {

    //calculates a^x mod p in logarithmic time.

    a = a % p ;

    if(a == 0)return 0L ;

    long res = 1L;

    while(x > 0) {

        if( x % 2 != 0) {

            res = (res * a) % p;

        }

        a = (a * a) % p;

        x =x/2;

    }

    return res;

}

  static long modInverse(long a, long p) {

    //calculates the modular multiplicative of a mod p.

    //(assuming p is prime).

    return modPow(a, p-2, p);

}

 static long[] factorial =  new long[1000001] ;

 static void modfac(long mod)

 {

     factorial[0]=1L ; factorial[1]=1L ;

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

     {

         factorial[i] = factorial[i-1] *(long)(i) ;

          factorial[i] = factorial[i] % mod ;

     }

 }

static long modBinomial(long n, long r, long p) {

// calculates C(n,r) mod p (assuming p is prime).

  if(n < r) return 0L ;

    long num = factorial[(int)(n)] ;

    long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) %  p ;

    long ans  = num*(modInverse(den,p)) ;

    ans = ans % p ;

    return ans  ;

}

 static void update(int val , long[] bit ,int n)

 {

     for( ; val <= n ; val += (val &(-val)) )

     {

         bit[val]++ ;

     }

 }

 static long query(int val , long[] bit , int n)

 {

     long ans = 0L;

     for( ; val >=1 ; val-=(val&(-val))  )ans += bit[val];

     return ans ;

 }

static int countSetBits(long n)

    {

        int count = 0;

        while (n > 0) {

            n = (n) & (n - 1L);

            count++;

        }

        return count;

    }

static int abs(int x)

{

    if(x < 0)x = -1*x ;

    return x ;

}

static long abs(long x)

{

    if(x < 0)x = -1L*x ;

    return x ;

}

////////////////////////////////////////////////////////////////////////////////////////////////

static void p(int val)

{

    out.print(val) ;

}

static void p()

{

    out.print(" ") ;

}

static void pln(int val)

{

    out.println(val) ;

}

static void pln()

{

    out.println() ;

}

static void p(long val)

{

    out.print(val) ;

}

static void pln(long val)

{

    out.println(val) ;

}

////////////////////////////////////////////////////////////////////////////////////////////

 // calculate total no of nos greater than or equal to key in  sorted array arr

static  int bs(int[] arr, int s ,int e  ,int key)

{

    if( s> e)return 0 ;

     int mid = (s+e)/2 ;

        if(arr[mid] <key)

        {

            return bs(arr ,mid+1,e , key) ;

        }

        else{

             return bs(arr ,s ,mid-1, key)  + e-mid+1;

        }

}

// static ArrayList<Integer>[] adj ;

// static int mod= 1000000007 ;

//////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////

public static void solve()

{

FastReader scn = new FastReader() ;

//Scanner scn = new Scanner(System.in);

//int[] store = {2 ,3, 5 , 7  ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ;

// product of first 11 prime nos is greater than 10 ^ 12;

//sieve() ;

//ArrayList<Integer> arr[] = new ArrayList[n] ;

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

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

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

// ArrayList<Integer> lista = new ArrayList<>() ;

// ArrayList<Integer> listb = new ArrayList<>() ;

//ArrayList<String> lists = new ArrayList<>() ;

HashMap<Integer,ArrayList<Pair>> map = new HashMap<>() ;

//HashMap<Long,Long> map = new HashMap<>() ;

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

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

//HashMap<String,Integer> maps = new HashMap<>() ;

//HashMap<Integer,Boolean> mapb = new HashMap<>() ;

//HashMap<Point,Integer> point = new HashMap<>() ;

 Set<Integer> set = new HashSet<>() ;

 Set<Integer> setx = new HashSet<>() ;

 Set<Integer> sety = new HashSet<>() ;

StringBuilder sb =new StringBuilder("") ;

//Collections.sort(list);

//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;

//else map.put(arr[i],1) ;

// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;

// else map.put(temp,1) ;

//int bit  =Integer.bitCount(n);

// gives total no of set bits in n;

// Arrays.sort(arr, new Comparator<Pair>() {

// 			@Override

// 			public int compare(Pair a, Pair b) {

// 				if (a.first != b.first) {

// 					return a.first - b.first; // for increasing order of first

// 				}

// 				return a.second - b.second ; //if first is same then sort on second basis

// 			}

// 		});

int testcase = 1;

 //testcase = scn.nextInt() ;

for(int testcases =1  ; testcases <= testcase ;testcases++)

{

 //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;

 //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;

 //adj = new ArrayList[n] ;

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

// {

//     adj[i] = new ArrayList<Integer>();

// }

// long n = scn.nextLong() ;

//String s = scn.next() ;

int n= scn.nextInt() ;

int[] arr= new int[n] ;

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

{

    arr[i]= scn.nextInt();

}

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

{

    int sum = 0 ;

    for(int l =r ;l>= 0 ;l--)

    {

       sum = sum + arr[l] ;

       if(map.containsKey(sum))

       {

           map.get(sum).add(new Pair(l,r)) ;

       }

       else{

           map.put(sum,new ArrayList<Pair>());

            map.get(sum).add(new Pair(l,r)) ;

       }

    }

}

 ArrayList<Pair> ans = null ;

 int bestcount = 0 ;

for(int x : map.keySet())

{

    ArrayList<Pair> curr = map.get(x) ;

    ArrayList<Pair> now = new ArrayList<Pair>() ;

    int r=-1  ;

    int count = 0 ;

    for(Pair seg : curr)

    {

      if(seg.first > r)

      {

          count++ ;

          now.add(seg) ;

          r= seg.second  ;

      }

    }

    if(count > bestcount)

    {

        ans = now ;

        bestcount = count  ;

    }

}

pln(bestcount) ;

if(bestcount >0)

{

for(Pair x :  ans)

{

    out.println((x.first+1) +" " +( x.second+1)) ;

}

}

//out.println(ans) ;

//out.println(ans+" "+in) ;

//out.println("Case #" + testcases + ": "  + ans ) ;

//out.println("@") ;

set.clear() ;

sb.delete(0 , sb.length()) ;

list.clear() ;lista.clear() ;listb.clear() ;

map.clear() ;

mapx.clear() ;

mapy.clear() ;

setx.clear() ;sety.clear() ;

} // test case  end loop

out.flush() ;

} // solve fn ends

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

{

solve() ;

}

}

 class Pair

{

  int first ;

int second  ;

   public Pair(int l , int r)

   {

       first = l ;second = r ;

   }

@Override

	public String toString() {

	String ans = "" ;

	ans  += this.first ;

	ans += " ";

	ans += this.second ;

	return ans  ;

	}

}


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

import java.io.*;

import java.util.*;

public class Main {

    static List<Integer>[] g;

    static void bfs(int u, int[] dis) {

        dis[u] = 0;

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

        q.add(u);

        while(!q.isEmpty()) {

            int v = q.peek();

            q.remove();

            for(int w: g[v])

                if(dis[w] > dis[v] + 1) {

                    dis[w] = dis[v] + 1;

                    q.add(w);

                }

        }

    }

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

        Scanner in = new Scanner(System.in);

        int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();

        g = new List[n];

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

            g[i] = new ArrayList<Integer>();

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

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

            a.add(in.nextInt() - 1);

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

            int u = in.nextInt() - 1, v = in.nextInt() - 1;

            g[u].add(v);

            g[v].add(u);

        }

        int[] d1 = new int[n];

        int[] dn = new int[n];

        Arrays.fill(d1, 100000000);

        Arrays.fill(dn, 100000000);

        bfs(0, d1);

        bfs(n - 1, dn);

        int best = 0, mx = -100000000;

        Collections.sort(a, new Comparator<Integer>() {

            @Override public int compare(Integer b, Integer c) {

                return d1[b] - dn[b] - d1[c] + dn[c];

            }

        });

        for(int e: (List<Integer>) a) {

            best = Math.max(best, mx + dn[e]);

            mx = Math.max(mx, d1[e]);

        }

        System.out.println(Math.min(best + 1, d1[n - 1]));

    }

}


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

/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static int MAX = 20000, INF = (int) 1e9;

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

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

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

        sc = new FastReader();

        precompute();

        int test = sc.nextInt();

        for (int t = 1; t <= test; t++) {

            solve();

        }

        out.close();

    }

    private static void precompute() {

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

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

                for (int k = j; k <= MAX; k += j) {

                    list.add(new int[]{i, j, k});

                }

            }

        }

    }

    private static void solve() {

        int a = sc.nextInt();

        int b = sc.nextInt();

        int c = sc.nextInt();

        int[] res = new int[]{0, 0, 0};

        int minOperations = INF;

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

            int[] curr = list.get(i);

            int operations = Math.abs(curr[0] - a) + Math.abs(curr[1] - b) + Math.abs(curr[2] - c);

            if (minOperations > operations) {

                minOperations = operations;

                res = curr;

            }

        }

        out.println(minOperations);

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

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.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 lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

public class C1316D {
    public static void main(String[] args) {
        var scanner = new BufferedScanner();
        var writer = new PrintWriter(new BufferedOutputStream(System.out));

        var n = scanner.nextInt();
        var target = new int[n + 1][n + 1];
        var blocks = new ArrayList<Integer>();
        var starts = new HashMap<Integer, List<Integer>>();
        for (int x = 1; x <= n; x++) {
            for (int y = 1; y <= n; y++) {
                var h = hash(n, x, y);
                var x1 = scanner.nextInt();
                var y1 = scanner.nextInt();
                int h1 = hash(n, x1, y1);
                target[x][y] = h1;
                if (x == x1 && y == y1) {
                    blocks.add(h1);
                } else if (x1 >= 1) {
                    starts.compute(h1, (k, v) -> {
                        if (v == null) {
                            v = new ArrayList<>();
                        }
                        v.add(h);
                        return v;
                    });
                }
            }
        }
        var ans = new char[n + 1][n + 1];
        var valid = true;
        // 最起码，所有starts的终点的终点都是自己
        for (Integer t : starts.keySet()) {
            if (t < 0) {
                valid = false;
                break;
            }
            var xy = dehash(t, n);
            if (target[xy[0]][xy[1]] != t) {
                valid = false;
                break;
            }
        }
        if (!valid) {
            writer.println("INVALID");
        } else {
            // 首先，所有的blocks要能够走到到自己的所有出发点。
            for (Integer block : blocks) {
                bfs(block, ans, n, target);
                if (!allStartsReach(block, starts, ans, n)) {
                    valid = false;
                    break;
                }
            }
            if (!valid) {
                writer.println("INVALID");
            } else {
                // 其次所有的(-1,-1)不能是孤立的。
                if (!fillInfinite(ans, n)) {
                    writer.println("INVALID");
                } else {
                    writer.println("VALID");
                    for (int x = 1; x <= n; x++) {
                        writer.println(Arrays.copyOfRange(ans[x], 1, n + 1));
                    }
                }
            }
        }

        scanner.close();
        writer.flush();
        writer.close();
    }

    private static boolean fillInfinite(char[][] ans, int n) {
        for (int x = 1; x <= n; x++) {
            for (int y = 1; y <= n; y++) {
                if (ans[x][y] == 0) {
                    var q = new LinkedList<int[]>();
                    q.add(new int[]{x, y});
                    {
                        for (int i = 0; i < 4; i++) {
                            var x1 = x + dx[i];
                            var y1 = y + dy[i];
                            if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && ans[x1][y1] == 0) {
                                q.add(new int[]{x1, y1});
                                ans[x][y] = dn[i];
                                ans[x1][y1] = dn[3 - i];
                                break;
                            }
                        }
                    }
                    if (q.size() < 2) {
                        return false;
                    }
                    while (!q.isEmpty()) {
                        var xy = q.poll();
                        for (int i = 0; i < 4; i++) {
                            var x1 = xy[0] + dx[i];
                            var y1 = xy[1] + dy[i];
                            if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && ans[x1][y1] == 0) {
                                ans[x1][y1] = dn[3 - i];
                                q.add(new int[]{x1, y1});
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    private static boolean allStartsReach(Integer block, HashMap<Integer, List<Integer>> starts, char[][] ans, int n) {
        List<Integer> ss = starts.get(block);
        if (ss == null) {
            return true;
        }
        for (Integer start : ss) {
            var xy = dehash(start, n);
            if (ans[xy[0]][xy[1]] == 0) {
                return false;
            }
        }
        return true;
    }

    static int[] dx = new int[]{1, 0, 0, -1};
    static int[] dy = new int[]{0, 1, -1, 0};
    static char[] dn = new char[]{'D', 'R', 'L', 'U'};

    private static void bfs(int block, char[][] ans, int n, int[][] target) {
        var q = new LinkedList<int[]>();
        {
            var xy = dehash(block, n);
            ans[xy[0]][xy[1]] = 'X';
            q.add(xy);
        }
        while (!q.isEmpty()) {
            var xy = q.poll();
            for (int i = 0; i < 4; i++) {
                var x1 = xy[0] + dx[i];
                var y1 = xy[1] + dy[i];
                if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && target[x1][y1] == block && ans[x1][y1] == 0) {
                    ans[x1][y1] = dn[3 - i];
                    q.add(new int[]{x1, y1});
                }
            }
        }
    }

    private static int[] dehash(int block, int n) {
        return new int[]{block / (n + 1), block % (n + 1)};
    }

    private static int hash(int n, int x, int y) {
        return x * (n + 1) + y;
    }

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

        public BufferedScanner(Reader reader) {
            br = new BufferedReader(reader);
        }

        public BufferedScanner() {
            this(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;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    static long gcd(long a, long b) {
        if (a < b) {
            return gcd(b, a);
        }
        while (b > 0) {
            long tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }

    static long inverse(long a, long m) {
        long[] ans = extgcd(a, m);
        return ans[0] == 1 ? (ans[1] + m) % m : -1;
    }

    private static long[] extgcd(long a, long m) {
        if (m == 0) {
            return new long[]{a, 1, 0};
        } else {
            long[] ans = extgcd(m, a % m);
            long tmp = ans[1];
            ans[1] = ans[2];
            ans[2] = tmp;
            ans[2] -= ans[1] * (a / m);
            return ans;
        }
    }

    private static List<Integer> primes(double upperBound) {
        var limit = (int) Math.sqrt(upperBound);
        var isComposite = new boolean[limit + 1];
        var primes = new ArrayList<Integer>();
        for (int i = 2; i <= limit; i++) {
            if (isComposite[i]) {
                continue;
            }
            primes.add(i);
            int j = i + i;
            while (j <= limit) {
                isComposite[j] = true;
                j += i;
            }
        }
        return primes;
    }

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int ttt=1;

		ttt=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

		for(int tt=0;tt<ttt;tt++) {

			int n=f.nextInt();

			char[] l=f.next().toCharArray();

			int num = n, last = 0;

			int[] ans=new int[n];

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

			{

				if (i == n - 1 || l[i] == '>')

				{

					for (int j = i; j >= last; j--)

						ans[j] = num--;

					last = i + 1;

				}

			}

			for (int i:ans) out.print(i+" ");

			out.println();

			ans=new int[n];

			num = 1;

			last = 0;

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

			{

				if (i == n - 1 || l[i] == '<')

				{

					for (int j = i; j >= last; j--)

						ans[j] = num++;

					last = i + 1;

				}

			}

			for (int i:ans) out.print(i+" ");

			out.println();

		}

		out.close();

	}

	static void sort(int[] p) {

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

        for (int i: p) q.add( i);

        Collections.sort(q);

        for (int i = 0; i < p.length; i++) p[i] = q.get(i);

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}


B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.

import java.util.Scanner;

public class Codeforces1324 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        StringBuffer sb = new StringBuffer();

        for (int i=0;i < n;++i) {
            int m = Integer.parseInt(in.nextLine());
            String[] items = in.nextLine().split(" ");
            int j = 0;
            boolean found = false;
            while (j < m - 2) {
                for (int k = m - 1; k > j + 1;--k) {
                    if (items[j].equals(items[k])) {
                        found = true;
                        break;
                    }
                }
                if (found)                         {
                    sb.append("YES").append("\n");
                    break;
                } else {
                    ++j;
                }
            }
            if (!found)  sb.append("NO").append("\n");
        }
        System.out.print(sb.substring(0, sb.length() - 1));

    }
}


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.math.BigInteger;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashMap;

import java.util.Map;

import java.util.StringTokenizer;

import java.util.function.Supplier;

import java.util.stream.Collectors;

public class cf {

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

    public static PrintWriter out;

    public static int cnt;

    //-----------MyScanner class for faster input----------

    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 boolean isPrime(int n)

{

    // Corner cases

    if (n <= 1)

        return false;

    if (n <= 3)

        return true;

    // This is checked so that we can skip

    // middle five numbers in below loop

    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;

}

    public static int reverseBits(int n)

    {

        int rev = 0;

        // traversing bits of 'n'

        // from the right

        while (n > 0)

        {

            // bitwise left shift

            // 'rev' by 1

            rev <<= 1;

            // if current bit is '1'

            if ((int)(n & 1) == 1)

                rev ^= 1;

            // bitwise right shift

            //'n' by 1

            n >>= 1;

        }

        // required number

        return rev;

    }

    public static ArrayList<String> getSequence(String str)

    {

        // If string is empty

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

            // Return an empty arraylist

            ArrayList<String> empty = new ArrayList<>();

            empty.add("");

            return empty;

        }

        // Take first character of str

        char ch = str.charAt(0);

        // Take sub-string starting from the

        // second character

        String subStr = str.substring(1);

        // Recursive call for all the sub-sequences

        // starting from the second character

        ArrayList<String> subSequences =

                              getSequence(subStr);

        // Add first character from str in the beginning

        // of every character from the sub-sequences

        // and then store it into the resultant arraylist

        ArrayList<String> res = new ArrayList<>();

        for (String val : subSequences) {

            res.add(val);

            res.add(ch + val);

        }

        return res;

    }

	public static void main(String[] args)

	{

		MyScanner sc = new MyScanner();

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

		StringBuilder sb = new StringBuilder();

		int t=sc.nextInt();

		while(t-->0)

		{

			int n=sc.nextInt();

			int m=sc.nextInt();

			long arr[]=new long[n];

			long brr[]=new long[m];

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

			{

				arr[i]=sc.nextLong();

			}

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

			{

				brr[i]=sc.nextLong();

			}

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

			Arrays.sort(brr);

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

			{

				int i1=(int) brr[i]-1;

				while(i+1<m &&brr[i+1]-brr[i]==1 )

				{

					i++;

				}

				int i2=(int)brr[i];

				if(i2>i1)

				{

					long crr[]=Arrays.copyOfRange(arr,i1, i2+1);

					Arrays.sort(crr);

					int k=0;

					for(int i3=i1;i3<=i2;i3++)

					{

						arr[i3]=crr[k];

						k++;

					}

				}

				else

				{

					long a=Math.max(arr[i1],arr[i1+1]);

					long b=Math.min(arr[i1],arr[i1+1]);

					arr[i1+1]=a;

					arr[i1]=b;

				}

			}

			long crr[]=Arrays.copyOf(arr, n);

			Arrays.sort(crr);

			if(Arrays.equals(arr,crr))

			{

				out.println("YES");

			}

			else

			{

				out.println("NO");

			}

		}

		out.close();

	}

}


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

    public static class FastWriter {

        private static final int BUF_SIZE = 1 << 13;

        private final byte[] buf = new byte[BUF_SIZE];

        private final OutputStream out;

        private int ptr = 0;

        private FastWriter() {

            out = null;

        }

        public FastWriter(OutputStream os) {

            this.out = os;

        }

        public FastWriter(String path) {

            try {

                this.out = new FileOutputStream(path);

            } catch (FileNotFoundException e) {

                throw new RuntimeException("FastWriter");

            }

        }

        public FastWriter write(byte b) {

            buf[ptr++] = b;

            if (ptr == BUF_SIZE) innerflush();

            return this;

        }

        public FastWriter write(char c) {

            return write((byte) c);

        }

        public FastWriter write(char[] s) {

            for (char c : s) {

                buf[ptr++] = (byte) c;

                if (ptr == BUF_SIZE) innerflush();

            }

            return this;

        }

        public FastWriter write(String s) {

            s.chars().forEach(c -> {

                buf[ptr++] = (byte) c;

                if (ptr == BUF_SIZE) innerflush();

            });

            return this;

        }

        private static int countDigits(int l) {

            if (l >= 1000000000) return 10;

            if (l >= 100000000) return 9;

            if (l >= 10000000) return 8;

            if (l >= 1000000) return 7;

            if (l >= 100000) return 6;

            if (l >= 10000) return 5;

            if (l >= 1000) return 4;

            if (l >= 100) return 3;

            if (l >= 10) return 2;

            return 1;

        }

        public FastWriter write(int x) {

            if (x == Integer.MIN_VALUE) {

                return write((long) x);

            }

            if (ptr + 12 >= BUF_SIZE) innerflush();

            if (x < 0) {

                write((byte) '-');

                x = -x;

            }

            int d = countDigits(x);

            for (int i = ptr + d - 1; i >= ptr; i--) {

                buf[i] = (byte) ('0' + x % 10);

                x /= 10;

            }

            ptr += d;

            return this;

        }

        private static int countDigits(long l) {

            if (l >= 1000000000000000000L) return 19;

            if (l >= 100000000000000000L) return 18;

            if (l >= 10000000000000000L) return 17;

            if (l >= 1000000000000000L) return 16;

            if (l >= 100000000000000L) return 15;

            if (l >= 10000000000000L) return 14;

            if (l >= 1000000000000L) return 13;

            if (l >= 100000000000L) return 12;

            if (l >= 10000000000L) return 11;

            if (l >= 1000000000L) return 10;

            if (l >= 100000000L) return 9;

            if (l >= 10000000L) return 8;

            if (l >= 1000000L) return 7;

            if (l >= 100000L) return 6;

            if (l >= 10000L) return 5;

            if (l >= 1000L) return 4;

            if (l >= 100L) return 3;

            if (l >= 10L) return 2;

            return 1;

        }

        public FastWriter write(long x) {

            if (x == Long.MIN_VALUE) {

                return write("" + x);

            }

            if (ptr + 21 >= BUF_SIZE) innerflush();

            if (x < 0) {

                write((byte) '-');

                x = -x;

            }

            int d = countDigits(x);

            for (int i = ptr + d - 1; i >= ptr; i--) {

                buf[i] = (byte) ('0' + x % 10);

                x /= 10;

            }

            ptr += d;

            return this;

        }

        public FastWriter write(double x, int precision) {

            if (x < 0) {

                write('-');

                x = -x;

            }

            x += Math.pow(10, -precision) / 2;

            //		if(x < 0){ x = 0; }

            write((long) x).write(".");

            x -= (long) x;

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

                x *= 10;

                write((char) ('0' + (int) x));

                x -= (int) x;

            }

            return this;

        }

        public FastWriter writeln(char c) {

            return write(c).writeln();

        }

        public FastWriter writeln(int x) {

            return write(x).writeln();

        }

        public FastWriter writeln(long x) {

            return write(x).writeln();

        }

        public FastWriter writeln(double x, int precision) {

            return write(x, precision).writeln();

        }

        public FastWriter write(int... xs) {

            boolean first = true;

            for (int x : xs) {

                if (!first) write(' ');

                first = false;

                write(x);

            }

            return this;

        }

        public FastWriter write(long... xs) {

            boolean first = true;

            for (long x : xs) {

                if (!first) write(' ');

                first = false;

                write(x);

            }

            return this;

        }

        public FastWriter writeln() {

            return write((byte) '\n');

        }

        public FastWriter writeln(int... xs) {

            return write(xs).writeln();

        }

        public FastWriter writeln(long... xs) {

            return write(xs).writeln();

        }

        public FastWriter writeln(char[] line) {

            return write(line).writeln();

        }

        public FastWriter writeln(char[]... map) {

            for (char[] line : map) write(line).writeln();

            return this;

        }

        public FastWriter writeln(String s) {

            return write(s).writeln();

        }

        private void innerflush() {

            try {

                out.write(buf, 0, ptr);

                ptr = 0;

            } catch (IOException e) {

                throw new RuntimeException("innerflush");

            }

        }

        public void flush() {

            innerflush();

            try {

                out.flush();

            } catch (IOException e) {

                throw new RuntimeException("flush");

            }

        }

        public FastWriter print(byte b) {

            return write(b);

        }

        public FastWriter print(char c) {

            return write(c);

        }

        public FastWriter print(char[] s) {

            return write(s);

        }

        public FastWriter print(String s) {

            return write(s);

        }

        public FastWriter print(int x) {

            return write(x);

        }

        public FastWriter print(long x) {

            return write(x);

        }

        public FastWriter print(double x, int precision) {

            return write(x, precision);

        }

        public FastWriter println(char c) {

            return writeln(c);

        }

        public FastWriter println(int x) {

            return writeln(x);

        }

        public FastWriter println(long x) {

            return writeln(x);

        }

        public FastWriter println(double x, int precision) {

            return writeln(x, precision);

        }

        public FastWriter print(int... xs) {

            return write(xs);

        }

        public FastWriter print(long... xs) {

            return write(xs);

        }

        public FastWriter println(int... xs) {

            return writeln(xs);

        }

        public FastWriter println(long... xs) {

            return writeln(xs);

        }

        public FastWriter println(char[] line) {

            return writeln(line);

        }

        public FastWriter println(char[]... map) {

            return writeln(map);

        }

        public FastWriter println(String s) {

            return writeln(s);

        }

        public FastWriter println() {

            return writeln();

        }

    }

    static final class InputReader {

        private final InputStream stream;

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

        private int curChar;

        private int numChars;

        public InputReader(InputStream stream) {

            this.stream = stream;

        }

        private int read() throws IOException {

            if (curChar >= numChars) {

                curChar = 0;

                numChars = stream.read(buf);

                if (numChars <= 0) {

                    return -1;

                }

            }

            return buf[curChar++];

        }

        public final int readInt() throws IOException {

            return (int) readLong();

        }

        public final long readLong() throws IOException {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

                if (c == -1) throw new IOException();

            }

            boolean negative = false;

            if (c == '-') {

                negative = true;

                c = read();

            }

            long res = 0;

            do {

                res *= 10;

                res += c - '0';

                c = read();

            } while (!isSpaceChar(c));

            return negative ? -res : res;

        }

        public final int[] readIntArray(int size) throws IOException {

            int[] array = new int[size];

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

                array[i] = readInt();

            }

            return array;

        }

        public final long[] readLongArray(int size) throws IOException {

            long[] array = new long[size];

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

                array[i] = readLong();

            }

            return array;

        }

        public final String readString() throws IOException {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            StringBuilder res = new StringBuilder();

            do {

                res.append((char) c);

                c = read();

            } while (!isSpaceChar(c));

            return res.toString();

        }

        private boolean isSpaceChar(int c) {

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

        }

    }

    static long mulmod(long a, long b,

                       long mod) {

        long res = 0; // Initialize result

        a = a % mod;

        while (b > 0) {

            // If b is odd, add 'a' to result

            if (b % 2 == 1) {

                res = (res + a) % mod;

            }

            // Multiply 'a' with 2

            a = (a * 2) % mod;

            // Divide b by 2

            b /= 2;

        }

        // Return result

        return res % mod;

    }

    static long pow(long a, long b, long MOD) {

        long x = 1, y = a;

        while (b > 0) {

            if (b % 2 == 1) {

                x = (x * y);

                if (x > MOD) x %= MOD;

            }

            y = (y * y);

            if (y > MOD) y %= MOD;

            b /= 2;

        }

        return x;

    }

    static long[] f = new long[200001];

    static long InverseEuler(long n, long MOD) {

        return pow(n, MOD - 2, MOD);

    }

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

        return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD;

    }

    static int[] h = {0, 0, -1, 1};

    static int[] v = {1, -1, 0, 0};

    public static class Pair {

        public int a;

        public int b;

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Pair pair = (Pair) o;

            return a == pair.a &&

                    b == pair.b;

        }

        @Override

        public int hashCode() {

            return Objects.hash(a, b);

        }

        public Pair(int a, int b) {

            this.a = a;

            this.b = b;

        }

    }

    static class Pair2 {

        public long cost;

        int node;

        public Pair2(long cos, int node) {

            this.cost = cos;

            this.node = node;

        }

    }

    static long compute_hash(String s) {

        int p = 31;

        int m = 1000000007;

        long hash_value = 0;

        long p_pow = 1;

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

            char c = s.charAt(i);

            hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;

            p_pow = (p_pow * p) % m;

        }

        return hash_value;

    }

    public static class SegmentTree {

        long[][] tree;

        int n;

        public SegmentTree(int[] nodes) {

            tree = new long[nodes.length * 4][2];

            n = nodes.length;

            build(0, n - 1, 0, nodes);

        }

        private void build(int l, int r, int pos, int[] nodes) {

            if (l == r) {

                tree[pos][0] = nodes[l];

                tree[pos][1] = l;

                return;

            }

            int mid = (l + r) / 2;

            build(l, mid, 2 * pos + 1, nodes);

            build(mid + 1, r, 2 * pos + 2, nodes);

            if (tree[2 * pos + 1][0] > tree[2 * pos + 2][0]) {

                tree[pos][1] = tree[2 * pos + 1][1];

            } else {

                tree[pos][1] = tree[2 * pos + 2][1];

            }

            tree[pos][0] = Math.max(tree[2 * pos + 1][0], tree[2 * pos + 2][0]);

        }

        //        public void update(int pos, int val) {

        //            updateUtil(0, n - 1, 0, pos, val);

        //        }

        public long[] get(int l, int r) {

            return getUtil(0, n - 1, 0, l, r);

        }

        private long[] getUtil(int l, int r, int pos, int ql, int qr) {

            if (ql > r || qr < l) {

                return new long[]{-1, -1};

            }

            if (l >= ql && r <= qr) {

                return tree[pos];

            }

            int mid = (l + r) / 2;

            long[] left = getUtil(l, mid, 2 * pos + 1, ql, qr);

            long[] right = getUtil(mid + 1, r, 2 * pos + 2, ql, qr);

            long choice = right[1];

            if (left[0] > right[0]) choice = left[1];

            return new long[]{Math.max(left[0], right[0]), choice};

        }

        //        private void updateUtil(int l, int r, int pos, int i, int val) {

        //            if (i < l || i > r) {

        //                return;

        //            }

        //            if (l == r) {

        //                tree[pos] = val;

        //                return;

        //            }

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

        //            updateUtil(l, mid, 2 * pos + 1, i, val);

        //            updateUtil(mid + 1, r, 2 * pos + 2, i, val);

        //            tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];

        //        }

    }

    static int counter = 0;

    static int[] rIn;

    static int[] rOut;

    static int[] lIn;

    static int[] lOut;

    private static int[] flatten;

    private static int[] lFlatten;

    static long answer = 0;

    static int VISITED = 1;

    static int VISITING = 2;

    static int[] DIRX = new int[]{0, 0, 1, -1};

    static int[] DIRY = new int[]{1, -1, 0, 0};

    public static class Pair22 {

        int num, pos;

        public Pair22(int x, int y) {

            this.num = x;

            this.pos = y;

        }

    }

    public static long sumofdig(long n) {

        long sum = 0;

        while (n > 0) {

            sum += n % 10;

            n /= 10;

        }

        return sum;

    }

    public static class DK {

        int D, K;

        public DK(int d, int k) {

            D = d;

            K = k;

        }

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            DK dk = (DK) o;

            return D == dk.D &&

                    K == dk.K;

        }

        @Override

        public int hashCode() {

            return Objects.hash(D, K);

        }

    }

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

        //https://i...content-available-to-author-only...e.com/ebRGa6

        InputReader in = new InputReader(System.in);

        FastWriter out = new FastWriter(System.out);

//

//        f[0] = 1;

//        f[1] = 1;

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

//            f[i] = f[i-1] * i;

//            f[i] %= 100000000000000007L;

//        }

        int t = 1;

        while (t-- > 0) {

            int n = in.readInt();

            List<List<Integer>> g = new ArrayList<>();

            for (int i = 0; i < n; ++i) g.add(new ArrayList<>());

            int[] cost = new int[n];

            int parent = 0;

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

                int from = i;

                int to = in.readInt();

                cost[i] = in.readInt();

                to--;

                if (to != -1) {

                    g.get(from).add(to);

                    g.get(to).add(from);

                } else {

                    parent = i;

                }

            }

            List<Integer> val = dfs(g, parent, -1, cost);

            if (val.size() != n) {

                System.out.println("NO");

            } else {

                System.out.println("YES");

                int[] ans = new int[n];

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

                    ans[val.get(i)] = i + 1;

                }

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

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

                }

            }

            out.flush();

        }

    }

    private static List<Integer> dfs(List<List<Integer>> g, int cur, int last, int[] cost) {

        List<Integer> nodes = new ArrayList<>();

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

            int ntb = g.get(cur).get(i);

            if (ntb != last) {

                nodes.addAll(dfs(g, ntb, cur, cost));

            }

        }

        List<Integer> ans = new ArrayList<>();

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

            if (cost[cur] == i) {

                ans.add(cur);

                ans.add(nodes.get(i));

            } else {

                ans.add(nodes.get(i));

            }

        }

        if (cost[cur] == nodes.size()) {

            ans.add(cur);

        }

        if (cost[cur] > nodes.size()) {

            return new ArrayList<>();

        }

        return ans;

    }

//    private static Pair22 dfss(List<LinkedHashSet<Integer>> g, int node, HashSet<Integer> vis, int[] dis, int[] dis2) {

//        if (vis.contains(node)) return new Pair22(dis[node], dis2[node], -1);

//        vis.add(node);

//        int min = dis[node];

//        for (Integer ntb : g.get(node)) {

//            if (dis[ntb] > dis[node])

//                dfss(g, ntb, vis, dis, dis2);

//            if (dis[ntb] <= dis[node]) {

//                min = Math.min(min, dis[ntb]);

//            } else {

//                min = Math.min(min, dis2[ntb]);

//            }

//        }

//        //        if (dis)

//        dis2[node] = min;

//        return new Pair22(dis[node], min, -1);

//    }

    private static int solver(int[] nums, int pos, int[] dp) {

        if (pos >= nums.length) return 0;

        if (dp[pos] != Integer.MAX_VALUE) return dp[pos];

        int min = solver(nums, pos + 2, dp) + nums[pos];

        min = Math.min(solver(nums, pos + 3, dp) + nums[pos], min);

        if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 3, dp));

        if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 4, dp));

        //        System.out.println(pos + " " + min);

        return dp[pos] = min;

    }

    static int countFreq(String pattern, String text) {

        int m = pattern.length();

        int n = text.length();

        int res = 0;

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

            int j;

            for (j = 0; j < m; j++) {

                if (text.charAt(i + j) != pattern.charAt(j)) {

                    break;

                }

            }

            if (j == m) {

                res++;

                j = 0;

            }

        }

        return res;

    }

    private static void dfsR(List<List<Integer>> g, int node, int[] v) {

        rIn[node] = counter;

        flatten[counter++] = v[node];

        for (int i = 0; i < g.get(node).size(); ++i) {

            dfsR(g, g.get(node).get(i), v);

        }

        rOut[node] = counter;

        flatten[counter++] = v[node] * -1;

    }

    private static void dfsL(List<List<Integer>> g, int node, int[] v) {

        lIn[node] = counter;

        lFlatten[counter++] = v[node];

        for (int i = 0; i < g.get(node).size(); ++i) {

            dfsL(g, g.get(node).get(i), v);

        }

        lOut[node] = counter;

        lFlatten[counter++] = v[node] * -1;

        TreeMap<String, Integer> map = new TreeMap<>();

    }

    private static void preprocess(int pos, int[][] pre, List<List<Integer>> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) {

        tin[pos] = counter++;

        traverse[depth] = pos;

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

            pre[pos][i] = traverse[depth - (1 << i)];

        }

        for (int i = 0; i < tree.get(pos).size(); ++i) {

            if (tree.get(pos).get(i) != last)

                preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout);

        }

        tout[pos] = counter++;

    }

    static long gcd(long a, long b) {

        while (b != 0) {

            long t = a;

            a = b;

            b = t % b;

        }

        return a;

    }

    static long lcm(long a, long b) {

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

    }

    static boolean submit = true;

    static void debug(String s) {

        if (!submit)

            System.out.println(s);

    }

    static void debug(int s) {

        LinkedHashSet<Integer> exist = new LinkedHashSet<>();

            /*

            4 2 3 _ 2 4 3 _

             */

    }

}


import java.io.*;

import java.util.*;

public class Main {

	static Scanner sc = new Scanner(System.in);

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

	static int n, grid[][], dx[], dy[];

	static Pair adj[][];

	static boolean valid(int r, int c) {

		return r >= 0 && r < n && c >= 0 && c < n;

	}

	static boolean dfs(int r, int c) {

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

			int nr = r + dx[i], nc = c + dy[i];

			if (valid(nr, nc) && adj[nr][nc].r == -2) {

				grid[r][c] = i;

				return true;

			}

		}

		return false;

	}

	static void dfs2(int r, int c) {

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

			int nr = r + dx[i], nc = c + dy[i];

			if (valid(nr, nc) && grid[nr][nc] == -1) {

				if (adj[nr][nc].r == adj[r][c].r && adj[nr][nc].c == adj[r][c].c) {

					grid[nr][nc] = (i + 2) % 4;

					dfs2(nr, nc);

				}

			}

		}

	}

	static void bfs(Pair p) {

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

		q.add(p);

		while (!q.isEmpty()) {

			Pair u = q.poll();

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

				int nr = u.r + dx[i], nc = u.c + dy[i];

				if (valid(nr, nc) && grid[nr][nc] == -1) {

					if (adj[nr][nc].r == adj[u.r][u.c].r && adj[nr][nc].c == adj[u.r][u.c].c) {

						grid[nr][nc] = (i + 2) % 4;

						q.add(new Pair(nr,nc));

					}

				}

			}

		}

	}

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

		n = sc.nextInt();

		grid = new int[n][n];

		adj = new Pair[n][n];

		dx = new int[] { 0, 1, 0, -1 };

		dy = new int[] { 1, 0, -1, 0 };

		for (int[] arr : grid)

			Arrays.fill(arr, -1);

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

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

				adj[i][j] = new Pair(sc.nextInt() - 1, sc.nextInt() - 1);

			}

		}

		boolean flag = true;

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

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

				if (grid[i][j] == -1) {

					if (adj[i][j].r == -2) {

						flag &= dfs(i, j);

					} else {

						if (adj[i][j].r == i && adj[i][j].c == j) {

							grid[i][j] = 4;

							bfs(new Pair(i,j));

						}

					}

				}

			}

		}

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

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

				if (grid[i][j] == -1)

					flag = false;

			}

		}

		out.println(flag ? "VALID" : "INVALID");

		if (flag) {

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

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

					int x = grid[i][j];

					if (x == 0)

						out.print("R");

					else if (x == 1)

						out.print("D");

					else if (x == 2)

						out.print("L");

					else if (x == 3)

						out.print("U");

					else

						out.print("X");

				}

				out.println();

			}

		}

		out.close();

	}

	static class Pair {

		int r, c;

		public Pair(int r, int c) {

			this.r = r;

			this.c = c;

		}

	}

}

class Scanner {

	StringTokenizer st;

	BufferedReader br;

	public Scanner(InputStream system) {

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

	}

	public Scanner(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 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 Long nextLong() throws IOException {

		return Long.parseLong(next());

	}

}