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

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

public class Main {

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

    public static void solve() {
        int n  = in.nextInt();
        char[] s = fillArray();
        int max = 0;
        int lastAngry = -1;
        for(int i = 0; i < n; i++) {
            if(s[i] == 'A') {
                lastAngry = i;
                continue;
            }

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

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

        out.print(max);
    }

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

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

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

    public static PrintWriter out;
    public static MyScanner in;

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

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

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

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

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

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

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

    }

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


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

import java.util.*;

import java.awt.PrintGraphics;

import java.io.*;

import java.math.*;

import java.sql.Array;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.SQLIntegrityConstraintViolationException;

public class Main {

	 private static class MyScanner {

	        private static final int BUF_SIZE = 2048;

	        BufferedReader br;

	        private MyScanner() {

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

	        }

	        private boolean isSpace(char c) {

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

	        }

	        String next() {

	            try {

	                StringBuilder sb = new StringBuilder();

	                int r;

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

	                if (r == -1) {

	                    return null;

	                }

	                sb.append((char) r);

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

	                    sb.append((char)r);

	                }

	                return sb.toString();

	            } catch (IOException e) {

	                e.printStackTrace();

	            }

	            return null;

	        }

	        int nextInt() {

	            return Integer.parseInt(next());

	        }

	        long nextLong() {

	            return Long.parseLong(next());

	        }

	        double nextDouble() {

	            return Double.parseDouble(next());

	        }

	    }

	  static class Reader{

			BufferedReader br;

			StringTokenizer st;

			public Reader() {

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

			}

			String next()

		    {

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

		        {

		            try

		            {

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

		            }

		            catch (IOException  e)

		            {

		                e.printStackTrace();

		            }

		        }

		        return st.nextToken();

		    }

		    int nextInt()

		    {

		        return Integer.parseInt(next());

		    }

		    long nextLong()

		    {

		        return Long.parseLong(next());

		    }

		    double nextDouble()

		    {

		        return Double.parseDouble(next());

		    }

		    String nextLine()

		    {

		        String str = "";

		        try

		        {

		            str = br.readLine();

		        }

		        catch (IOException e)

		        {

		            e.printStackTrace();

		        }

		        return str;

		    }

		}

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

	static void sort(long[] arr ) {

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

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

		 Collections.sort(al);

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

	 }

	static void sort(int[] arr ) {

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

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

		 Collections.sort(al);

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

	 }

	static void sort(char[] arr) {

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

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

		Collections.sort(al);

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

	}

	static long mod_mul(  long... a) {

		long ans = a[0]%mod;

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

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

		}

