C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3
-2 1
OutputCopy3 1 2 InputCopy5
1 1 1 1
OutputCopy1 2 3 4 5 InputCopy4
-1 2 2
OutputCopy-1

	import java.io.*;

	import java.util.*;

	public class ProblemD {

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

			Scanner in = new Scanner();

			int n = in.readInt();

			long a[] = new long[n-1];

			long nn = n;

			long ans = (nn*(nn+1))/2;

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

				a[i] = in.readLong();

				ans-=((n-i-1) * a[i]);

			}

			boolean ok = true;

			LinkedHashSet<Long>set = new LinkedHashSet<>();

			if(ans%n == 0 && ans>0){

				ans/=n;

				set.add(ans);

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

					ans+=a[i];

					if(set.contains(ans) || ans<=0 || ans>n)ok = false;

					set.add(ans);

				}

			}else ok = false;

			if(ok){

				for(long it:set)System.out.print(it+" ");

			}else System.out.println(-1);

		}

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

			return b ==0 ?a:gcd(b,a%b);

		}

		public static long nearest(TreeSet<Long> list,long target){

			long nearest = -1,sofar = Integer.MAX_VALUE;

			for(long it:list){

				if(Math.abs(it - target)<sofar){

					sofar = Math.abs(it - target);

					nearest = it;

				}

			}

			return nearest;

		}

		public static ArrayList<Long> factors(long n){

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

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

				if(n%i == 0){

					l.add(i);

					if(n/i != i)l.add(n/i);

				}

			}

			Collections.sort(l);

			return l;

		}

		public static void swap(int a[],int i, int j){

			int t = a[i];

			a[i] = a[j];

			a[j] = t;

		}

		public static boolean isSorted(long a[]){

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

				if(i+1<a.length && a[i]>a[i+1])return false;

			}

			return true;

		}

		public static int first(ArrayList<Long>list,long target){

			int index = -1;

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

			while(l<=r){

				int mid = (l+r)/2;

				if(list.get(mid) == target){

					index = mid;

					r = mid-1;

				}else if(list.get(mid)>target){

					r  = mid-1;

				}else l  = mid+1;

			}

			return index;

		}

		public static int last(ArrayList<Long>list,long target){

			int index = -1;

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

			while(l<=r){

				int mid = (l+r)/2;

				if(list.get(mid) == target){

					index=  mid;

					l = mid+1;

				}else if(list.get(mid)<target){

					l  = mid+1;

				}else r  = mid-1;

			}

			return index;

		}

		public static void sort(int arr[]){

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

			for(int it:arr)list.add(it);

			Collections.sort(list);

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

		}

		static class Pair{

			int x,y;

			public Pair(int x,int y){

				this.x = x;

				this.y = y;

			}

		}

		static class Scanner{

			BufferedReader br;

			StringTokenizer st;

			public Scanner(){

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

			}

		    public String read()

		    {

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

		            try {	st = new StringTokenizer(br.readLine()); }

		            catch (Exception e) {	e.printStackTrace(); }

		         }

		         return st.nextToken();

		     }

		     public int  readInt() { return Integer.parseInt(read()); }

		     public long readLong() { return Long.parseLong(read()); }

		     public double readDouble(){return Double.parseDouble(read());}

		     public  String readLine() throws Exception { return br.readLine(); }

		}

}


C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets:   a occurs at (1)(1), (2)(2), (3)(3)  b occurs at (4)(4), (5)(5)  ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5)  aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3)  bb occurs at (4,5)(4,5)  aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4)  aaa occurs at (1,2,3)(1,2,3)  abb occurs at (3,4,5)(3,4,5)  aaab occurs at (1,2,3,4)(1,2,3,4)  aabb occurs at (2,3,4,5)(2,3,4,5)  aaabb occurs at (1,2,3,4,5)(1,2,3,4,5)  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

import java.awt.image.AreaAveragingScaleFilter;

import java.awt.image.MemoryImageSource;

import java.io.*;

import java.sql.Array;

import java.util.*;

import java.util.StringTokenizer;

public class cf799 {

    static class FastReader{

        BufferedReader br;

        StringTokenizer st;

        public FastReader(){

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

        }

