import java.util.*;

import javax.print.DocFlavor.INPUT_STREAM;

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] = Math.max(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.max(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 h = sc.nextLong();

		 int n = sc.nextInt();

		 long[] arr = new long[n];

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

			 arr[i] = sc.nextLong();

		 long[] pre = new long[n];

		 pre[0] = arr[0];

		 if(arr[0]+h<=0) {

			 sb.append("1\n");

			 return;

		 }

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

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

			 if(pre[i]+h<=0) {

				 sb.append(i+1).append("\n");

				 return;

			 }

		 }

		 if(pre[n-1]>=0) {

			 sb.append("-1\n");

			 return;

		 }

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

		 long ans = Long.MAX_VALUE;

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

			 long nh = h+pre[i];

			 long r = nh/(-pre[n-1]);

			 if(nh%(-pre[n-1])!=0) r++;

//			 System.out.println(nh +" - "+(r*n+i+1));

			 ans = min(ans , r*n+i+1);

		 }

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

	 }

	}

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

/**

 */


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

import java.util.Scanner;

import java.util.Arrays;

import java.util.HashSet;

import java.util.Iterator;

import java.util.HashMap;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Random;

import java.util.LinkedList;

import java.util.TreeSet;

import java.util.PriorityQueue;

import java.util.Deque;

public class Solution{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        int test_cases = sc.nextInt();

        outer : for(int h=0;h<test_cases;h++){

            //scan the input

            int n = sc.nextInt();

            String s = sc.next();

            String ans = "";

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

                if(((s.charAt(i)-'0') %2 )==1){

                    ans+=s.charAt(i);

                }

                if(ans.length()==2){

                    break;

                }

            }

            if(ans.length()!=2){

                System.out.println(-1);

            }

            else{

                System.out.println(ans);

            }

        }

        sc.close();

    }

    public static boolean check_sorted(long a[]){

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

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

                return true;

            }

        }

        return false;

    }

    public static void scan_string_array(String s[] , int n, Scanner sc){

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

            s[i] = sc.next();

        }

    }

    public static void swap_elements(int a[], int s_index, int e_index){

        int temp = a[s_index];

        a[s_index] = a[e_index];

        a[e_index] = temp;

    }

    public static void scan_array_long(long a[], int n, Scanner sc){

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

            a[i] = sc.nextLong();

        }

    }

    public static void scan_array(int a[], int n, Scanner sc){

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

            a[i] = sc.nextInt();

        }

    }

    public static void print_array(int a[]){

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

            if(i==a.length-1){

                System.out.println(a[i]);

                return;

            }

            System.out.print(a[i]);

        }

    }

    public static long sum_array(long a[]){

        long sum = 0;

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

            sum+=a[i];

        }

        return sum;

    }

    public static boolean perfect_square(double num){

        boolean isSq = false;

        double b = Math.sqrt(num);

        double c = Math.sqrt(num) - Math.floor(b);

        if(c==0){

            isSq=true;

        }

        return isSq;

    }

    public static boolean ispalindrome(String s){

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

        while(i<=j){

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

                return false;

            }

            i++;

            j--;

        }

        return true;

    }

    public static boolean ispowerOftwo(int n){

        if(n>0 && (int)(n & (n-1))==0){

            return true;

        }

        else{

            return false;

        }

    }

    public static int calculate_gcd(int x,int y){

        int gcd = 1;

        if(x%y==0){

            return y;

        }

        else if(y%x==0){

            return x;

        }

        else{

            for(int i=2;i<=x && i<=y;i++){

                if(x%i==0 && y%i==0){

                    gcd = i;

                }

            }

            return gcd;

        }

    }

    public static long calculate_factorial(long x){

        long ans = 1;

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

            ans*=i;

        }

        return ans;

    }

    public static void swap(int a[], int b[], int index_a, int index_b){

        int temp = a[index_a];

        a[index_a] = b[index_b];

        b[index_b] = temp;

    }

    public static int find_maximum(int a[]){

        int max = Integer.MIN_VALUE;

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

            max = Math.max(a[i], max);

        }

        return max;

    }

    public static int find_minimum(int a[]){

        int min = Integer.MAX_VALUE;

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

            min = Math.min(a[i], min);

        }

        return min;

    }

    public static void ruffleSort(int[] a) {

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

        Random random = new Random();

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

            int oi=random.nextInt(n);

            int temp=a[oi];

            a[oi]=a[i];

            a[i]=temp;

        }

        Arrays.sort(a);

    }

    public static int sum_of_digits(int n){

        int s =0;

        while(n!=0){

            s+=n%10;

            n/=10;

        }

        return s;

    }

    public static int[] mergeSort(int[] array) {

        if (array.length <= 1) {

            return array;

        }

        int midpoint = array.length / 2;

        int[] left = new int[midpoint];

        int[] right;

        if (array.length % 2 == 0) {

            right = new int[midpoint];

        } else {

            right = new int[midpoint + 1];

        }

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

            left[i] = array[i];

        }

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

            right[i] = array[i + midpoint];

        }

        int[] result = new int[array.length];

        left = mergeSort(left);

        right = mergeSort(right);

        result = merge(left, right);

        return result;

    }

    public static int[] merge(int[] left, int[] right) {

        int[] result = new int[left.length + right.length];

        int leftPointer = 0, rightPointer = 0, resultPointer = 0;

        while (leftPointer < left.length || rightPointer < right.length) {

            if (leftPointer < left.length && rightPointer < right.length) {

                if (left[leftPointer] < right[rightPointer]) {

                    result[resultPointer++] = left[leftPointer++];

                } else {

                    result[resultPointer++] = right[rightPointer++];

                }

            } else if (leftPointer < left.length) {

                result[resultPointer++] = left[leftPointer++];

            } else {

                result[resultPointer++] = right[rightPointer++];

            }

        }

        return result;

    }

}