		return ans;

	}

	static long mod_sum( long... a) {

		long ans = 0;

		for(long e:a) {

			ans = (ans + e)%mod;

		}

		return ans;

	}

	 static long gcd(long a, long b)

	  {

	     if (b == 0)

	        return a;

	     return gcd(b, a % b);

	  }

	 static void print(long[] arr) {

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

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

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

	 }

	 static void print(int[] arr) {

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

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

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

	 }

	 static boolean[] prime(int num) {

			boolean[] bool = new boolean[num];

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

		         bool[i] = true;

		      }

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

		         if(bool[i] == true) {

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

		               bool[j] = false;

		            }

		         }

		      }

		      if(num >= 0) {

		    	  bool[0] = false;

		    	  bool[1] = false;

		      }

		      return bool;

		}

	 static long modInverse(long a, long m)

	    {

	        long g = gcd(a, m);

	          return   power(a, m - 2);

	    }

	   static long lcm(long a , long b) {

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

	   }

	   static int lcm(int a , int b) {

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

	   }

	 static long power(long x, long y){

		 if(y<0) return 0;

		 long m = mod;

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

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

     static class Combinations{

	    	 private long[] z;  // factorial

	    	 private long[] z1; // inverse factorial

	    	 private long[] z2; // incerse number

	    	 private long mod;

	    	  public Combinations(long N , long mod) {

	    		  this.mod = mod;

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

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

				z[0] = 1;

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

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

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

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

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

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

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

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

			}

	    	  long fac(long n) {

	    		  return z[(int)n];

	    	  }

	    	  long invrsNum(long n) {

	    		  return z2[(int)n];

	    	  }

	    	  long invrsFac(long n) {

	    		  return z1[(int)n];

	    	  }

	    	  long ncr(long N, long R)

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

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

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

	    		             % mod;

	    		    return ans;

	    		}

	      }

	      static class DisjointUnionSets {

			    int[] rank, parent;

			    int n;

			    public DisjointUnionSets(int n)

			    {

			        rank = new int[n];

			        parent = new int[n];

			        this.n = n;

			        makeSet();

			    }

			    void makeSet()

			    {

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

			            parent[i] = i;

			        }

			    }

			    int find(int x)

			    {

			        if (parent[x] != x) {

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

			        }

			        return parent[x];

			    }

			    void union(int x, int y)

			    {

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

			        if (xRoot == yRoot)

			            return;

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

			            parent[xRoot] = yRoot;

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

			            parent[yRoot] = xRoot;

			        else

			        {

			            parent[yRoot] = xRoot;

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

			        }

			    }

			}

	      static int max(int... a ) {

	    	  int max = a[0];

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

	    	  return max;

	      }

	      static long max(long... a ) {

	    	  long max = a[0];

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

	    	  return max;

	      }

	      static int min(int... a ) {

	    	  int min = a[0];

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

	    	  return min;

	      }

	      static long min(long... a ) {

	    	  long min = a[0];

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

	    	  return min;

	      }

	      static int[] KMP(String str) {

	    	  int n = str.length();

	    	  int[] kmp = new int[n];

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

	    		  int j = kmp[i-1];

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

	    			  j = kmp[j-1];

	    		  }

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

	    		  kmp[i] = j;

	    	  }

	    	  return kmp;

	      }

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

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

	      static class SparseTable{

	    		private long[][] st;

	    		SparseTable(long[] arr){

	    			int n = arr.length;

	    			st = new long[n][25];

	    			log = new int[n+2];

	    			build_log(n+1);

	    			build(arr);

	    		}

	    		private void build(long[] arr) {

	    			int n = arr.length;

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

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

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

	    					if(r>=n) break;

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

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

	    				}

	    			}

	    		}

	    		public long gcd(long a  ,long b) {

	    			if(a == 0) return b;

	    			return gcd(b%a , a);

	    		}

	    		public long query(int l ,int r) {

	    			int w = r-l+1;

	    			int power = log[w];

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

	    		}

	    		private int[] log;

	    		void build_log(int n) {

	    			log[1] = 0;

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

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

	    			}

	    		}

	    	}

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

	 	 static class SegmentTree{

			 long[] tree;

			 long[] arr;

			 int n;

			 SegmentTree(long[] arr){

				 this.n = arr.length;

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

				 this.arr = arr;

				 buildTree(0, n-1, 1);

			 }

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

					if(s == e) {

						tree[index] = arr[s];

						return;

					}

					int mid = (s+e)/2;

					buildTree( s,  mid, 2*index);

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

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

				}

			 long query(int si ,int ei) {

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

			 }

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

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

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

					int mid = (ss + se)/2;

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

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

					return gcd(left, right);

				}

			 public void update(int index , int val) {

				 arr[index] = val;

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

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

			 }

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

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

				 if(si == ei ) {

					 tree[index] = arr[id];

					 return;

				 }

				 if(si > ei) return;

				 int mid = (ei + si)/2;

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

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

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

			 }

		 }

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

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

	      static Reader sc = new Reader();

	      static int TC;

	 static StringBuilder sb = new StringBuilder();

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

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

		 int tc = 1;

		 tc = sc.nextInt();

		 TC = 0;

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

			 TC++;

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

			 TEST_CASE();

		 }

		 System.out.print(sb);

	 }

	 static void TEST_CASE() throws IOException {

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

		long tot = sum(n);

		long min = min(n , m);

		long z = (n-m);

		if(z<=m+1) {

			tot -= z;

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

			return;

		}else {

			long gaps = m+1;

			long ele = z/(m+1);

			long ext = z%(m+1);

			long g1 = m+1-ext;

			long eleOfGap1 = ele;

			long g2 = ext;

			long eleOfGap2 = ele+1;

			long sub1 = sum(eleOfGap1) * g1;

			long sub2 = sum(eleOfGap2) * g2;

			tot -= sub1;

			tot -= sub2;

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

		}

	 }

	 static long sum(long n) {

		 long sum = 0 ;

		 sum += n*(n+1);

		 return sum/2;

	 }

	}

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

/**

  R -> 1

  B -> 1

  k -> 2

 */


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

import java.util.Arrays;

import java.util.Scanner;

public class sol {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while (t-- > 0) {

			int n = sc.nextInt();

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

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

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

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

			}

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

			StringBuilder sb = new StringBuilder();

			boolean ok = true;

			int x = 0, y = 0;

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

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

					ok = false;

					break;

				}

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

					sb.append("R");

					x++;

				}

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

					sb.append("U");

					y++;

				}

			}

			if (ok) {

				System.out.println("YES");

				System.out.println(sb);

			} else {

				System.out.println("NO");

			}

		}

	}

}


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

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

import com.sun.source.tree.ArrayAccessTree;

import javax.swing.*;

import java.beans.IntrospectionException;

import java.math.BigInteger;

import java.util.*;

import java.io.*;

public class Main {

    static class pair implements Comparable<pair> {

        long a = 0;

        long b = 0;

        // int cnt;

        pair(long b, long a) {

            this.a = b;

            this.b = a;

            // cnt = x;

        }

        @Override

        public int compareTo(pair o) {

            if(this.a != o.a)

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

            else

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

        }

        public boolean equals(Object o) {

            if (o instanceof pair) {

                pair p = (pair) o;

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

            }

            return false;

        }

        public int hashCode() {

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

        }

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine().trim();

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

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

        }

        public void prlong(Object object) throws IOException {

            bw.append("" + object);

        }

        public void prlongln(Object object) throws IOException {

            prlong(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

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

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    //HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS

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

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

//        int b = 0;

//        long h = 1;

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

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

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

//            if(b<=k){

//                set.add(h);

//            }

//        }

//    }

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

    //dsu

    static int[] par, rank;

    public static void dsu(int n) {

        par = new int[n];

        rank = new int[n];

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

            par[i] = i;

            rank[i] = 1;

        }

    }

    static int find(int u) {

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

    }

    static void union(int u, int v) {

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

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

            par[b] = a;

            rank[a] += rank[b];

        }

    }