        String next(){

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt(){

            return Integer.parseInt(next());

        }

        long nextLong(){

            return Long.parseLong(next());

        }

        double nextDouble(){

            return Double.parseDouble(next());

        }

        String nextLine(){

            String str="";

            try {

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

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

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

        }

        public void print(Object object) throws IOException {

            bw.append("" + object);

        }

        public void println(Object object) throws IOException {

            print(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

    static int []   parent=new int[100001];

    static int [] rank=new int[100001];

    public static void makeSet(){

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

            parent[i]=i;

            rank[i]=0;

        }

    }

    public static int findParent(int num){

        if(parent[num]==num)return num;

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

    }

    public static void union(int a,int b){

        int ff=findParent(a);

        int ss=findParent(b);

        if(rank[ff]<rank[ss]){

            parent[ff]=ss;

        }

        else if(rank[ss]<rank[ff]){

            parent[ss]=ff;

        }

        else{

            parent[ff]=ss;

            rank[ss]++;

        }

    }

static class ArrayMaxComparator implements Comparator<int[]> {

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

        return b[0] - a[0];

    }

}

    public static void main(String[] args) {

        try {

            FastReader sc = new FastReader();

            FastWriter out = new FastWriter();

//int t=sc.nextInt();

//while(t-->0) {

//    int a = sc.nextInt();

//    int b = sc.nextInt();

//int total=sc.nextInt();

//int discount= sc.nextInt();

//long first= (long) b * total;

//

//int times=(total)%(discount+1)==0?(total)/(discount+1):(total)/(discount+1)+1;

//long second= (long) times *discount*a;

//times--;

//long third=(((long) times *discount*a));

//int left=total-(times*discount+times);

//long fourth=third;

//third+= (long) left *b;

//fourth+=(long)left*a;

//

//    System.out.println(Math.min(fourth,Math.min(((long) a *total),Math.min(first,Math.min(second,third)))));

//

        String s=sc.next();

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

        PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());

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

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

        }

        for(char key:map.keySet()){

            pq.add(map.get(key));

        }

            long ans= (long) pq.remove();

//        int count=1;

//

//        int n=s.length();

//

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

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

//           if(s.charAt(i)!=s.charAt(i-1)){

//               occ.add(count);

//               count=1;

//           }else{

//               count++;

//           }

//       }

//       if(count!=0)occ.add(count);

//       int []prev_max=new int[occ.size()];

//       int [] suff_max=new int[occ.size()];

//       prev_max[0]=occ.get(0);

//for(int i=1;i<occ.size();i++){

//    prev_max[i]=Math.max(occ.get(i),prev_max[i-1]);

//}

//

//

//

//

//suff_max[occ.size()-1]=occ.get(occ.size()-1);

//

//

//

//

//for(int i=occ.size()-2;i>=0;i--){

//    suff_max[i]=Math.max(suff_max[i+1],occ.get(i));

//}

//int ans=0;

//for(int i=0;i<occ.size()-1;i++){

//    ans=Math.max(ans,prev_max[i]*suff_max[i+1]);

//

//}

//            System.out.println(ans);

//            int n=s.length();

//            // int ans=0;

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

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

//

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

//                    String s2=""+s.charAt(i);

//                    s2+=s.charAt(j);

//                    map2.put(s2,map2.getOrDefault(s2,0)+1);

//                    ans=Math.max(ans,map2.get(s2));

//                }

//            }

//            System.out.println(ans);

//

int n=s.length();

            int [][] d_2=new int[n][26];

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

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

                if(i==0){

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

                        d_2[i][ij]=ij==num?1:0;

                    }

                }else{

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

                        d_2[i][ij] =ij==num?d_2[i-1][ij]+1:d_2[i-1][ij];

                    }

                }

            }

            int [][] d_2_prev=new int[n][26];

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

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

                if(i==n-1){

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

                        d_2_prev[i][ij]=ij==num?1:0;

                    }

                }else{

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

                        d_2_prev[i][ij] =ij==num?d_2_prev[i+1][ij]+1:d_2_prev[i+1][ij];

                    }

                }

            }

//            for(int []d:d_2_prev)

//            System.out.println(Arrays.toString(d));

         //   qdpinbmcrfwxpdbfgozvvocemjructoadewegtvbvbfwwrpgyeaxgddrwvlqnygwmwhmrhaizpyxvgaflrsvzhhzrouvpxrkxfza

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

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

        char ff=(char)('a'+i);

        char ss=(char)('a'+j);

       long count=0L;

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

            if(s.charAt(k)==ff){

                count+= (long) d_2_prev[k + 1][ss - 'a'];

            }

        }

        ans=(long)(Math.max(ans,count));

count=0L;

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

            if(s.charAt(k)==ss){

                count+= (long) d_2_prev[k + 1][ff - 'a'];

            }

        }

        ans=Math.max(ans,count);

    }

}

            //System.out.println(d_2);

          //  System.out.println();

            System.out.println(ans);

        }catch (Exception e) {

            return;

        }

    }

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

        long ans=1;

        while(r>0){

            ans=((ans%1000000007)*n)%1000000007;

r--;

n--;

        }

        return ans;

    }

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

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

    }

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

        if(b==0)return a;

        return gcd(b,a%b);

    }

    static class Pair {

        int a;

        int b;

        // int c;

        Pair(int a, int b ) {

            this.a = a;

            this.b = b;

            //     this.c=c;

        }

    }

    static class Pair2 {

        String a;

        int b;

        // int c;

        Pair2(String a, int b ) {

            this.a = a;

            this.b = b;

            //     this.c=c;

        }

    }

    static   class ArrayKey {

        private int[] array;

        public ArrayKey(int[] array) {

            this.array = array;

        }

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            ArrayKey arrayKey = (ArrayKey) o;

            return Arrays.equals(array, arrayKey.array);

        }

        @Override

        public int hashCode() {

            return Arrays.hashCode(array);

        }

    }

}


A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here:  After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5).  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3).  After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

        Reader.init(System.in);

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