C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class Main {

  static final int ALPHABET_SIZE = 26;

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int T = sc.nextInt();

    for (int tc = 0; tc < T; ++tc) {

      String s = sc.next();

      System.out.println(solve(s));

    }

    sc.close();

  }

  static String solve(String s) {

    @SuppressWarnings("unchecked")

    Set<Integer>[] adjSets = new Set[ALPHABET_SIZE];

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

      adjSets[i] = new HashSet<>();

    }

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

      int index1 = s.charAt(i) - 'a';

      int index2 = s.charAt(i + 1) - 'a';

      adjSets[index1].add(index2);

      adjSets[index2].add(index1);

    }

    StringBuilder layout =

        new StringBuilder(

            IntStream.range(0, adjSets.length)

                .filter(i -> adjSets[i].isEmpty())

                .mapToObj(i -> String.valueOf((char) (i + 'a')))

                .collect(Collectors.joining()));

    boolean[] visited = new boolean[adjSets.length];

    int[] begins = IntStream.range(0, adjSets.length).filter(i -> adjSets[i].size() == 1).toArray();

    for (int begin : begins) {

      if (!visited[begin]) {

        visited[begin] = true;

        layout.append((char) (begin + 'a'));

        int current = begin;

        while (!adjSets[current].isEmpty()) {

          int next = adjSets[current].iterator().next();

          adjSets[next].remove(current);

          current = next;

          if (visited[current]) {

            return "NO";

          }

          visited[current] = true;

          layout.append((char) (current + 'a'));

        }

      }

    }

    return (layout.length() == ALPHABET_SIZE) ? String.format("YES\n%s", layout) : "NO";

  }

}


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

import java.io.*;

import java.util.*;

public class CF1305B extends PrintWriter {

	CF1305B() { super(System.out, true); }

	Scanner sc = new Scanner(System.in);

	public static void main(String[] $) {

		CF1305B o = new CF1305B(); o.main(); o.flush();

	}

	void main() {

		byte[] cc = sc.next().getBytes();

		int n = cc.length;

		int[] ii = new int[n];

		int k = 0;

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

			while (i < n && cc[i] != '(')

				i++;

			while (j >= 0 && cc[j] != ')')

				j--;

			if (i < j) {

				ii[k] = i;

				ii[n - 1 - k] = j;

				k++;

			}

		}

		if (k == 0) {

			println(0);

			return;

		}

		println(1);

		println(k * 2);

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

			print(ii[h] + 1 + " ");

		for (int h = n - k; h < n; h++)

			print(ii[h] + 1 + " ");

		println();

	}

}


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.util.*;

import java.lang.*;

public class Y

{

	public int[][][] abc;

	public int[][] up;

    public static void main(String[] args)

    {

        Y ob=new Y();

		Scanner sc=new Scanner(System.in);

		int N=sc.nextInt();

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

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

		{

			AA.add(new ArrayList<Integer>());

		}

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

		{

			int U=sc.nextInt();

			int V=sc.nextInt();

			U=U-1;

			V=V-1;

			AA.get(U).add(V);

			AA.get(V).add(U);

		}

		ob.solve(AA);

    }

	void solve(ArrayList<ArrayList<Integer>> AA)

	{

		abc=new int[AA.size()][3][2];

		int d=fill(AA,0,-1);

		up=new int[AA.size()][2];

		up[0][0]=0;

		up[0][1]=0;

		int u=upfill(AA,0,-1);

		show(AA);

	}

	void show(ArrayList<ArrayList<Integer>> AA)

	{

		int m=0;

		int a=0;

		int b=0;

		int c=0;

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

		{

			/*

			System.out.println();

			System.out.println("curr -> "+i);

			System.out.println("up.D -> "+up[i][0]+" , up.P -> "+up[i][1]);

			System.out.println("D0.D -> "+abc[i][0][0]+" , D0.P -> "+abc[i][0][1]);

			System.out.println("D1.D -> "+abc[i][1][0]+" , D1.P -> "+abc[i][1][1]);

			System.out.println("D2.D -> "+abc[i][2][0]+" , D2.P -> "+abc[i][2][1]);

			*/

			int upp=up[i][1];

			int d0p=abc[i][0][1];

			int d1p=abc[i][1][1];

			int d2p=abc[i][2][1];

			if(m<(abc[i][0][0]+abc[i][1][0]+up[i][0]) && (upp!=d0p && d0p!=d1p && d1p!=upp))

			{

				m=(abc[i][0][0]+abc[i][1][0]+up[i][0]);

				a=abc[i][0][1];

				b=abc[i][1][1];

				c=up[i][1];

			}

			if(m<(abc[i][0][0]+abc[i][1][0]+abc[i][2][0]) && (d2p!=d0p && d0p!=d1p && d1p!=d2p))

			{

				m=(abc[i][0][0]+abc[i][1][0]+abc[i][2][0]);

				a=abc[i][0][1];

				b=abc[i][1][1];

				c=abc[i][2][1];

			}

		}

		System.out.println(m);

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

	}

	int fill(ArrayList<ArrayList<Integer>> AA,int curr,int parent)

	{

		abc[curr][0][0]=abc[curr][1][0]=abc[curr][2][0]=0;

		abc[curr][0][1]=abc[curr][1][1]=abc[curr][2][1]=curr;

		if(AA.get(curr).size()==1 && AA.get(curr).get(0)==parent)

		{

			return 0;

		}

		PriorityQueue<Point> pq=new PriorityQueue<Point>(new PC());

		for(int i=0;i<AA.get(curr).size();i++)

		{

			int now=AA.get(curr).get(i);

			if(now==parent)

			{

				continue;

			}

			fill(AA,now,curr);

			if(pq.size()<3)

			{

				pq.add(new Point(abc[now][0][0],abc[now][0][1]));

			}

			else if(pq.size()==3 && pq.peek().D<abc[now][0][0])

			{

				pq.poll();

				pq.add(new Point(abc[now][0][0],abc[now][0][1]));

			}

		}

		int j=0;

		while(0<pq.size())

		{

			j=pq.size();

			j=j-1;

			Point P=pq.poll();

			abc[curr][j][0]=P.D+1;

			abc[curr][j][1]=P.P;

		}

		return abc[curr][0][0];

	}

	int upfill(ArrayList<ArrayList<Integer>> AA,int curr,int parent)