    static void disunion(int u, int v) {

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

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

            par[a] = -1;

        }

    }

    static class Calc_nCr {

        private final long[] fact;

        private final long[] invfact;

        private final int p;

        Calc_nCr(int n, int prime) {

            fact = new long[n + 5];

            invfact = new long[n + 5];

            p = prime;

            fact[0] = 1;

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

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

            }

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

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

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

            }

        }

        private long nCr(int n, int r) {

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

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

        }

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

            long result = 1;

            while (b > 0) {

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

                    result = (result * a) % mod;

                }

                a = (a * a) % mod;

                b >>= 1;

            }

            return result;

        }

    }

    static void sort(long[] a ) {

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

        for(long i: a) {

            l.add(i);

        }

        Collections.sort(l);

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

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

        }

    }

    public static void main(String[] args) {

        try {

            FastReader in = new FastReader();

            FastWriter out = new FastWriter();

//            int mx=10000000;

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

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

//                isPrime[i] = true;

//            }

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

//                primeDiv[i]=i;

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

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

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

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

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

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

//                        }

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

//                    }

//                }

//            }

//            System.out.println(

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

            int testCases=in.nextInt();

//            int n =in.nextInt();

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

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

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

//

//

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

//            Collections.sort(ans);

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

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

            int mod =1000000007;

            fl:

            while (testCases-- > 0) {

                int n =in.nextInt();

                String s =in.next();

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

                int min =100000000;

                int a=-1;

                int b =-1;

                int x =0;

                int y =0;

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

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

                {

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

                        y++;

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

                        y--;

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

                        x--;

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

                        x++;

                    pair p =new pair(x,y);

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

                    if(map.containsKey(p))

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

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

                        if(len<min)

                        {

                            min=len;

                            a=map.get(p)+1;

                            b=i;

                        }

                    }

                    map.put(p,i);

                }

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

{

    System.out.println(-1);

    continue fl;

}

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

            }

            out.close();

        } catch (Exception e) {

            return;

        }

    }

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

        double len = 0;

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

            if(child == par)

                continue;

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

        }

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

        if(len == 0) // leaf node

            return 0;

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

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

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

    }

    static long comb(int r, int n)

    {

        long result;

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

        return result;

    }

    static long factorial(int n) {

        int c;

        long result = 1;

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

            result = result*c;

        return result;

    }

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

//        String temp = str + '/';

//        str = reverse(str);

//        temp += str;

        String temp =str;

        int n = temp.length();

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

        {

            int len = lps[i - 1];

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

                    temp.charAt(i))

            {

                len = lps[len - 1];

            }

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

            {

                len++;

            }

            lps[i] = len;

        }

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

    }

    static String reverse(String input)

    {

        char[] a = input.toCharArray();

        int l, r = a.length - 1;

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

        {

            char temp = a[l];

            a[l] = a[r];

            a[r] = temp;

        }

        return String.valueOf(a);

    }

}

/*

 *

 *　　┏┓　　　┏┓+ +

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

 *　┃　　　　　　　┃

 *　┃　　　━　　　┃ ++ + + +

 *   ████━████+

 *  ◥██◤　◥██◤ +

 *　┃　　　┻　　　┃

 *　┃　　　　　　　┃ + +

 *　┗━┓　　　┏━┛

 *　　　┃　　┃      JACKS PET FROM ANOTHER WORLD

 *　　　┃　　┃

 *　　　┃　 　 ┗━━━┓

 *　　　┃ 　　　　　　 ┣┓-------

 *　　  ┃ 　　　　　 　┏┛-------

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

 *　　　　┃┫┫　┃┫┫

 *　　　　┗┻┛　┗┻┛+ + + +

 */

//RULES

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

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

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

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


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

import java.io.*;

import java.util.*;

import java.util.function.BinaryOperator;

import java.util.stream.Collectors;

public class Main {

    private final static long mod = 1000000007;

    private final static int MAXN = 1000001;

    private static long power(long x, long y, long m) {

        long temp;

        if (y == 0)

            return 1;

        temp = power(x, y / 2, m);

        temp = (temp * temp) % m;

        if (y % 2 == 0)

            return temp;

        else

            return ((x % m) * temp) % m;

    }

    private static long power(long x, long y) {

        return power(x, y, mod);

    }

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

        if (b == 0) return a;