//        int t = Reader.nextInt();

        int t = 1;

        while(t-->0) {

            int n = Reader.nextInt();

            int q = Reader.nextInt();

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

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

            int hurdles = 0;

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

                int r = Reader.nextInt();

                int c = Reader.nextInt();

                if(r==1){

                    if(row1[c]){

                        row1[c] = false;

                        if(c-1>=0 && row2[c-1]) hurdles--;

                        if(row2[c]) hurdles--;

                        if(c+1<=n && row2[c+1]) hurdles--;

                    }

                    else{

                        row1[c] = true;

                        if(c-1>=0 && row2[c-1]) hurdles++;

                        if(row2[c]) hurdles++;

                        if(c+1<=n && row2[c+1]) hurdles++;

                    }

                }

                else{

                    if(row2[c]){

                        row2[c] = false;

                        if(c-1>=0 && row1[c-1]) hurdles--;

                        if(row1[c]) hurdles--;

                        if(c+1<=n && row1[c+1]) hurdles--;

                    }

                    else{

                        row2[c] = true;

                        if(c-1>=0 && row1[c-1]) hurdles++;

                        if(row1[c]) hurdles++;

                        if(c+1<=n && row1[c+1]) hurdles++;

                    }

                }

                if(hurdles==0){

                    output.write("YES\n");

                }

                else{

                    output.write("NO\n");

                }

            }

    }

        output.close();

    }

    public static long[] factorial(int n){

        long[] factorials = new long[n+1];

        factorials[1] = 1;

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

            factorials[i] = (factorials[i-1]*i)%((int)1e9+7);

        }

        return factorials;

    }

    public static long numOfBits(long n){

        long ans = 0;

        while(n>0){

            n = n & (n-1);

            ans++;

        }

        return ans;

    }

    public static long ceilOfFraction(long x, long y){

        // ceil using integer division: ceil(x/y) = (x+y-1)/y

        // using double may go out of range.

        return (x+y-1)/y;

    }

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

        int res = 1;

        x = x % p;

        while (y > 0) {

            if (y % 2 == 1) res = (res * x) % p;

            y = y >> 1;

            x = (x * x) % p;

        }

        return res;

    }

    // Returns n^(-1) mod p

    public static int modInverse(int n, int p) {

        return power(n, p - 2, p);

    }

    // Returns nCr % p using Fermat's

    // little theorem.

    public static int nCrModPFermat(int n, int r, int p) {

        if (n<r) return 0;

        if (r == 0) return 1;

        // Fill factorial array so that we

        // can find all factorial of r, n

        // and n-r

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

        fac[0] = 1;

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

            fac[i] = fac[i - 1] * i % p;

        return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;

    }

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

        long p = 1, k = 1;

        if (n - r < r) {

            r = n - r;

        }

        if (r != 0) {

            while (r > 0) {

                p *= n;

                k *= r;

                long m = gcd(p, k);

                p /= m;

                k /= m;

                n--;

                r--;

            }

        } else {

            p = 1;

        }

        return p;

    }

    public static boolean isPrime(long n){

        if (n <= 1) return false;

        if (n <= 3) return true;

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

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

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

                return false;

            }

        }

        return true;

    }

    public static int powOf2JustSmallerThanN(int n) {

        n |= n >> 1;

        n |= n >> 2;

        n |= n >> 4;

        n |= n >> 8;

        n |= n >> 16;

        return n ^ (n >> 1);

    }

    public static int mergeSortAndCount(int[] arr, int l, int r) {

        int count = 0;

        if (l < r) {

            int m = (l + r) / 2;

            count += mergeSortAndCount(arr, l, m);

            count += mergeSortAndCount(arr, m + 1, r);

            count += mergeAndCount(arr, l, m, r);

        }

        return count;

    }

    public static int mergeAndCount(int[] arr, int l, int m, int r) {

        int[] left = Arrays.copyOfRange(arr, l, m + 1);

        int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);

        int i = 0, j = 0, k = l, swaps = 0;

        while (i < left.length && j < right.length) {

            if (left[i] <= right[j])

                arr[k++] = left[i++];

            else {

                arr[k++] = right[j++];

                swaps += (m + 1) - (l + i);

            }

        }

        while (i < left.length)

            arr[k++] = left[i++];

        while (j < right.length)

            arr[k++] = right[j++];

        return swaps;

    }

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

        int temp;

        while (start < end) {

            temp = arr[start];

            arr[start] = arr[end];

            arr[end] = temp;

            start++;

            end--;

        }

    }

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

        if(a==0){

            return b;

        }

        return gcd(b%a,a);

    }

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

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

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

    }

    public static long largeExponentMod(long x,long y,long mod){

        // computing (x^y) % mod

        x%=mod;

        long ans = 1;

        while(y>0){

            if((y&1)==1){

                ans = (ans*x)%mod;

            }

            x = (x*x)%mod;

            y = y >> 1;

        }

        return ans;

    }

    public static boolean[] numOfPrimesInRange(long L, long R){

        boolean[] isPrime = new boolean[(int) (R-L+1)];

        Arrays.fill(isPrime,true);

        long lim = (long) Math.sqrt(R);

        for (long i = 2; i <= lim; i++){

            for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){

                isPrime[(int) (j - L)] = false;

            }

        }

        if (L == 1) isPrime[0] = false;

        return isPrime;

    }

    public static ArrayList<Long> primeFactors(long n){

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

        if(n%2==0){

            factorization.add(2L);

        }

        while(n%2==0){

            n/=2;

        }

        if(n%3==0){

            factorization.add(3L);

        }

        while(n%3==0){

            n/=3;

        }

        if(n%5==0){

            factorization.add(5L);

        }

        while(n%5==0){

//            factorization.add(5L);

            n/=5;

        }

        int[] increments = {4, 2, 4, 2, 4, 6, 2, 6};

        int i = 0;

        for (long d = 7; d * d <= n; d += increments[i++]) {

            if(n%d==0){

                factorization.add(d);

            }

            while (n % d == 0) {

//                factorization.add(d);

                n /= d;

            }

            if (i == 8)

                i = 0;

        }

        if (n > 1)

            factorization.add(n);

        return factorization;

    }

}

class DSU {

    int[] size, parent;

    int n;

    public DSU(int n){

        this.n = n;

        size = new int[n];

        parent = new int[n];

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

            parent[i] = i;

            size[i] = 1;

        }

    }

    public int find(int u){

        if(parent[u]==u){

            return u;

        }

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

    }

    public void merge(int u, int v){

        u = find(u);

        v = find(v);

        if(u!=v){

            if(size[u]>size[v]){

                parent[v] = u;

                size[u] += size[v];

            }

            else{

                parent[u] = v;

                size[v] += size[u];

            }

        }

    }

}

class Reader {

    static BufferedReader reader;

    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */

    static void init(InputStream input) {

        reader = new BufferedReader(

                new InputStreamReader(input) );

        tokenizer = new StringTokenizer("");

    }

    /** get next word */

    static String next() throws IOException {

        while ( ! tokenizer.hasMoreTokens() ) {

            //TODO add check for eof if necessary

            tokenizer = new StringTokenizer(

                    reader.readLine() );

        }

        return tokenizer.nextToken();

    }

    static String nextLine() throws IOException {

        return reader.readLine();

    }

    static int nextInt() throws IOException {

        return Integer.parseInt( next() );

    }

    static long nextLong() throws IOException{

        return Long.parseLong(next() );

    }

    static double nextDouble() throws IOException {

        return Double.parseDouble( next() );

    }

}