	{

		int[][] DD=new int[3][2];

		DD[0][0]=up[curr][0];

		DD[0][1]=up[curr][1];

		DD[1][0]=abc[curr][0][0];

		DD[1][1]=abc[curr][0][1];

		DD[2][0]=abc[curr][1][0];

		DD[2][1]=abc[curr][1][1];

		for(int i=0;i<AA.get(curr).size();i++)

		{

			int next=AA.get(curr).get(i);

			if(next==parent)

			{

				continue;

			}

			int MD=DD[0][0];

			int MP=DD[0][1];

			if(abc[next][0][1]!=DD[1][1] && MD<DD[1][0])

			{

				MD=DD[1][0];

				MP=DD[1][1];

			}

			if(abc[next][0][1]!=DD[2][1] && MD<DD[2][0])

			{

				MD=DD[2][0];

				MP=DD[2][1];

			}

			up[next][0]=MD+1;

			up[next][1]=MP;

			upfill(AA,next,curr);

		}

		return DD[0][0];

	}

	public class Point

	{

		int D;

		int P;

		Point(int d,int p)

		{

			D=d;

			P=p;

		}

	}

	public class PC implements Comparator<Point>

	{

		public int compare(Point P1,Point P2)

		{

			return P1.D-P2.D;

		}

	}

}


C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

import java.util.*;
import java.io.*;

public class Practice {

	static boolean multipleTC = false;
	final static int mod = 1000000007;
	final static int mod2 = 998244353;
	final double E = 2.7182818284590452354;
	final double PI = 3.14159265358979323846;
	int MAX = 10000005;

	void pre() throws Exception {
	}

	// All the best
	void solve(int TC) throws Exception {
		int n = ni(), arr[] = readArr(n);
		long max = 0;
		int res[] = new int[n];
		for (int i = 0; i < n; i++) {
			int cur[] = calc(arr, n, i);
			long sum = sum(cur);
			if (max < sum) {
				res = cur;
				max = sum;
			}
		}
		StringBuilder ans = new StringBuilder();
		for (int i = 0; i < n; i++) {
			ans.append(res[i] + " ");
		}
		pn(ans);
	}

	private int[] calc(int[] arr, int n, int peek) {
		int res[] = new int[n];
		res[peek] = arr[peek];
		for (int i = peek - 1; i >= 0; i--) {
			if (arr[i] > res[i + 1]) {
				res[i] = res[i + 1];
			} else {
				res[i] = arr[i];
			}
		}
		for (int i = peek + 1; i < n; i++) {
			if (arr[i] > res[i - 1]) {
				res[i] = res[i - 1];
			} else {
				res[i] = arr[i];
			}
		}
		return res;
	}

	int cur;