        return gcd(b, a % b);

    }

    static int nextPowerOf2(int a) {

        return 1 << nextLog2(a);

    }

    static int nextLog2(int a) {

        return (a == 0 ? 0 : 32 - Integer.numberOfLeadingZeros(a - 1));

    }

    private static long modInverse(long a, long m) {

        long m0 = m;

        long y = 0, x = 1;

        if (m == 1)

            return 0;

        while (a > 1) {

            long q = a / m;

            long t = m;

            m = a % m;

            a = t;

            t = y;

            y = x - q * y;

            x = t;

        }

        if (x < 0)

            x += m0;

        return x;

    }

    private static int[] getLogArr(int n) {

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

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

            arr[i] = (int) (Math.log(i) / Math.log(2) + 1e-10);

        }

        return arr;

    }

    private static int log[] = getLogArr(MAXN);

    private static int getLRSpt(int st[][], int L, int R, BinaryOperator<Integer> binaryOperator) {

        int j = log[R - L + 1];

        return binaryOperator.apply(st[L][j], st[R - (1 << j) + 1][j]);

    }

    private static int[][] getSparseTable(int array[], BinaryOperator<Integer> binaryOperator) {

        int k = log[array.length + 1] + 1;

        int st[][] = new int[array.length + 1][k + 1];

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

            st[i][0] = array[i];

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

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

                st[i][j] = binaryOperator.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);

            }

        }

        return st;

    }

    private static int[][] getSparseTable(List<Integer> list, BinaryOperator<Integer> binaryOperator) {

        int n=list.size();

        int k = log[n + 1] + 1;

        int st[][] = new int[n + 1][k + 1];

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

            st[i][0] = list.get(i);

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

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

                st[i][j] = binaryOperator.apply(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);

            }

        }

        return st;

    }

    static class Subset {

        int parent;

        int rank;

        @Override

        public String toString() {

            return "" + parent;

        }

    }

    static int find(Subset[] subsets, int i) {

        if (subsets[i].parent != i)

            subsets[i].parent = find(subsets, subsets[i].parent);

        return subsets[i].parent;

    }

    static void union(Subset[] Subsets, int x, int y) {

        int xroot = find(Subsets, x);

        int yroot = find(Subsets, y);

        if (Subsets[xroot].rank < Subsets[yroot].rank)

            Subsets[xroot].parent = yroot;

        else if (Subsets[yroot].rank < Subsets[xroot].rank)

            Subsets[yroot].parent = xroot;

        else {

            Subsets[xroot].parent = yroot;

            Subsets[yroot].rank++;

        }

    }

    private static int maxx(Integer... a) {

        return Collections.max(Arrays.asList(a));

    }

    private static int minn(Integer... a) {

        return Collections.min(Arrays.asList(a));

    }

    private static long maxx(Long... a) {

        return Collections.max(Arrays.asList(a));

    }

    private static long minn(Long... a) {

        return Collections.min(Arrays.asList(a));

    }

    private static class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {

        T a;

        U b;

        public Pair(T a, U b) {

            this.a = a;

            this.b = 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.equals(pair.a) &&

                    b.equals(pair.b);

        }

        @Override

        public int hashCode() {

            return Objects.hash(a, b);

        }

        @Override

        public String toString() {

            return "(" + a +

                    "," + b +

                    ')';

        }

        @Override

        public int compareTo(Pair<T, U> o) {

            return (this.a.equals(o.a) ? this.b.equals(o.b) ? 0 : this.b.compareTo(o.b) : this.a.compareTo(o.a));

        }

    }

    public static int upperBound(List<Integer> list, int value) {

        int low = 0;

        int high = list.size();

        while (low < high) {

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

            if (value >= list.get(mid)) {

                low = mid + 1;

            } else {

                high = mid;

            }

        }

        return low;

    }

    private static int[] getLPSArray(String pattern) {

        int i, j, n = pattern.length();

        int[] lps = new int[pattern.length()];

        lps[0] = 0;

        for (i = 1, j = 0; i < n; ) {

            if (pattern.charAt(i) == pattern.charAt(j)) {

                lps[i++] = ++j;

            } else if (j > 0) {

                j = lps[j - 1];

            } else {

                lps[i++] = 0;

            }

        }

        return lps;

    }

    private static List<Integer> findPattern(String text, String pattern) {

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

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

            return matchedIndexes;

        }

        int[] lps = getLPSArray(pattern);

        int i = 0, j = 0, n = text.length(), m = pattern.length();

        while (i < n) {

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

                i++;

                j++;

            }

            if (j == m) {

                matchedIndexes.add(i - j);

                j = lps[j - 1];

            }

            if (i < n && text.charAt(i) != pattern.charAt(j)) {

                if (j > 0) {

                    j = lps[j - 1];

                } else {

                    i++;

                }

            }

        }

        return matchedIndexes;

    }

    private static Set<Long> getDivisors(long n) {

        Set<Long> divisors = new HashSet<>();

        divisors.add(1L);

        divisors.add(n);

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

            if (n % i == 0) {

                divisors.add(i);

                divisors.add(n / i);

            }

        }

        return divisors;

    }

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

        return (Math.max(a, b) / gcd(a, b)) * Math.min(a, b);

    }

    static long fac[];

    static long ifac[];

    private static void preCompute(int n) {

        fac = new long[n + 1];

        ifac = new long[n + 1];

        fac[0] = ifac[0] = fac[1] = ifac[1] = 1;

        int i;

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

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

            ifac[i] = (power(i, mod - 2) * ifac[i - 1]) % mod;

        }

    }

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

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

        if (r > n) return 1;

        return (fac[n] * ((ifac[r] * ifac[n - r]) % mod)) % mod;

    }

    static int getSum(int BITree[], int index) {

        int sum = 0;

        index = index + 1;

        while (index > 0) {

            sum+=BITree[index];

            index -= index & (-index);

        }

        return sum;

    }

    public static void updateBIT(int BITree[], int index, int val) {

        index = index + 1;

        while (index <= BITree.length - 1) {

            BITree[index] += val;

            index += index & (-index);

        }

    }

    static int[] constructBITree(int n) {

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

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

            BITree[i] = 0;

        return BITree;

    }

    private static int upperBound(int a[], int l, int r, int x) {

        if (l > r) return -1;

        if (l == r) {

            if (a[l] <= x) {

                return -1;

            } else {

                return a[l];

            }

        }

        int m = (l + r) / 2;

        if (a[m] <= x) {

            return upperBound(a, m + 1, r, x);

        } else {

            return upperBound(a, l, m, x);

        }

    }

    private static void mul(long A[][], long B[][]) {

        int i, j, k, n = A.length;

        long C[][] = new long[n][n];

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

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

                for (k = 0; k < n; k++) {

                    C[i][j] = (C[i][j] + (A[i][k] * B[k][j]) % mod) % mod;

                }

            }

        }

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

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

                A[i][j] = C[i][j];

            }

        }

    }

    private static void power(long A[][], long base[][], long n) {

        if (n < 2) {

            return;

        }

        power(A, base, n / 2);

        mul(A, A);

        if (n % 2 == 1) {

            mul(A, base);

        }

    }

    static void reverse(int a[], int l, int r) {

        while (l < r) {

            int t = a[l];

            a[l] = a[r];

            a[r] = t;

            l++;

            r--;

        }

    }

    static void reverse(long a[], int l, int r) {

        while (l < r) {

            long t = a[l];

            a[l] = a[r];

            a[r] = t;

            l++;

            r--;

        }

    }

    public void rotate(int[] nums, int k) {

        k = k % nums.length;

        reverse(nums, 0, nums.length - k - 1);

        reverse(nums, nums.length - k, nums.length - 1);

        reverse(nums, 0, nums.length - 1);

    }

    private static boolean isSorted(int a[]) {

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

            if (a[i] > a[i + 1]) return false;

        }

        return true;

    }

    public static int[] getNGE(int arr[]) {

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

        int n = arr.length;

        int nge[] = new int[n];

        s.push(0);

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

            while (!s.isEmpty() && arr[s.peek()] <= arr[i]) {

                nge[s.peek()] = i;

                s.pop();

            }

            s.push(i);

        }

        while (!s.isEmpty()) {

            nge[s.peek()] = n;

            s.pop();

        }

        return nge;

    }

    public static int[] getPSE(int arr[]) {

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

        int n = arr.length;

        int pse[] = new int[n];

        s.push(n-1);

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

            while (!s.isEmpty() && arr[s.peek()] > arr[i]) {

                pse[s.peek()] = i;

                s.pop();

            }

            s.push(i);

        }

        while (!s.isEmpty()) {

            pse[s.peek()] = -1;

            s.pop();

        }

        return pse;

    }

    public static int[] getNSE(int arr[]) {

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

        int n = arr.length;

        int nse[] = new int[n];

        s.push(0);

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

            while (!s.isEmpty() && arr[s.peek()] > arr[i]) {

                nse[s.peek()] = i;

                s.pop();

            }

            s.push(i);

        }

        while (!s.isEmpty()) {

            nse[s.peek()] = n;

            s.pop();

        }

        return nse;

    }

    public int maximumScore(int[] nums, int k) {

        int pse[]=getPSE(nums);

        int nse[]=getNSE(nums);

        int ans=0;

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

            int p=pse[i];

            int n=nse[i];

            if(p<k&&n>k){

                ans=Math.max(ans,(n-p-1)*nums[i]);

            }

        }

        return ans;

    }

    public int validSubarraySize(int[] nums, int threshold) {

        int nse[]=getNSE(nums);

        int pse[]=getPSE(nums);

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

            int len=nse[i]-pse[i]-1;

            if(nums[i]>threshold/len) {

                return len;

            }

        }

        return -1;

    }

    private static boolean isPal(String s){

        for(int i=0,j=s.length()-1;i<j;i++,j--){

            if(s.charAt(i)!=s.charAt(j))return false;

        }

        return true;

    }

    private static int[] getSuffixArray(String s) {

        int n=s.length();

        int su[][]=new int[n][3];

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

            su[i]=new int[]{i, s.charAt(i)-'$', 0};

        }

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

            su[i][2]=(i+1<n?su[i+1][1]:-1);

        }

        Arrays.sort(su, (a,b)->a[1]==b[1]?a[2]-b[2]:a[1]-b[1]);

        int ind[]=new int[n];

        for(int l=4;l<2*n;l*=2){

            int rank=0,prev=su[0][1];

            su[0][1]=0;

            ind[su[0][0]]=0;

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

                if(su[i][1]==prev&&su[i][2]==su[i-1][2]){

                    su[i][1]=rank;

                } else {

                    prev=su[i][1];

                    su[i][1]=++rank;

                }

                ind[su[i][1]]=1;

            }

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

                int np=su[i][1]+l/2;

                su[i][2]=(np<n?su[ind[np]][1]:-1);

            }

            Arrays.sort(su, (a,b)->a[1]==b[1]?a[2]-b[2]:a[1]-b[1]);

        }

        int suf[]=new int[n];

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

            suf[i]=su[i][0];

        }

        return suf;

    }

    private static Set<Long> getPrimeFactors(long n){

        Set<Long>pfSet=new HashSet<>();

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

            while(n%i==0){

                pfSet.add(i);

                n/=i;

            }

        }

        if(n>1){

            pfSet.add(n);

        }

        return pfSet;

    }

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

        long START_TIME = System.currentTimeMillis();

        try (FastReader in = new FastReader();

             FastWriter out = new FastWriter()) {

            int n, t, i, j, f, k, m, ti, tidx, gm, g, l,r,q;

            for (t = in.nextInt(), tidx = 1; tidx <= t; tidx++)

            {

                long x = 0, y = 0, z = 0, sum = 0, bhc = 0, ans = 0;

                //out.print(String.format("Case #%d: ", tidx));

                x=in.nextLong();

                y=in.nextLong();

                z=gcd(x,y);

                y/=z;

                Set<Long>pf=getPrimeFactors(y);

                for(long p:pf){

                    y=(y/p)*(p-1);

                }

                out.println(y);

            }

            /*if (args.length > 0 && "ex_time".equals(args[0])) {

                out.print("\nTime taken: ");

                out.println(System.currentTimeMillis() - START_TIME);

            }*/

            out.commit();

        }

    }

    public static class FastReader implements Closeable {

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

        private StringTokenizer st;

        String next() {

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

                try {

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

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        @Override

        public void close() throws IOException {

            br.close();

        }

        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;

        }

        int[] nextIntArr(int n) {

            int[] arr = new int[n];

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

                arr[i] = nextInt();

            }

            return arr;

        }

        Integer[] nextIntegerArr(int n) {

            Integer[] arr = new Integer[n];

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

                arr[i] = nextInt();

            }

            return arr;

        }

        double[] nextDoubleArr(int n) {

            double[] arr = new double[n];

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

                arr[i] = nextDouble();

            }

            return arr;

        }

        long[] nextLongArr(int n) {

            long[] arr = new long[n];

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

                arr[i] = nextLong();

            }

            return arr;

        }

        List<Long> nextLongList(int n) {

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

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

                retList.add(nextLong());

            }

            return retList;

        }

        String[] nextStrArr(int n) {

            String[] arr = new String[n];

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

                arr[i] = next();

            }

            return arr;

        }

        int[][] nextIntArr2(int n, int m) {

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

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

                arr[i] = nextIntArr(m);

            }

            return arr;

        }

        long[][] nextLongArr2(int n, int m) {

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

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

                arr[i] = nextLongArr(m);

            }

            return arr;

        }

    }

    public static class FastWriter implements Closeable {

        BufferedWriter bw;

        StringBuilder sb = new StringBuilder();

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

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

        public FastWriter() {

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

        }

        <T> void commit() throws IOException {

            bw.write(sb.toString());

            bw.flush();

            sb = new StringBuilder();

        }

        public <T> void print(T obj) throws IOException {

            sb.append(obj.toString());

            //commit();

        }

        public void println() throws IOException {

            print("\n");

        }

        public <T> void println(T obj) throws IOException {

            print(obj.toString() + "\n");

        }

        <T> void printArrLn(T[] arr) throws IOException {

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

                print(arr[i] + " ");

            }

            println(arr[arr.length - 1]);

        }

        <T> void printArr2(T[][] arr) throws IOException {

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

                for (int i = 0; i < arr[j].length - 1; i++) {

                    print(arr[j][i] + " ");

                }

                println(arr[j][arr[j].length - 1]);

            }

        }

        <T> void printColl(Collection<T> coll) throws IOException {

            List<String> stringList = coll.stream().map(e -> ""+e).collect(Collectors.toList());

            println(String.join(" ", stringList));

        }

        void printCharN(char c, int n) throws IOException {

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

                print(c);

            }

        }

        void printIntArr(int []arr) throws IOException {

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

                print(arr[i] + " ");

            }

            println(arr[arr.length - 1]);

        }

        void printIntArr2(int[][] arr) throws IOException {

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

                for (int i = 0; i < arr[j].length - 1; i++) {

                    print(arr[j][i] + " ");

                }

                println(arr[j][arr[j].length - 1]);

            }

        }

        @Override

        public void close() throws IOException {

            bw.close();

        }

    }

}