C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can:   either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5
4 100
0 0 0 0
1 2
1
3 4
1 4 1
3 2
0 1 3
3 9
0 59049 810
OutputCopyYES
YES
NO
NO
YES
NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;

/*
*
*   820 = 729,81,9,1;
*     0 , 0 ,
*
*
* */

public class Codeforces {
     public static void main(String[] args) {
        FastReader fastReader = new FastReader();
        PrintWriter out = new PrintWriter(System.out);
        int tt = fastReader.nextInt();
         outer:while(tt-- > 0) {
            int n = fastReader.nextInt();
            int k = fastReader.nextInt();
            long a[] =fastReader.rla(n);
            HashSet<Integer> set = new HashSet<>();
            for(int i = 0 ; i < n; i++){
                long val = a[i];
                while(val > 0){
                    int pow = largestPoawer(val,k);
                    if(!set.add(pow)){
                        out.println("NO");
                        continue outer;
                    }
                    val-=lp(val,k);

                }
            }
            out.println("YES");
         }
         out.close();
     }

    public static int largestPoawer(long val, int base){
        int pow  =0;
        long cur = 1L;
        while(val >= cur){
            cur*=base;
            pow++;
        }

        return pow-1;
    }
    public static long lp(long val,int base){
         int pow = 0;
         long curr = 1L;
         while(curr <=val){
             curr*=base;
         }
         return curr/base;
    }

    static class Pair{
        int x;
        int y;
        Pair(int x, int y){
            this.x  = x;
            this.y = y;
        }

    }

    // constants
    static final int IBIG = 1000000007;
    static final int IMAX = 2147483647;
    static final long LMAX = 9223372036854775807L;
    static Random __r = new Random();

    // math util
    static int minof(int a, int b, int c) {
        return min(a, min(b, c));
    }