	int[] readArr(int n) throws Exception {
		int arr[] = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = ni();
		}
		return arr;
	}

	void sort(int arr[], int left, int right) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = left; i <= right; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = left; i <= right; i++)
			arr[i] = list.get(i - left);
	}

	void sort(int arr[]) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < arr.length; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = 0; i < arr.length; i++)
			arr[i] = list.get(i);
	}

	public long max(long... arr) {
		long max = arr[0];
		for (long itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public int max(int... arr) {
		int max = arr[0];
		for (int itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public long min(long... arr) {
		long min = arr[0];
		for (long itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public int min(int... arr) {
		int min = arr[0];
		for (int itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public long sum(long... arr) {
		long sum = 0;
		for (long itr : arr)
			sum += itr;
		return sum;
	}

	public long sum(int... arr) {
		long sum = 0;
		for (int itr : arr)
			sum += itr;
		return sum;
	}

	String bin(long n) {
		return Long.toBinaryString(n);
	}

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

	static int bitCount(int x) {
		return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
	}

	static void dbg(Object... o) {
		System.err.println(Arrays.deepToString(o));
	}

	int bit(long n) {
		return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
	}

	int abs(int a) {
		return (a < 0) ? -a : a;
	}

	long abs(long a) {
		return (a < 0) ? -a : a;
	}

	void p(Object o) {
		out.print(o);
	}

	void pn(Object o) {
		out.println(o);
	}

	void pni(Object o) {
		out.println(o);
		out.flush();
	}

	String n() throws Exception {
		return in.next();
	}

	String nln() throws Exception {
		return in.nextLine();
	}

	int ni() throws Exception {
		return Integer.parseInt(in.next());
	}

	long nl() throws Exception {
		return Long.parseLong(in.next());
	}

	double nd() throws Exception {
		return Double.parseDouble(in.next());
	}

	public static void main(String[] args) throws Exception {
		new Practice().run();
	}

	FastReader in;
	PrintWriter out;

	void run() throws Exception {
		in = new FastReader();
		out = new PrintWriter(System.out);
		int T = (multipleTC) ? ni() : 1;
		pre();
		for (int t = 1; t <= T; t++)
			solve(t);
		out.flush();
		out.close();
	}

	class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		public FastReader(String s) throws Exception {
			br = new BufferedReader(new FileReader(s));
		}

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

		String nextLine() throws Exception {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				throw new Exception(e.toString());
			}
			return str;
		}
	}
}


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

import java.io.BufferedOutputStream;

import java.io.Closeable;

import java.io.DataInputStream;

import java.io.Flushable;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.AbstractMap;

import java.util.Arrays;

import java.util.Comparator;

import java.util.InputMismatchException;

import java.util.Map;

import java.util.TreeMap;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

	static class TaskAdapter implements Runnable {

		@Override

		public void run() {

			long startTime = System.currentTimeMillis();

			InputStream inputStream = System.in;

			OutputStream outputStream = System.out;

			FastReader in = new FastReader(inputStream);

			Output out = new Output(outputStream);

			ARecommendations solver = new ARecommendations();

			solver.solve(1, in, out);

			out.close();

			System.err.println(System.currentTimeMillis()-startTime+"ms");

		}

	}

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

		Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);

		thread.start();

		thread.join();

	}

	static class ARecommendations {

		public ARecommendations() {

		}

		public void solve(int kase, InputReader in, Output pw) {

			int n = in.nextInt();

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

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

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

					arr[i][j] = in.nextInt();

				}

			}

			Arrays.sort(arr, Comparator.comparingInt(o -> o[0]));

			TreeMap<Integer, Integer> tm = new TreeMap<>();

			long ans = 0, sum = 0, cnt = 0;

			int i = 0, cur = -1;

			while(i<n||!tm.isEmpty()) {

				if(tm.isEmpty()) {

					cur = arr[i][0];

				}

				for(; i<n&&arr[i][0]==cur; i++) {

					Utilities.add(tm, arr[i][1]);

					sum += arr[i][1];

				}

				sum -= tm.lastKey();

				Utilities.remove(tm, tm.lastKey());

				ans += sum;

				cur++;

			}

			;

			pw.println(ans);

		}

	}

	static class Utilities {

		public static <K, V> V getOrDefault(Map<? extends K, ? extends V> map, K key, V value) {

			V ret = map.get(key);

			if(ret==null) {

				return value;

			}

			return ret;

		}

		public static <T> void add(Map<? super T, Integer> map, T key) {

			map.put(key, getOrDefault(map, key, 0)+1);

		}

		public static <T> void remove(Map<? super T, Integer> map, T key) {

			int cnt = getOrDefault(map, key, 1)-1;

			if(cnt>0) {

				map.put(key, cnt);

			}else {

				map.remove(key);

			}

		}

	}

	static class Output implements Closeable, Flushable {

		public StringBuilder sb;

		public OutputStream os;

		public int BUFFER_SIZE;

		public String lineSeparator;

		public Output(OutputStream os) {

			this(os, 1<<16);

		}

		public Output(OutputStream os, int bs) {

			BUFFER_SIZE = bs;

			sb = new StringBuilder(BUFFER_SIZE);

			this.os = new BufferedOutputStream(os, 1<<17);

			lineSeparator = System.lineSeparator();

		}

		public void println(long l) {

			println(String.valueOf(l));

		}

		public void println(String s) {

			sb.append(s);

			println();

		}

		public void println() {

			sb.append(lineSeparator);

		}

		private void flushToBuffer() {

			try {

				os.write(sb.toString().getBytes());

			}catch(IOException e) {

				e.printStackTrace();

			}

			sb = new StringBuilder(BUFFER_SIZE);

		}

		public void flush() {

			try {

				flushToBuffer();

				os.flush();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

		public void close() {

			flush();

			try {

				os.close();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

	}

	static class FastReader implements InputReader {

		final private int BUFFER_SIZE = 1<<16;

		private DataInputStream din;

		private byte[] buffer;

		private int bufferPointer;

		private int bytesRead;

		public FastReader(InputStream is) {

			din = new DataInputStream(is);

			buffer = new byte[BUFFER_SIZE];

			bufferPointer = bytesRead = 0;

		}

		public int nextInt() {

			int ret = 0;

			byte c = skipToDigit();

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

			if(neg) {

				c = read();

			}

			do {

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

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

			if(neg) {

				return -ret;

			}

			return ret;

		}

		private boolean isDigit(byte b) {

			return b>='0'&&b<='9';

		}

		private byte skipToDigit() {

			byte ret;

			while(!isDigit(ret = read())&&ret!='-') ;

			return ret;

		}

		private void fillBuffer() {

			try {

				bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);

			}catch(IOException e) {

				e.printStackTrace();

				throw new InputMismatchException();

			}

			if(bytesRead==-1) {

				buffer[0] = -1;

			}

		}

		private byte read() {

			if(bytesRead==-1) {

				throw new InputMismatchException();

			}else if(bufferPointer==bytesRead) {

				fillBuffer();

			}

			return buffer[bufferPointer++];

		}

	}

	static interface InputReader {

		int nextInt();

	}

}


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

import java.util.*;
import java.io.*;

public class B1301 {
    final boolean DEBUG = true;

    final int INF = Integer.MAX_VALUE;
    final long LINF = Long.MAX_VALUE;

    FastScanner sc;
    PrintWriter out;

    int n;
    int[] a;
    ArrayList<Integer> inds;

    void solve() throws Exception {
        n = sc.nextInt();
        inds = new ArrayList<Integer>();
        a = new int[n];

        for (int i = 0; i < n; i++) {
            int x = sc.nextInt();

            if (x == -1)    inds.add(i);
            else            a[i] = x;
        }

        int lo = -1;
        int hi = 1_000_000_000;

        while (hi - lo > 1) {
            int mid = (lo + hi) / 2;

            if (calc(mid) < calc(mid+1)) {
                hi = mid;
            } else {
                lo = mid;
            }
        }

        out.println(calc(lo+1) + " " + (lo+1));
    }

    int calc(int k) {
        for (var i: inds)
            a[i] = k;

        int m = -INF;

        for (int i = 0; i < n-1; i++)
            m = Math.max(m, Math.abs(a[i] - a[i+1]));

        return m;
    }

    void run() throws Exception {
        Locale.setDefault(Locale.US);
        sc = new FastScanner(System.in);
        out = new PrintWriter(System.out);

        int t = sc.nextInt();
        for (; t > 0; t--) {
            solve();
        }

        out.close();
        sc.close();
    }

    void log(Object... objs) {
        if (!DEBUG)
            return;

        var sb = new StringBuilder();
        for (var x: objs)
            sb.append(x.toString()).append(" ");

        out.println(sb);
    }

    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream in) throws Exception {
        	br = new BufferedReader(new InputStreamReader(in));
        }

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

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

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

        float nextFloat() {
        	return Float.parseFloat(next());
        }

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

        String nextLine() {
            String line = "";
            try {
                line = br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return line;
        }

        void close() throws Exception {
        	br.close();
        }
    }

    public static void main(String[] arg) throws Exception {
        new B1301().run();
    }
}


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.

// import static java.lang.System.out;

import static java.lang.Math.*;

import java.util.*;

import javax.naming.ContextNotEmptyException;

import javax.swing.ImageIcon;

import javax.swing.table.TableStringConverter;

import javax.swing.text.DefaultStyledDocument.ElementSpec;

import java.io.*;

import java.math.*;

import java.rmi.ConnectIOException;

public class Main {

    static FastReader sc;

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

    static Tree tree;

    static PrintWriter out, err;

    static int imax = Integer.MAX_VALUE;

    static int imin = Integer.MIN_VALUE;

    static long lmax = Long.MAX_VALUE;

    static long lmin = Long.MIN_VALUE;

    static double dmax = Double.MAX_VALUE;

    static double dmin = Double.MIN_VALUE;

    private static void solve() throws IOException {

        int n=sc.nextInt();

        int m=sc.nextInt();

        String s=sc.next();

        int[] arr=readIntArray(m);

        sort(arr);

        int[] res=new int[26];

        int ind=0;

        int tm=m;

        m++;

        boolean prev=false;

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

            // debug(i);

            char ch=s.charAt(i);

            int cur=-1;

            if(ind<tm){

                cur=arr[ind]-1;

            }

            if(!prev)res[ch-'a']+=m;

            if(cur==i){

                m--;

                ind++;

                if(ind<tm){

                    cur=arr[ind]-1;

                    if(cur==i){

                        i--;

                        prev=true;

                        continue;

                    }

                }

                prev=false;

            }

        }

        for(int c:res)out.print(c+" ");

        out.println();

        // debug(res);

    }

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

        initializeIO();

        out = new PrintWriter(System.out);

        err = new PrintWriter(System.err);

        sc = new FastReader();

        long startTimeProg = System.currentTimeMillis();

        long endTimeProg;

        int testCase = 1;

        testCase = sc.nextInt();

        while (testCase-- != 0) {

            solve();

        }

        endTimeProg = System.currentTimeMillis();

        debug("[finished : " + (endTimeProg - startTimeProg) + ".ms ]");

        out.flush();

        err.flush();

        // System.out.println(String.format("%.9f", max));

    }

    private static class Pair {

        int first = 0;

        int sec = 0;

        int[] arr;

        char ch;

        String s;

        Map<Integer, Integer> map;

        Pair(int first, int sec) {

            this.first = first;

            this.sec = sec;

        }

        Pair(int[] arr) {

            this.map = new HashMap<>();

            for (int x : arr)

                this.map.put(x, map.getOrDefault(x, 0) + 1);

            this.arr = arr;

        }

        Pair(char ch, int first) {

            this.ch = ch;

            this.first = first;

        }

        Pair(String s, int first) {

            this.s = s;

            this.first = first;

        }

    }

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

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

        // res.add(n);

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

            if (n % i == 0) {

                res.add(i);

                if (n / i != i) {

                    res.add(n / i);

                }

            }

        }

        return res;

    }

    // geometrics

    private static double areaOftriangle(double x1, double y1, double x2, double y2, double x3, double y3) {

        double[] mid_point = midOfaLine(x1, y1, x2, y2);

        // debug(Arrays.toString(mid_point)+" "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+"

        // "+y3);

        double height = distanceBetweenPoints(mid_point[0], mid_point[1], x3, y3);

        double wight = distanceBetweenPoints(x1, y1, x2, y2);

        // debug(height+" "+wight);

        return (height * wight) / 2;

    }

    private static double distanceBetweenPoints(double x1, double y1, double x2, double y2) {

        double x = x2 - x1;

        double y = y2 - y1;

        return (Math.pow(x, 2) + Math.pow(y, 2));

    }

    private static double[] midOfaLine(double x1, double y1, double x2, double y2) {

        double[] mid = new double[2];

        mid[0] = (x1 + x2) / 2;

        mid[1] = (y1 + y2) / 2;

        return mid;

    }

    /* Function to calculate x raised to the power y in O(logn) */

    static long power(long x, long y) {

        long temp;

        if (y == 0)

            return 1l;

        temp = power(x, y / 2);

        if (y % 2 == 0)

            return (temp * temp);

        else

            return (x * temp * temp);

    }

    private static StringBuilder reverseString(String s) {

        StringBuilder sb = new StringBuilder(s);

        int l = 0, r = sb.length() - 1;

        while (l <= r) {

            char ch = sb.charAt(l);

            sb.setCharAt(l, sb.charAt(r));

            sb.setCharAt(r, ch);

            l++;

            r--;

        }

        return sb;

    }

    private static void swap(List<Integer> li, int i, int j) {

        int t = li.get(i);

        li.set(i, li.get(j));

        li.set(j, t);

    }

    private static void swap(int[] arr, int i, int j) {

        int t = arr[i];

        arr[i] = arr[j];

        arr[j] = t;

    }

    static int lcm(int a, int b) {

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

    }

    static long lcm(long a, long b) {

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

    }

    private static boolean isPallindrome(String s, int l, int r) {

        while (l < r) {

            if (s.charAt(l) != s.charAt(r))

                return false;

            l++;

            r--;

        }

        return true;

    }

    private static StringBuilder removeLeadingZero(StringBuilder sb) {

        int i = 0;

        while (i < sb.length() && sb.charAt(i) == '0')

            i++;

        // debug("remove "+i);

        if (i == sb.length())

            return new StringBuilder();

        return new StringBuilder(sb.substring(i, sb.length()));

    }

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

        int n = arr.length;

        int m = arr[0].length;

        int i, j;

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

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

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

            }

            out.println();

        }

    }

    private static StringBuilder removeEndingZero(StringBuilder sb) {

        int i = sb.length() - 1;

        while (i >= 0 && sb.charAt(i) == '0')

            i--;

        if (i < 0)

            return new StringBuilder();

        return new StringBuilder(sb.substring(0, i + 1));

    }

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

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

            err.println(Arrays.toString(arr[i]));

        }

    }

    private static void debug(long[][] arr) {

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

            err.println(Arrays.toString(arr[i]));

        }

    }

    private static void debug(List<int[]> arr) {

        for (int[] a : arr) {

            err.println(Arrays.toString(a));

        }

    }

    private static void debug(float[][] arr) {

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

            err.println(Arrays.toString(arr[i]));

        }

    }

    private static void debug(double[][] arr) {

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

            err.println(Arrays.toString(arr[i]));

        }

    }

    private static void debug(boolean[][] arr) {

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

            err.println(Arrays.toString(arr[i]));

        }

    }

    // private static void print() throws IOException {

    // out.println(s);

    // }

    private static void debug(String s) throws IOException {

        err.println(s);

    }

    private static void print(double s) throws IOException {

        out.println(s);

    }

    private static void print(float s) throws IOException {

        out.println(s);

    }

    private static void print(long s) throws IOException {

        out.println(s);

    }

    private static void print(int s) throws IOException {

        out.println(s);

    }

    private static void debug(double s) throws IOException {

        err.println(s);

    }

    private static void debug(float s) throws IOException {

        err.println(s);

    }

    private static void debug(long s) {

        err.println(s);

    }

    private static void debug(int s) {

        err.println(s);

    }

    private static boolean isPrime(long n) {

        // Check if number is less than

        // equal to 1

        if (n <= 1)

            return false;

        // Check if number is 2

        else if (n == 2)

            return true;

        // Check if n is a multiple of 2

        else if (n % 2 == 0)

            return false;

        // If not, then just check the odds

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

            if (n % i == 0)

                return false;

        }

        return true;

    }

    private static List<List<Integer>> readUndirectedGraph(int n) {

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

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

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

        }

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

            int x = sc.nextInt();

            int y = sc.nextInt();

            graph.get(x).add(y);

            graph.get(y).add(x);

        }

        return graph;

    }

    private static List<List<Integer>> readUndirectedGraph(int[][] intervals, int n) {

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

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

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

        }

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

            int x = intervals[i][0];

            int y = intervals[i][1];

            graph.get(x).add(y);

            graph.get(y).add(x);

        }

        return graph;

    }

    private static List<List<Integer>> readDirectedGraph(int[][] intervals, int n) {

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

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

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

        }

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

            int x = intervals[i][0];

            int y = intervals[i][1];

            graph.get(x).add(y);

            // graph.get(y).add(x);

        }

        return graph;

    }

    private static List<List<Integer>> readDirectedGraph(int n) {

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

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

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

        }

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

            int x = sc.nextInt();

            int y = sc.nextInt();

            graph.get(x).add(y);

            // graph.get(y).add(x);

        }

        return graph;

    }

    static String[] readStringArray(int n) {

        String[] arr = new String[n];

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

            arr[i] = sc.next();

        }

        return arr;

    }

    private static Map<Character, Integer> freq(String s) {

        Map<Character, Integer> map = new HashMap<>();

        for (char c : s.toCharArray()) {

            map.put(c, map.getOrDefault(c, 0) + 1);

        }

        return map;

    }

    private static Map<Long, Integer> freq(long[] arr) {

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

        for (long x : arr) {

            map.put(x, map.getOrDefault(x, 0) + 1);

        }

        return map;

    }

    private static Map<Integer, Integer> freq(int[] arr) {

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

        for (int x : arr) {

            map.put(x, map.getOrDefault(x, 0) + 1);

        }

        return map;

    }

    static boolean[] sieveOfEratosthenes(long n) {

        boolean prime[] = new boolean[(int) n + 1];

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

            prime[i] = true;

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

            // If prime[p] is not changed, then it is a

            // prime

            if (prime[p] == true) {

                // Update all multiples of p

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

                    prime[i] = false;

            }

        }

        return prime;

    }

    static int[] sieveOfEratosthenesInt(long n) {

        boolean prime[] = new boolean[(int) n + 1];

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

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

            prime[i] = true;

        }

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

            if (prime[p] == true) {

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

                    prime[i] = false;

                }

            }

        }

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

            if (prime[i])

                li.add(i);

        }

        int[] arr = new int[li.size()];

        int i = 0;

        for (int x : li) {

            arr[i++] = x;

        }

        return arr;

    }

    static boolean isMemberAC(int a, int d, int x) {

        // If difference is 0, then x must

        // be same as a.

        if (d == 0)

            return (x == a);

        // Else difference between x and a

        // must be divisible by d.

        return ((x - a) % d == 0 && (x - a) / d >= 0);

    }

    static boolean isMemberAC(long a, long d, long x) {

        // If difference is 0, then x must

        // be same as a.

        if (d == 0)

            return (x == a);

        // Else difference between x and a

        // must be divisible by d.

        return ((x - a) % d == 0 && (x - a) / d >= 0);

    }

    private static void sort(int[] arr) {

        int n = arr.length;

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

        for (int x : arr) {

            li.add(x);

        }

        Collections.sort(li);

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

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

        }

    }

    private static void sortReverse(int[] arr) {

        int n = arr.length;

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

        for (int x : arr) {

            li.add(x);

        }

        Collections.sort(li, Collections.reverseOrder());

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

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

        }

    }

    private static void sort(double[] arr) {

        int n = arr.length;

        List<Double> li = new ArrayList<>();

        for (double x : arr) {

            li.add(x);

        }

        Collections.sort(li);

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

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

        }

    }

    private static void sortReverse(double[] arr) {

        int n = arr.length;

        List<Double> li = new ArrayList<>();

        for (double x : arr) {

            li.add(x);

        }

        Collections.sort(li, Collections.reverseOrder());

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

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

        }

    }

    private static void sortReverse(long[] arr) {

        int n = arr.length;

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

        for (long x : arr) {

            li.add(x);

        }

        Collections.sort(li, Collections.reverseOrder());

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

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

        }

    }

    private static void sort(long[] arr) {

        int n = arr.length;

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

        for (long x : arr) {

            li.add(x);

        }

        Collections.sort(li);

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

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

        }

    }

    private static long sum(int[] arr) {

        long sum = 0;

        for (int x : arr) {

            sum += x;

        }

        return sum;

    }

    private static long sum(long[] arr) {

        long sum = 0;

        for (long x : arr) {

            sum += x;

        }

        return sum;

    }

    private static void initializeIO() {

        try {

            System.setIn(new FileInputStream("input.txt"));

            System.setOut(new PrintStream(new FileOutputStream("output.txt")));

            System.setErr(new PrintStream(new FileOutputStream("error.txt")));

        } catch (Exception e) {

            System.err.println(e.getMessage());

        }

    }

    private static int maxOfArray(int[] arr) {

        int max = Integer.MIN_VALUE;

        for (int x : arr) {

            max = Math.max(max, x);

        }

        return max;

    }

    private static long maxOfArray(long[] arr) {

        long max = Long.MIN_VALUE;

        for (long x : arr) {

            max = Math.max(max, x);

        }

        return max;

    }

    private static int[][] readIntIntervals(int n, int m) {

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

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

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

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

            }

        }

        return arr;

    }

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

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

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

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

    private static int[] readIntArray(int n) {

        int[] arr = new int[n];

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

            arr[i] = sc.nextInt();

        }

        return arr;

    }

    private static double[] readDoubleArray(int n) {

        double[] arr = new double[n];

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

            arr[i] = sc.nextDouble();

        }

        return arr;

    }

    private static long[] readLongArray(int n) {

        long[] arr = new long[n];

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

            arr[i] = sc.nextLong();

        }

        return arr;

    }

    private static void print(int[] arr) throws IOException {

        out.println(Arrays.toString(arr));

    }

    private static void print(long[] arr) throws IOException {

        out.println(Arrays.toString(arr));

    }

    private static void print(String[] arr) throws IOException {

        out.println(Arrays.toString(arr));

    }

    private static void print(double[] arr) throws IOException {

        out.println(Arrays.toString(arr));

    }

    private static void debug(String[] arr) {

        err.println(Arrays.toString(arr));

    }

    private static void debug(Boolean[][] arr) {

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

            err.println(Arrays.toString(arr[i]));

    }

    private static void debug(int[] arr) {

        err.println(Arrays.toString(arr));

    }

    private static void debug(long[] arr) {

        err.println(Arrays.toString(arr));

    }

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

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

        int parent = 1;

        int[] arr;

        int n;

        Map<Integer, Integer> node_parent;

        List<Integer> leaf;

        public Tree(int n) {

            this.n = n;

            leaf = new ArrayList<>();

            node_parent = new HashMap<>();

            arr = new int[n + 2];

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

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

            }

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

                arr[i] = sc.nextInt();

                node_parent.put(i + 1, arr[i]);

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

                    parent = arr[i];

                else

                    adj.get(arr[i]).add(i + 1);

            }

        }

        private List<List<Integer>> getTree() {

            return adj;

        }

        private void formLeaf(int v) {

            boolean leaf = true;

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

                formLeaf(x);

                leaf = false;

            }

            if (leaf)

                this.leaf.add(v);

        }

        private List<Integer> getLeaf() {

            return leaf;

        }

        private Map<Integer, Integer> getParents() {

            return node_parent;

        }

        int[] getArr() {

            return arr;

        }

    }

    static class Dsu {

        int[] parent, size;

        Dsu(int n) {

            parent = new int[n + 1];

            size = new int[n + 1];

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

                parent[i] = i;

                size[i] = 1;

            }

        }

        private int findParent(int u) {

            if (parent[u] == u)

                return u;

            return parent[u] = findParent(parent[u]);

        }

        private boolean union(int u, int v) {

            // System.out.println("uf "+u+" "+v);

            int pu = findParent(u);

            // System.out.println("uf2 "+pu+" "+v);

            int pv = findParent(v);

            // System.out.println("uf3 " + u + " " + pv);

            if (pu == pv)

                return false;

            if (size[pu] <= size[pv]) {

                parent[pu] = pv;

                size[pv] += size[pu];

            } else {

                parent[pv] = pu;

                size[pu] += size[pv];

            }

            return true;

        }

    }

    // ===================================================================================

    public static int log2(int N) {

        return (int) (Math.log(N) / Math.log(2));

    }

    private static long fact(long n) {

        if (n <= 2)

            return n;

        return n * fact(n - 1);

    }

    private static void print(String s) throws IOException {

        out.println(s);

    }

    public static boolean isNumeric(String strNum) {

        if (strNum == null) {

            return false;

        }

        try {

            double d = Double.parseDouble(strNum);

        } catch (NumberFormatException nfe) {

            return false;

        }

        return true;

    }

    private static boolean isSorted(List<Integer> li) {

        int n = li.size();

        if (n <= 1)

            return true;

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

            if (li.get(i) > li.get(i + 1))

                return false;

        }

        return true;

    }

    private static boolean isSorted(int[] arr) {

        int n = arr.length;

        if (n <= 1)

            return true;

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

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

                return false;

        }

        return true;

    }

    private static boolean ispallindromeList(List<Integer> res) {

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

        while (l < r) {

            if (res.get(l) != res.get(r))

                return false;

            l++;

            r--;

        }

        return true;

    }

    private static long ncr(long n, long r) {

        return fact(n) / (fact(r) * fact(n - r));

    }

    private static void swap(char[] s, int i, int j) {

        char t = s[i];

        s[i] = s[j];

        s[j] = t;

    }

    static boolean isPowerOfTwo(long x) {

        return x != 0 && ((x & (x - 1)) == 0);

    }

    private static long gcd(long[] arr) {

        long ans = 0;

        for (long x : arr) {

            ans = gcd(x, ans);

        }

        return ans;

    }

    private static int gcd(int[] arr) {

        int ans = 0;

        for (int x : arr) {

            ans = gcd(x, ans);

        }

        return ans;

    }

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

        long res = 1;

        x = x % p;

        if (x == 0)

            return 0;

        while (y > 0) {

            if ((y & 1) != 0)

                res = (res * x) % p;

            y = y >> 1;

            x = (x * x) % p;

        }

        return res;

    }

}


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.