C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.

import java.io.*;
import java.sql.Array;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        var fastScanner = new FastScanner();
        int n = fastScanner.nextInt();
        for (int i=0; i<n; i++) {
            var s = fastScanner.nextLine();
            var list = new ArrayList<Integer>();
            list.add(0);
            for (int j=0; j<s.length(); j++) {
                if(s.charAt(j) == 'R') {
                    list.add(j+1);
                }
            }
            list.add(s.length()+1);
            int mx = 0;
            for (int j=1; j<list.size(); j++) {
                mx = Math.max(mx, list.get(j) - list.get(j-1));
            }
            System.out.println(mx);
        }
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

    }
}


C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4
OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0
2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2
NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.

/*

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

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

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

        sc = new FastReader();

        int test = sc.nextInt();

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

        int m = sc.nextInt();

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

        int[] freq = new int[n];

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

            int val = sc.nextInt();

            freq[val - 1]++;

        }

        freq[n - 1]++;

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

            freq[i] += freq[i + 1];

        }

        int[] res = new int[26];

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

            res[s[i] - 'a'] += freq[i];

        }

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

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

        }

        out.println();

    }

    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;

        }

    }

}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

import java.util.List;

import java.util.ArrayList;

public class Solution {

    static Reader input = new Reader();

    static int n;

    static List<Integer>[] adjacents;

    static int[] parent, height, deep;

    static int start = 0, end = 0, v = 0;

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

        n = input.nextInt();

        adjacents = new List[n];

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

        int u, v;

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

            u = input.nextInt()-1;

            v = input.nextInt()-1;

            adjacents[u].add(v);

            adjacents[v].add(u);

        }

        parent = new int[n];

        height = new int[n];

        deep = new int[n];

        dfs(0, -1);

        dfs(0);

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

        setPath(start, end, -1, path);

        boolean[] inPath = new boolean[n];

        for(int node : path) inPath[node] = true;

        int[] t = null;

        for(int node : path) {

            int[] temp = test(node, -1, inPath);

            if(temp[0] == start || temp[0] == end) continue;

            if(t == null || temp[1] > t[1]) {

                t = temp;

            }

        }

        StringBuilder output = new StringBuilder();

        int x = t[1] + path.size()-1;

        output.append(x);

        output.append("\n");

        output.append(start+1);

        output.append(" ");

        output.append(end+1);

        output.append(" ");

        output.append(t[0]+1);

        System.out.print(output);

    }

    static int[] test(int node, int p, boolean[] inPath) {

        int[] result = new int[]{node, 0};

        for(int adjacent : adjacents[node]) {

            if(adjacent != p && !inPath[adjacent]) {

                int[] temp = test(adjacent, node, inPath);

                if(temp[1] > result[1]) {

                    result = temp;

                }

            }

        }

        if(p != -1) {

            ++result[1];

        }

        return result;

    }

    static boolean setPath(int node, int dist, int p, List<Integer> path) {

        if(node == dist) {

            path.add(node);

            return true;

        }

        for(int adjacent : adjacents[node]) {

            if(adjacent != p) {

                if(setPath(adjacent, dist, node, path)) {

                    path.add(node);

                    return true;

                }

            }

        }

        return false;

    }

    static void dfs(int node) {

        int max1 = -1, max2 = -1;

        for(int adjacent : adjacents[node]) {

            if(adjacent != parent[node]) {

                if(max1 == -1 || height[adjacent] > height[max1]) {

                    max2 = max1;

                    max1 = adjacent;

                } else if(max2 == -1 || height[adjacent] > height[max2]) {

                    max2 = adjacent;

                }

                dfs(adjacent);

            }

        }

        if(max1 != -1 && max2 != -1) {

            if(height[max1]+height[max2]+1 > v) {

                v = height[max1]+height[max2]+1;

                start = deep[max1];

                end = deep[max2];

            }

        } else if(max1 != -1) {

            if(height[max1]+1 > v) {

                v = height[max1]+1;

                start = deep[max1];

                end = node;

            }

        } else if(max2 != -1) {

            if(height[max2]+1 > v) {

                v = height[max2]+1;

                start = deep[max2]+1;

                end = node;

            }

        }

    }

    static void dfs(int node, int p) {

        parent[node] = p;

        int h = 0;

        int d = node;

        for(int adjacent : adjacents[node]) {

            if(adjacent != p) {

                dfs(adjacent, node);

                if(height[adjacent] > h) {

                    h = height[adjacent];

                    d = deep[adjacent];

                }

            }

        }

        height[node] = h+1;

        deep[node] = d;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

                string = new StringTokenizer(bufferedReader.readLine());

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

/*

    Author : Akshat Jindal

    from NIT Jalandhar , Punjab , India

    JAI MATA DI

 */