    static int minof(int... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return min(x[0], x[1]);
        if (x.length == 3)
            return min(x[0], min(x[1], x[2]));
        int min = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] < min)
                min = x[i];
        return min;
    }

    static long minof(long a, long b, long c) {
        return min(a, min(b, c));
    }

    static long minof(long... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return min(x[0], x[1]);
        if (x.length == 3)
            return min(x[0], min(x[1], x[2]));
        long min = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] < min)
                min = x[i];
        return min;
    }

    static int maxof(int a, int b, int c) {
        return max(a, max(b, c));
    }

    static int maxof(int... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return max(x[0], x[1]);
        if (x.length == 3)
            return max(x[0], max(x[1], x[2]));
        int max = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] > max)
                max = x[i];
        return max;
    }

    static long maxof(long a, long b, long c) {
        return max(a, max(b, c));
    }

    static long maxof(long... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return max(x[0], x[1]);
        if (x.length == 3)
            return max(x[0], max(x[1], x[2]));
        long max = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] > max)
                max = x[i];
        return max;
    }

    static int powi(int a, int b) {
        if (a == 0)
            return 0;
        int ans = 1;
        while (b > 0) {
            if ((b & 1) > 0)
                ans *= a;
            a *= a;
            b >>= 1;
        }
        return ans;
    }

    static long powl(long a, int b) {
        if (a == 0)
            return 0;
        long ans = 1;
        while (b > 0) {
            if ((b & 1) > 0)
                ans *= a;
            a *= a;
            b >>= 1;
        }
        return ans;
    }

    static int fli(double d) {
        return (int) d;
    }

    static int cei(double d) {
        return (int) ceil(d);
    }

    static long fll(double d) {
        return (long) d;
    }

    static long cel(double d) {
        return (long) ceil(d);
    }

    static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static int lcm(int a, int b) {
        return (a / gcd(a, b)) * b;
    }

    static long gcd(long a, long b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static long lcm(long a, long b) {
        return (a / gcd(a, b)) * b;
    }

    static int[] exgcd(int a, int b) {
        if (b == 0)
            return new int[] { 1, 0 };
        int[] y = exgcd(b, a % b);
        return new int[] { y[1], y[0] - y[1] * (a / b) };
    }

    static long[] exgcd(long a, long b) {
        if (b == 0)
            return new long[] { 1, 0 };
        long[] y = exgcd(b, a % b);
        return new long[] { y[1], y[0] - y[1] * (a / b) };
    }

    static int randInt(int min, int max) {
        return __r.nextInt(max - min + 1) + min;
    }

    static long mix(long x) {
        x += 0x9e3779b97f4a7c15L;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
        x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
        return x ^ (x >> 31);
    }

    public static boolean[] findPrimes(int limit) {
        assert limit >= 2;

        final boolean[] nonPrimes = new boolean[limit];
        nonPrimes[0] = true;
        nonPrimes[1] = true;

        int sqrt = (int) Math.sqrt(limit);
        for (int i = 2; i <= sqrt; i++) {
            if (nonPrimes[i])
                continue;
            for (int j = i; j < limit; j += i) {
                if (!nonPrimes[j] && i != j)
                    nonPrimes[j] = true;
            }
        }

        return nonPrimes;
    }

    // array util
    static void reverse(int[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            int swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void reverse(long[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            long swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void reverse(double[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            double swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void reverse(char[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            char swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void shuffle(int[] a) {
        int n = a.length - 1;
        for (int i = 0; i < n; ++i) {
            int ind = randInt(i, n);
            int swap = a[i];
            a[i] = a[ind];
            a[ind] = swap;
        }
    }

    static void shuffle(long[] a) {
        int n = a.length - 1;
        for (int i = 0; i < n; ++i) {
            int ind = randInt(i, n);
            long swap = a[i];
            a[i] = a[ind];
            a[ind] = swap;
        }
    }

    static void shuffle(double[] a) {
        int n = a.length - 1;
        for (int i = 0; i < n; ++i) {
            int ind = randInt(i, n);
            double swap = a[i];
            a[i] = a[ind];
            a[ind] = swap;
        }
    }

    static void rsort(int[] a) {
        shuffle(a);
        sort(a);
    }

    static void rsort(long[] a) {
        shuffle(a);
        sort(a);
    }

    static void rsort(double[] a) {
        shuffle(a);
        sort(a);
    }

    static int[] copy(int[] a) {
        int[] ans = new int[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static long[] copy(long[] a) {
        long[] ans = new long[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static double[] copy(double[] a) {
        double[] ans = new double[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static char[] copy(char[] a) {
        char[] ans = new char[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

        int[] ria(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = Integer.parseInt(next());
            return a;
        }

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

        long[] rla(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = Long.parseLong(next());
            return a;
        }

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

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


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

import java.util.*;

import java.lang.*;

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

public class Codechef

{

   static void shuffleSort(int[] a) {

        int n=a.length;

        Random r=new Random();

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

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

            a[i]=a[oi];

            a[oi]=temp;

        }

        Arrays.sort(a);

   }

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

	{

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

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

	  long H=Long.parseLong(st.nextToken());

	  int n=Integer.parseInt(st.nextToken());

	  int a[]=new int[n];

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

	  long prefix[]=new long[n];

	  long sum=0;

	  long min=Long.MAX_VALUE;

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

	     a[i]=Integer.parseInt(st.nextToken());

	     sum+=a[i];

	     prefix[i]=sum;

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

	  }

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

	     if(H+min>0){

	        System.out.print(-1);

	     }

	     else{

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

	           if(prefix[i]+H<=0){

	              System.out.print((i+1));

	              break;

	           }

	        }

	     }

	  }

	  else{

	     if(H+min<=0){

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

	           if(prefix[i]+H<=0){

	              System.out.print((i+1));

	              break;

	           }

	        }

	     }

	     else{

	        long k=(long)Math.ceil((H+min)/(double)Math.abs(prefix[n-1]));

	        H=H+k*prefix[n-1];

	        long time=k*n;

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

	           if(prefix[i]+H<=0){

	              time=time+i+1;

	              break;

	           }

	        }

	        System.out.print(time);

	     }

	  }

	}

}


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Random;
import java.util.HashMap;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        CInstantNoodles solver = new CInstantNoodles();
        solver.solve(1, in, out);
        out.close();
    }

    static class CInstantNoodles {
        long[] random;

        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            int t = in.scanInt();

            random = new long[500005];

            for (int i = 0; i < random.length; i++) random[i] = new Random().nextInt(1000000000) + 234792734l;

            while (t-- > 0) {
                int n = in.scanInt();
                int m = in.scanInt();
                long cost[] = new long[n + 1];
                for (int i = 1; i <= n; i++) cost[i] = in.scanLong();

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

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

                for (int i = 0; i < m; i++) {
                    int a = in.scanInt();
                    int b = in.scanInt();
                    arrayList[b].add(a);
                }

                for (int i = 1; i <= n; i++) {
                    if (arrayList[i].size() == 0) continue;
                    Collections.sort(arrayList[i]);
                    long hash = findHash(arrayList[i]);
                    hashMap.put(hash, cost[i] + hashMap.getOrDefault(hash, 0l));
                }

                long gcd = 0;
                for (long kkk : hashMap.values()) {
                    gcd = CodeX.GCD(gcd, kkk);
                }

                out.println(gcd);

            }

        }

        long findHash(ArrayList<Integer> arrayList) {
            int p = 0;
            long res = 0;
            for (int k : arrayList) {
                res = (res + ((k * random[p++]) % 792950153)) % 792950153;
            }
            return res;
        }

    }

    static class CodeX {
        public static long GCD(long A, long B) {
            if (B == 0)
                return A;
            else
                return GCD(B, A % B);
        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int INDEX;
        private BufferedInputStream in;
        private int TOTAL;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (INDEX >= TOTAL) {
                INDEX = 0;
                try {
                    TOTAL = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TOTAL <= 0) return -1;
            }
            return buf[INDEX++];
        }

        public int scanInt() {
            int I = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    I *= 10;
                    I += n - '0';
                    n = scan();
                }
            }
            return neg * I;
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

        public long scanLong() {
            long I = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    I *= 10;
                    I += n - '0';
                    n = scan();
                }
            }
            return neg * I;
        }

    }
}


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

// package c1296;

//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// F. Berland Beauty
// https://codeforces.com/contest/1296/problem/F
// time limit per test 3 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n railway stations in Berland. They are connected to each other by n-1 railway
// sections. The railway network is connected, i.e. can be represented as an undirected tree.
//
// You have a map of that network, so for each railway section you know which stations it connects.
//
// Each of the n-1 sections has some integer value of the . However, these values are not marked on
// the map and you don't know them. All these values are from 1 to 10^6 inclusive.
//
// You asked m passengers some questions: the j-th one told you three values:
//  * his departure station a_j;
//  * his arrival station b_j;
//  * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest
//    path from a_j to b_j).
//
// You are planning to update the map and set some value f_i on each railway section -- the . The
// passengers' answers should be consistent with these values.
//
// Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent
// with or report that it doesn't exist.
//
// Input
//
// The first line contains a single integer n (2 <= n <= 5000) -- the number of railway stations in
// Berland.
//
// The next n-1 lines contain descriptions of the railway sections: the i-th section description is
// two integers x_i and y_i (1 <= x_i, y_i <= n, x_i != y_i), where x_i and y_i are the indices of
// the stations which are connected by the i-th railway section. All the railway sections are
// bidirected. Each station can be reached from any other station by the railway.
//
// The next line contains a single integer m (1 <= m <= 5000) -- the number of passengers which were
// asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1
// <= a_j, b_j <= n; a_j != b_j; 1 <= g_j <= 10^6) -- the departure station, the arrival station and
// the minimum scenery beauty along his path.
//
// Output
//
// If there is no answer then print a single integer -1.
//
// Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 <= f_i <= 10^6), where f_i is some valid
// scenery beauty along the i-th railway section.
//
// If there are multiple answers, you can print any of them.
//
// Example
/*
input:
4
1 2
3 2
3 4
2
1 2 5
1 3 3
output:
5 3 5

input:
6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
output:
5 3 1 2 1

input:
6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
output:
-1
*/
//

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class C1296F {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  static int[] solve(int[][] edges, int[][] paths) {
    int n = edges.length + 1;
    int m = paths.length;

    List<int[]>[] adjs = new ArrayList[n+1];
    for (int i = 0; i < n+1; i++) {
      adjs[i] = new ArrayList<>();
    }
    for (int i = 0; i < n-1; i++) {
      int u = edges[i][0];
      int v = edges[i][1];
      adjs[u].add(new int[] {v, i});
      adjs[v].add(new int[] {u, i});
    }

    int[][] parent = new int[n+1][2];
    int[] depth = new int[n+1];
    int r = 1;

    Queue<Integer> q = new LinkedList<>();
    q.add(r);
    while (!q.isEmpty()) {
      int v = q.poll();
      for (int[] e : adjs[v]) {
        int w = e[0];
        if (w == parent[v][0]) {
          continue;
        }
        parent[w][0] = v;
        parent[w][1] = e[1];
        depth[w] = depth[v] + 1;
        q.add(w);
      }
    }
    if (test) System.out.format("  parent: %s\n", Arrays.deepToString(parent));

    int maxw = 0;
    for (int pid = 0; pid < m; pid++) {
      maxw = Math.max(maxw, paths[pid][2]);
    }

    // Evaluate all paths in descending weight order
    Arrays.sort(paths, (x,y)->y[2]-x[2]);

    int[] ans = new int[n-1];
    for (int pid = 0; pid < m; pid++) {
      int a = paths[pid][0];
      int b = paths[pid][1];
      int w = paths[pid][2];
      List<Integer> eids = getPathEdgesList(a, b, parent, depth);
      if (test) System.out.format("  pid:%d a:%d b:%d w:%d eids:%s\n", pid, a, b, w, eids.toString());
      // All the involved edges has minimal weight w
      boolean ok = false;
      for (int eid : eids) {
        myAssert(ans[eid] == 0 || ans[eid] >= w);
        if (ans[eid] == 0) {
          if (test) System.out.format("  assign %d %d\n", eid, w);
          ans[eid] = w;
          ok = true;
        } else if (ans[eid] == w) {
          ok = true;
        } else {
          // this edge won't satisfy w
        }
      }
      if (!ok) {
        // no edge in the path can support w
        return null;
      }
    }
    for (int i = 0; i < n-1; i++) {
      if (ans[i] == 0) {
        ans[i] = maxw;
      }
    }
    return ans;
  }

  // Time limit exceeded on test 268
  // 5000
  // 1 2
  // 2 3
  // 3 4
  // ...
  // test 264 5000 2261 ms  2262 ms
  // test 266 5000 2713 ms  2355 ms
  static int[] solveA(int[][] edges, int[][] paths) {
    int n = edges.length + 1;
    int m = paths.length;

    List<int[]>[] adjs = new ArrayList[n+1];
    for (int i = 0; i < n+1; i++) {
      adjs[i] = new ArrayList<>();
    }
    for (int i = 0; i < n-1; i++) {
      int u = edges[i][0];
      int v = edges[i][1];
      adjs[u].add(new int[] {v, i});
      adjs[v].add(new int[] {u, i});
    }

    int[][] parent = new int[n+1][2];
    int[] depth = new int[n+1];
    int r = 1;

    Queue<Integer> q = new LinkedList<>();
    q.add(r);
    while (!q.isEmpty()) {
      int v = q.poll();
      for (int[] e : adjs[v]) {
        int w = e[0];
        if (w == parent[v][0]) {
          continue;
        }
        parent[w][0] = v;
        parent[w][1] = e[1];
        depth[w] = depth[v] + 1;
        q.add(w);
      }
    }
    if (test) System.out.format("  parent: %s\n", Arrays.deepToString(parent));

    // pida[eid] is the path ids that contains edge eid
    Set<Integer>[] pida = new HashSet[n-1];
    for (int eid = 0; eid < n-1; eid++) {
      // Sort paths for the edge in ascending order of weight (smallest path first)
      // *** Note that if we sort, ensure the comparison is NOT 0 for different eid regardless ***
      // pida[eid] = new TreeSet<>((x, y)->paths[x][2] - paths[y][2]);
      pida[eid] = new HashSet<>();
    }

    TreeMap<Integer, Set<Integer>> wpids = new TreeMap<>();

    int maxw = 0;
    for (int pid = 0; pid < m; pid++) {
      int a = paths[pid][0];
      int b = paths[pid][1];
      int w = paths[pid][2];
      maxw = Math.max(maxw, w);
      List<Integer> eids = getPathEdgesList(a, b, parent, depth);
      if (test) System.out.format("  pid:%d a:%d b:%d w:%d eids:%s\n", pid, a, b, w, eids.toString());
      for (int eid : eids) {
        pida[eid].add(pid);
      }
      wpids.computeIfAbsent(w, x -> new HashSet<>()).add(pid);
    }

    for (int eid = 0; eid < n-1; eid++) {
      if (!pida[eid].isEmpty()) {
        if (test) {
          List<Integer> pids = new ArrayList<>(pida[eid]);
          System.out.format("  eid:%d pids:%s\n", eid, pids.toString());
        }
      }
    }
    for (Map.Entry<Integer, Set<Integer>> e : wpids.entrySet()) {
      int w = e.getKey();
      Set<Integer> pids = e.getValue();
      if (test) System.out.format("  w:%d pids:%s\n", w, pids.toString());
    }

    boolean[] edone = new boolean[n-1];
    boolean[] pdone = new boolean[m];

    int[] ans = new int[n-1];
    Arrays.fill(ans, maxw);

    Set<Integer> eids = new HashSet<>();
    for (int eid = 0; eid < n-1; eid++) {
      if (edone[eid] || pida[eid].isEmpty()) {
        continue;
      }
      eids.add(eid);
    }

    for (Map.Entry<Integer, Set<Integer>> e : wpids.entrySet()) {
      int w = e.getKey();
      Set<Integer> pids = e.getValue();
      if (test) System.out.format("  w:%d pids:%s\n", w, pids.toString());
      while (!pids.isEmpty()) {
        int eid = -1;
        for (int v : eids) {
          boolean ok = true;
          for (int pid : pida[v]) {
            myAssert(!pdone[pid]);
            if (paths[pid][2] != w) {
              ok = false;
              break;
            }
          }
          if (ok) {
            eid = v;
            break;
          }
        }
        if (eid < 0) {
          if (test) System.out.format("  no edge for %d found\n", w);
          return null;
        }
        if (test) System.out.format("  found edge %d for %d found\n", eid, w);
        Set<Integer> epids = pida[eid];

        if (test) System.out.format("    epids %s\n", epids.toString());

        ans[eid] = w;
        edone[eid] = true;
        // remove eid from all the paths that contain it
        for (int pid : epids) {
          pdone[pid] = true;
        }
        for (int v : eids) {
          if (v != eid) {
            pida[v].removeAll(epids);
            if (test) System.out.format("    v:%d %s\n", v, pida[v].toString());
          }
        }
        eids.remove(eid);
        pids.removeAll(epids);
      }
    }
    return ans;
  }

  static Set<Integer> getPathEdgesSet(int a, int b, int[][] parent, int[] depth) {
    if (depth[a] < depth[b]) {
      return getPathEdgesSet(b, a, parent, depth);
    }
    myAssert(depth[a] >= depth[b]);
    //        root
    //        /
    //       p
    //      / \
    //     *   b
    //    /
    //   a

    Set<Integer> edges = new HashSet<>();
    int x = a;
    for (int i = 0; i < depth[a] - depth[b]; i++) {
      edges.add(parent[x][1]);
      x = parent[x][0];
    }
    int y = b;
    while (x != y) {
      edges.add(parent[x][1]);
      x = parent[x][0];
      edges.add(parent[y][1]);
      y = parent[y][0];
    }
    return edges;
  }

  // Get list of edge ids on the path from a to b.
  // For efficiency, the order is not guarantee.
  static List<Integer> getPathEdgesList(int a, int b, int[][] parent, int[] depth) {
    if (depth[a] < depth[b]) {
      return getPathEdgesList(b, a, parent, depth);
    }
    myAssert(depth[a] >= depth[b]);
    //        root
    //        /
    //       p
    //      / \
    //     *   b
    //    /
    //   a

    List<Integer> edges = new ArrayList<>();
    int x = a;
    for (int i = 0; i < depth[a] - depth[b]; i++) {
      edges.add(parent[x][1]);
      x = parent[x][0];
    }
    int y = b;
    while (x != y) {
      edges.add(parent[x][1]);
      x = parent[x][0];
      edges.add(parent[y][1]);
      y = parent[y][0];
    }
    return edges;
  }

  static String trace(int[][] a) {
    return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
  }

  static String trace(int[] a) {
    return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
  }

  static void test(int[] exp, int[][] railways, int[][] paths) {
    System.out.format("edges:%s\n", trace(railways));
    System.out.format("paths:%s\n", trace(paths));
    int[] ans = solve(railways, paths);
    boolean ok = true;
    if (ans == null) {
      ok = exp == null;
      System.out.format("  => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
    } else if (exp == null) {
      System.out.format("  => %s Expected -1\n", trace(ans));
      ok = false;
    } else {
      for (int i = 0; i < ans.length; i++) {
        if (ans[i] != exp[i]) {
          ok = false;
          break;
        }
      }
      System.out.format("  => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
    }
    myAssert(ok);
  }

  static boolean test = false;
  static void doTest() {
    if (!test) {
      return;
    }
    long t0 = System.currentTimeMillis();
    test(new int[] {5,3,1,2,5}, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
        new int[][] {{6,1,3},{3,4,1},{6,5,2},{1,2,5},{1,4,5}});

    test(new int[] {1}, new int[][] {{2,1}}, new int[][] {{1,2,1},{2,1,1}});
    test(null, new int[][] {{1,2},{3,1},{4,2}}, new int[][] {{2,4,1},{4,1,2}});
    test(new int[] {5,3,5}, new int[][] {{1,2},{3,2},{3,4}}, new int[][] {{1,2,5},{1,3,3}});
    test(new int[] {5,3,1,2,1}, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
        new int[][] {{6,1,3},{3,4,1},{6,5,2},{1,2,5}});
    test(new int[] {3, 3}, new int[][] {{2,1},{3,1}}, new int[][] {{3,2,3}});
    test(new int[] {2, 4}, new int[][] {{1,2},{1,3}}, new int[][] {{3,2,2},{1,3,4}});

    test(null, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
        new int[][] {{6,1,1},{3,4,3},{6,5,3},{1,2,4}});

    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    doTest();
    MyScanner in = new MyScanner();
    int n = in.nextInt();
    int[][] railways = new int[n-1][2];
    for (int i = 0; i < n-1; i++) {
      railways[i][0] = in.nextInt();
      railways[i][1] = in.nextInt();
    }
    int m = in.nextInt();
    int[][] questions = new int[m][3];
    for (int i = 0; i < m; i++) {
      questions[i][0] = in.nextInt();
      questions[i][1] = in.nextInt();
      questions[i][2] = in.nextInt();
    }
    int[] ans = solve(railways, questions);
    output(ans);
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
      sb.append(v);
      sb.append(' ');
      if (sb.length() > 4000) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }

  static class MyScanner {
    BufferedReader br;
    StringTokenizer st;

    public MyScanner() {
      try {
        final String USERDIR = System.getProperty("user.dir");
        String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
        cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
        final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
        br = new BufferedReader(new InputStreamReader(fin.exists()
            ? new FileInputStream(fin) : System.in));
      } catch (Exception e) {
        br = new BufferedReader(new InputStreamReader(System.in));
      }
    }

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

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

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


E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:  if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100];  if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then:  erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union;  erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

	PrintWriter out = new PrintWriter(System.out);

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

    StringTokenizer tok = new StringTokenizer("");

    String next() throws IOException {

        if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }

        return tok.nextToken();

    }

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

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

    long mod=1000000007;

    void solve() throws IOException {

        for (int tc=ni();tc>0;tc--) {

            int n=ni();

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

            for (int i=0;i<n;i++) { A[i][0]=ni(); A[i][1]=ni(); A[i][2]=i;}

            Arrays.sort(A,(a,b)->Integer.compare(a[0],b[0]));

            int[]C=new int[n];

            HashSet<Integer>H=new HashSet();

            PriorityQueue<Pair>Q=new PriorityQueue<Pair>((a,b)->a.v-b.v);

            int max=0;

            int seg=-1;

            int ans=1;

            boolean end=false;

            boolean overlap=false;

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

                int nextstart=A[i][0];

                while (Q.size()>0 && Q.peek().v<nextstart) {

                    Pair toremove=Q.poll();

                    H.remove(toremove.id);

                    end=true;

                }

                if (end && H.size()==1 ) {

                    for (int v:H) {

                        C[v]++;

                        if (C[v]>max) { max=C[v]; seg=v; }

                    }

                }

                if (end && H.size()==0) { ans++; end=false; }

                if (H.size()>0) overlap=true;

                H.add(A[i][2]);

                Q.add(new Pair(A[i][1],A[i][2]));

            }

            if (!overlap) ans--;

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

            out.println(ans+max);

        }

        out.flush();

    }

    class Pair {

        int v,id;

        Pair(int a,int b) { v=a; id=b; }

        int getval() { return v; }

    }

    int gcd(int a,int b) { return(b==0?a:gcd(b,a%b)); }

    long gcd(long a,long b) { return(b==0?a:gcd(b,a%b)); }

    long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; }

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

        new Main().solve();

    }

}


E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.StringTokenizer;

public class StringColoring {

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

        new StringColoring().solve();

    }

    public void solve() throws IOException{

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

        PrintWriter out = new PrintWriter(System.out);

        int n = Integer.parseInt(f.readLine());

        char[] seq = f.readLine().toCharArray();

        int[] values = new int[n];

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

            values[i] = seq[i] - 'a';

        }

        seq = null;

        int[] color = new int[n];

        int[][] maxByColor = new int[n][26];

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

            color[i] = maxByColor[i][values[i]] + 1;

            if (i != n - 1) {

                for (int j = 0; j < values[i]; j++) {

                    maxByColor[i + 1][j] = Math.max(maxByColor[i][j], color[i]);

                }

                for (int j = values[i]; j < 26; j++) {

                    maxByColor[i + 1][j] = maxByColor[i][j];

                }

            }

        }

        int max = 0;

        for (int i = 0; i < n; i++) max = Math.max(max, color[i]);

        out.println(max);

        out.print(color[0]);

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

            out.print(" ");

            out.print(color[i]);

        }

        out.println();

        out.close();

    }

}