/*****  --->         :)    Vijender  Srivastava      (:       <---       *****/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

    static FastReader sc =new FastReader();

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

    static long mod=(long)998244353;

    static StringBuilder sb = new StringBuilder();

    /* start */

    public static void main(String [] args)

    {

        int testcases = 1;

        testcases = i();

        // calc();

        while(testcases-->0)

        {

            solve();

        }

        out.flush();

        out.close();

    }

    static void solve()

    {

        int n = i(),a[] = input(n);

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

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

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

        {

            fre[a[i]]++;

            if(map.containsKey(a[i]) && i-map.get(a[i])>1)

            {

                pl("YES");

                return;

            } else map.put(a[i],i);

            if(fre[a[i]]==3)

            {

                pl("YES");

                return ;

            }

        }

        pl("NO");

    }

    /* end */

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(new

                     InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  e)

                {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException e)

            {

                e.printStackTrace();

            }

            return str;

        }

    }

    // print code start

    static void p(Object o)

    {

        out.print(o);

    }

    static void pl(Object o)

    {

        out.println(o);

    }

    static void pl()

    {

        out.println("");

    }

    // print code end //

    static int i() {

        return sc.nextInt();

    }

    static String s() {

        return sc.next();

    }

    static long l() {

        return sc.nextLong();

    }

    static char[] inputC()

    {

        String s = sc.nextLine();

        return s.toCharArray();

    }

    static int[] input(int n) {

        int A[]=new int[n];

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

               A[i]=sc.nextInt();

           }

        return A;

    }

    static long[] inputL(int n) {

        long A[]=new long[n];

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

               A[i]=sc.nextLong();

           }

           return A;

    }

    static int[][] input(int n,int m) {

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

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

        return a;

    }

    static long[][] inputL(int n,int m)

    {

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

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

        return a;

    }

    static long[] putL(long a[]) {

        long A[]=new long[a.length];

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

               A[i]=a[i];

           }

           return A;

    }

    static String[] inputS(int n) {

        String A[]=new String[n];

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

               A[i]=sc.next();

           }

           return A;

    }

    static int gcd(int a, int b)

     {

         if (a == 0)

             return b;

         return gcd(b % a, a);

     }

     static long gcd(long a, long b)

     {

         if (a == 0)

             return b;

         return gcd(b % a, a);

     }

     static int lcm(int a, int b)

    {

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

    }

     static String reverse(String s) {

        StringBuffer p=new StringBuffer(s);

        p.reverse();

        return p.toString();

     }

     static int min(int a,int b) {

        return Math.min(a, b);

    }

    static int min(int a,int b,int c) {

        return Math.min(a, Math.min(b, c));

    }

    static int min(int a,int b,int c,int d) {

        return Math.min(a, Math.min(b, Math.min(c, d)));

    }

    static int max(int a,int b) {

        return Math.max(a, b);

    }

    static int max(int a,int b,int c) {

        return Math.max(a, Math.max(b, c));

    }

    static int max(int a,int b,int c,int d) {

        return Math.max(a, Math.max(b, Math.max(c, d)));

    }

    static long min(long a,long b) {

        return Math.min(a, b);

    }

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

        return Math.min(a, Math.min(b, c));

    }

    static long min(long a,long b,long c,long d) {

        return Math.min(a, Math.min(b, Math.min(c, d)));

    }

    static long max(long a,long b) {

        return Math.max(a, b);

    }

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

        return Math.max(a, Math.max(b, c));

    }

    static long max(long a,long b,long c,long d) {

        return Math.max(a, Math.max(b, Math.max(c, d)));

    }

    static long sum(int A[]) {

        long sum=0;

        for(int i : A) {

            sum+=i;

        }

        return sum;

    }

    static long sum(long A[]) {

        long sum=0;

        for(long i : A) {

            sum+=i;

        }

        return sum;

    }

    static long mod(long x) {

          return ((x%mod + mod)%mod);

    }

    static long sum_mod(long x,long y)

    {

        return mod(mod(x)+mod(y));

    }

    public static long ncr_mod(long n,long r){

        long top=fac_mod(n);

        long bottom=mul_mod(fac_mod(r),fac_mod(n-r));

        long ans=mul_mod(top,power_mod(bottom,mod-2));

        return ans;

    }

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

        if(b==0)return 1;

        if(b==1)return a;

        long res=1;

        while(b>0){

            if((b&1)==1) res=mul_mod(res,a);

            a=mul_mod(a,a);

            b/=2;

        }

        return res;

    }

    public static long fac_mod(long n){

        if(n==0)return 1;

        return mul_mod(fac_mod(n-1),n);

    }

    static long mul_mod(long x,long y)

    {

        return mod(mod(x)*mod(y));

    }

    static long power(long x, long y)

    {

	if(y==0)

		return 1;

	if(x==0)

		return 0;

    long res = 1;

    while (y > 0) {

        if (y % 2 == 1)

            res = (res * x) ;

        y = y >> 1;

        x = (x * x);

    }

    return res;

    }

    static boolean prime(int n)

	    {

	        if (n <= 1)

	            return false;

	        if (n <= 3)

	            return true;

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

	            return false;

	        double sq=Math.sqrt(n);

	        for (int i = 5; i <= sq; i = i + 6)

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

	                return false;

	        return true;

	    }

     static boolean prime(long n)

	    {

	        if (n <= 1)

	            return false;

	        if (n <= 3)

	            return true;

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

	            return false;

	        double sq=Math.sqrt(n);

	        for (int i = 5; i <= sq; i = i + 6)

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

	                return false;

	        return true;

	    }

        static long[] sort(long a[]) {

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

            for(long i : a) {

                arr.add(i);

            }

            Collections.sort(arr);

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

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

            }

            return a;

        }

        static int[] sort(int a[])

        {

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

            for(Integer i : a) {

                arr.add(i);

            }

            Collections.sort(arr);

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

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

            }

            return a;

        }

        static int[] sortInd(int a[])

        {

            int n = a.length;

            int ii[] = new int[n];

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

            ii = Arrays.stream(ii).boxed().sorted((i,j)->a[i]-a[j]).mapToInt($->$).toArray();

            return ii;

        }

        //pair class

        private static class Pair implements Comparable<Pair> {

            long first, second;

            public Pair(long f, long s) {

                first = f;

                second = s;

            }

            @Override

            public int compareTo(Pair p) {

                if (first < p.first)

                    return 1;

                else if (first > p.first)

                    return -1;

                else {

                    if (second > p.second)

                        return 1;

                    else if (second < p.second)

                        return -1;

                    else

                        return 0;

                }

            }

        }

}