import java.util.*;

import javax.swing.text.Segment;

import java.io.*;

import java.math.*;

import java.sql.Array;

public class Main {

	  static class Scanner{

			BufferedReader br;

			StringTokenizer st;

			public Scanner() {

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

			}

			String next()

		    {

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

		        {

		            try

		            {

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

		            }

		            catch (IOException  e)

		            {

		                e.printStackTrace();

		            }

		        }

		        return st.nextToken();

		    }

		    int nextInt()

		    {

		        return Integer.parseInt(next());

		    }

		    long nextLong()

		    {

		        return Long.parseLong(next());

		    }

		    double nextDouble()

		    {

		        return Double.parseDouble(next());

		    }

		    String nextLine()

		    {

		        String str = "";

		        try

		        {

		            str = br.readLine();

		        }

		        catch (IOException e)

		        {

		            e.printStackTrace();

		        }

		        return str;

		    }

		}

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

	static void sort(long[] arr ) {

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

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

		 Collections.sort(al);

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

	 }

	static void sort(int[] arr ) {

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

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

		 Collections.sort(al);

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

	 }

	static void sort(char[] arr) {

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

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

		Collections.sort(al);

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

	}

	static void rvrs(int[] arr) {

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

		while(i>=j) {

			int temp = arr[i];

			arr[i] = arr[j];

			arr[j] = temp;

			i++;

			j--;

		}

	}