/*

        "Everything in the universe is balanced. Every disappointment

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

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

        int[] maxColorNeeded = new int[26];

        int[] dp = new int[n];

        Arrays.fill(dp, 1); // at least one color needed to color

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

            int index = s[i] - 'a';

            for (int j = 25; j > index; j--) { // swap is required for these chars, since we want to sort

                dp[i] = Math.max(dp[i], maxColorNeeded[j] + 1);

            }

            maxColorNeeded[index] = Math.max(maxColorNeeded[index], dp[i]);

        }

        int maxColorRequired = 0;

        for (int colorsNeeded : maxColorNeeded) {

            maxColorRequired = Math.max(maxColorRequired, colorsNeeded);

        }

        out.println(maxColorRequired);

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

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

        }

        out.println();

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  end)

                {

                    end.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException end)

            {

                end.printStackTrace();

            }

            return str;

        }

    }

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

//package Codeforces.GFG;

import java.util.*;

public class F {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

        int[] ar = new int[n];

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

            ar[i] = in.nextInt();

        }

        Arrays.sort(ar);

        System.out.println(cal(30, 0, n - 1, ar));

    }

    static int cal(int index, int from, int to, int[] data) {

        if (index < 0) {

            return 0;

        }

        if (from > to) {

            return 0;

        }

        int re = -1;

        int st = from;

        int ed = to;

        while (st <= ed) {

            int mid = (st + ed) / 2;

            if ((data[mid] & (1 << index)) != 0) {

                re = mid;

                ed = mid - 1;

            } else {

                st = mid + 1;

            }

        }

        if (re != -1 && re != from) {

            int a = (1 << index) + cal(index - 1, from, re - 1, data);

            int b = (1 << index) + cal(index - 1, re, to, data);

            return Integer.min(a, b);

        } else {

            return cal(index - 1, from, to, data);

        }

    }

}


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

import java.util.ArrayList;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

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

            int n = sc.nextInt();

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

            int sum = 0;

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

                arrayList.add(sc.nextInt() % 2);

                sum += arrayList.get(j);

            }

            if (sum == arrayList.size() || sum == 0) {

                System.out.println("YES");

            } else {

                System.out.println("NO");

            }

        }

    }

}


A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets:  the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different),  the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — 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≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.

import java.util.*;

public class cC {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while(t-->0) {

			int n = sc.nextInt();

			int neck[] = new int[n];

			for(int i=0;i<n;i++) neck[i] = sc.nextInt();

			int brac[] = new int[n];

			for(int i=0;i<n;i++) brac[i] = sc.nextInt();

			Arrays.sort(neck);

			Arrays.sort(brac);

			for(int i=0;i<n;i++)System.out.print(neck[i]+" ");

			System.out.println();

			for(int i=0;i<n;i++)System.out.print(brac[i]+" ");

			System.out.println();

		}

	}

}