	static void rvrs(long[] arr) {

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

		while(i>=j) {

			long temp = arr[i];

			arr[i] = arr[j];

			arr[j] = temp;

			i++;

			j--;

		}

	}

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

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

	}

	 static long gcd(long a, long b)

	  {

	     if (b == 0)

	        return a;

	     return gcd(b, a % b);

	  }

	 static boolean[] prime(int num) {

			boolean[] bool = new boolean[num];

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

		         bool[i] = true;

		      }

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

		         if(bool[i] == true) {

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

		               bool[j] = false;

		            }

		         }

		      }

		      if(num >= 0) {

		    	  bool[0] = false;

		    	  bool[1] = false;

		      }

		      return bool;

		}

	 static long modInverse(long a, long m)

	    {

	        long g = gcd(a, m);

	          return   power(a, m - 2, m);

	    }

	 static long power(long x, long y, long m){

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

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

     static class Combinations{

	    	 private long[] z;

	    	 private long[] z1;

	    	 private long[] z2;

	    	  public Combinations(long N , long mod) {

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

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

				z[0] = 1;

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

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

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

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

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

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

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

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

			}

	    	  long fac(long n) {

	    		  return z[(int)n];

	    	  }

	    	  long invrsNum(long n) {

	    		  return z2[(int)n];

	    	  }

	    	  long invrsFac(long n) {

	    		  return invrsFac((int)n);

	    	  }

	    	  long ncr(long N, long R, long mod)

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

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

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

	    		             % mod;

	    		    return ans;

	    		}

	      }

	      static class DisjointUnionSets {

			    int[] rank, parent;

			    int n;

			    public DisjointUnionSets(int n)

			    {

			        rank = new int[n];

			        parent = new int[n];

			        this.n = n;

			        makeSet();

			    }

			    void makeSet()

			    {

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

			            parent[i] = i;

			        }

			    }

			    int find(int x)

			    {

			        if (parent[x] != x) {

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

			        }

			        return parent[x];

			    }

			    void union(int x, int y)

			    {

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

			        if (xRoot == yRoot)

			            return;

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

			            parent[xRoot] = yRoot;

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

			            parent[yRoot] = xRoot;

			        else

			        {

			            parent[yRoot] = xRoot;

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

			        }

			    }

			}

	      static int[] KMP(String str) {

	    	  int n = str.length();

	    	  int[] kmp = new int[n];

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

	    		  int j = kmp[i-1];

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

	    			  j = kmp[j-1];

	    		  }

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

	    		  kmp[i] = j;

	    	  }

	    	  return kmp;

	      }

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

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

	      static class SparseTable{

	    		private long[][] st;

	    		SparseTable(long[] arr){

	    			int n = arr.length;

	    			st = new long[n][25];

	    			log = new int[n+2];

	    			build_log(n+1);

	    			build(arr);

	    		}

	    		private void build(long[] arr) {

	    			int n = arr.length;

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

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

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

	    					if(r>=n) break;

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

	    					else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );

	    				}

	    			}

	    		}

	    		public long gcd(long a  ,long b) {

	    			if(a == 0) return b;

	    			return gcd(b%a , a);

	    		}

	    		public long query(int l ,int r) {

	    			int w = r-l+1;

	    			int power = log[w];

	    			return Math.min(st[l][power],st[r - (1<<power) + 1][power]);

	    		}

	    		private int[] log;

	    		void build_log(int n) {

	    			log[1] = 0;

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

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

	    			}

	    		}

	    	}

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

/**

	 	 static class SegmentTree{

			 long[] tree;

			 long[] arr;

			 int n;

			 SegmentTree(long[] arr){

				 this.n = arr.length;

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

				 this.arr = arr;

				 buildTree(0, n-1, 1);

			 }

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

					if(s == e) {

						tree[index] = arr[s];

						return;

					}

					int mid = (s+e)/2;

					buildTree( s,  mid, 2*index);

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

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

				}

			 long query(int si ,int ei) {

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

			 }

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

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

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

					int mid = (ss + se)/2;

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

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

					return Math.min(left, right);

				}

			 public void update(int index , int val) {

				 arr[index] = val;

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

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

			 }

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

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

				 if(si == ei ) {

					 tree[index] = arr[id];

					 return;

				 }

				 if(si > ei) return;

				 int mid = (ei + si)/2;

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

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

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

			 }

		 }

		 */

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

	      static Scanner sc = new Scanner();

	 static StringBuilder sb = new StringBuilder();

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

		 int tc = 1;

//		  tc = sc.nextInt();

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

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

			 TEST_CASE();

		 }

		 System.out.println(sb);

	 }

	 static void TEST_CASE() {

		 String str = sc.next();

		 int n = str.length();

		 int[] dp[] = new int[n+1][26];

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

			 char cc = str.charAt(i-1);

			 dp[i][cc-'a']++;

			 for(int j = 0 ; j<26 ; j++) dp[i][j] += dp[i-1][j];

		 }

		 int q = sc.nextInt();

		 while(q-- > 0) {

			 int l = sc.nextInt() , r = sc.nextInt();

			 int c = 0;

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

				 if(dp[r][i]-dp[l-1][i] > 0) c++;

			 }

			 if(c>2 || l == r || str.charAt(l-1) != str.charAt(r-1)) {

				 sb.append("YES\n");

			 }else {

				 sb.append("NO\n");

			 }

		 }

	 }

}

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

/**

	abb - > bab - > bba

	abc - > cba

	abcba -> abbca -> aabbc	 || a -> a , a -> b , a -> c

 	abbb -> bb

 	dbccbba

 */


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

import java.util.*;

public class A {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

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

            String tar = "";

            int q = in.nextInt();

            while (q!=0){

                if(q%2==0){

                    tar+="1";

                    q-=2;

                }else{

                    tar+="7";

                    q-=3;

                }

            }

            System.out.println(tar);

        }

    }

}