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

import java.io.*;

import java.util.*;

import java.util.function.BinaryOperator;

import java.util.stream.Collectors;

public class Main {

    private final static long mod = 1000000007;

    private final static int MAXN = 1000001;

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

        long temp;

        if (y == 0)

            return 1;

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

        temp = (temp * temp) % m;

        if (y % 2 == 0)

            return temp;

        else

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

    }

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

        return power(x, y, mod);

    }

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

        if (b == 0) return a;

        return gcd(b, a % b);

    }

    static int nextPowerOf2(int a) {

        return 1 << nextLog2(a);

    }

    static int nextLog2(int a) {

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

    }

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

        long m0 = m;

        long y = 0, x = 1;

        if (m == 1)

            return 0;

        while (a > 1) {

            long q = a / m;

            long t = m;

            m = a % m;

            a = t;

            t = y;

            y = x - q * y;

            x = t;

        }

        if (x < 0)

            x += m0;

        return x;

    }

    private static int[] getLogArr(int n) {

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

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

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

        }

        return arr;

    }

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

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

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

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

    }

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

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

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

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

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

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

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

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

            }

        }

        return st;

    }

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

        int n=list.size();

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

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

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

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

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

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

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

            }

        }

        return st;

    }

    static class Subset {

        int parent;

        int rank;

        @Override

        public String toString() {

            return "" + parent;

        }

    }

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

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

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

        return subsets[i].parent;

    }

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

        int xroot = find(Subsets, x);

        int yroot = find(Subsets, y);

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

            Subsets[xroot].parent = yroot;

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

            Subsets[yroot].parent = xroot;

        else {

            Subsets[xroot].parent = yroot;

            Subsets[yroot].rank++;

        }

    }

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

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

    }

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

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

    }

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

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

    }

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

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

    }

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

        T a;

        U b;

        public Pair(T a, U b) {

            this.a = a;

            this.b = b;

        }

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Pair pair = (Pair) o;

            return a.equals(pair.a) &&

                    b.equals(pair.b);

        }

        @Override

        public int hashCode() {

            return Objects.hash(a, b);

        }

        @Override

        public String toString() {

            return "(" + a +

                    "," + b +

                    ')';

        }

        @Override

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

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

        }

    }

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

        int low = 0;

        int high = list.size();

        while (low < high) {

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

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

                low = mid + 1;

            } else {

                high = mid;

            }

        }

        return low;

    }

    private static int[] getLPSArray(String pattern) {

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

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

        lps[0] = 0;

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

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

                lps[i++] = ++j;

            } else if (j > 0) {

                j = lps[j - 1];

            } else {

                lps[i++] = 0;

            }

        }

        return lps;

    }

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

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

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

            return matchedIndexes;

        }

        int[] lps = getLPSArray(pattern);

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

        while (i < n) {

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

                i++;

                j++;

            }

            if (j == m) {

                matchedIndexes.add(i - j);

                j = lps[j - 1];

            }

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

                if (j > 0) {

                    j = lps[j - 1];

                } else {

                    i++;

                }

            }

        }

        return matchedIndexes;

    }

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

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

        divisors.add(1L);

        divisors.add(n);

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

            if (n % i == 0) {

                divisors.add(i);

                divisors.add(n / i);

            }

        }

        return divisors;

    }

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

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

    }

    static long fac[];

    static long ifac[];

    private static void preCompute(int n) {

        fac = new long[n + 1];

        ifac = new long[n + 1];

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

        int i;

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

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

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

        }

    }

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

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

        if (r > n) return 1;

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

    }

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

        int sum = 0;

        index = index + 1;

        while (index > 0) {

            sum+=BITree[index];

            index -= index & (-index);

        }

        return sum;

    }

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

        index = index + 1;

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

            BITree[index] += val;

            index += index & (-index);

        }

    }

    static int[] constructBITree(int n) {

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

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

            BITree[i] = 0;

        return BITree;

    }

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

        if (l > r) return -1;

        if (l == r) {

            if (a[l] <= x) {

                return -1;

            } else {

                return a[l];

            }

        }

        int m = (l + r) / 2;

        if (a[m] <= x) {

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

        } else {

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

        }

    }

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

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

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

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

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

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

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

                }

            }

        }

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

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

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

            }

        }

    }

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

        if (n < 2) {

            return;

        }

        power(A, base, n / 2);

        mul(A, A);

        if (n % 2 == 1) {

            mul(A, base);

        }

    }

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

        while (l < r) {

            int t = a[l];

            a[l] = a[r];

            a[r] = t;

            l++;

            r--;

        }

    }

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

        while (l < r) {

            long t = a[l];

            a[l] = a[r];

            a[r] = t;

            l++;

            r--;

        }

    }

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

        k = k % nums.length;

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

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

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

    }

    private static boolean isSorted(int a[]) {

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

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

        }

        return true;

    }

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

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

        int n = arr.length;

        int nge[] = new int[n];

        s.push(0);

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

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

                nge[s.peek()] = i;

                s.pop();

            }

            s.push(i);

        }

        while (!s.isEmpty()) {

            nge[s.peek()] = n;

            s.pop();

        }

        return nge;

    }

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

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

        int n = arr.length;

        int pse[] = new int[n];

        s.push(n-1);

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

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

                pse[s.peek()] = i;

                s.pop();

            }

            s.push(i);

        }

        while (!s.isEmpty()) {

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

            s.pop();

        }

        return pse;

    }

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

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

        int n = arr.length;

        int nse[] = new int[n];

        s.push(0);

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

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

                nse[s.peek()] = i;

                s.pop();

            }

            s.push(i);

        }

        while (!s.isEmpty()) {

            nse[s.peek()] = n;

            s.pop();

        }

        return nse;

    }

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

        int pse[]=getPSE(nums);

        int nse[]=getNSE(nums);

        int ans=0;

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

            int p=pse[i];

            int n=nse[i];

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

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

            }

        }

        return ans;

    }

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

        int nse[]=getNSE(nums);

        int pse[]=getPSE(nums);

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

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

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

                return len;

            }

        }

        return -1;

    }

    private static boolean isPal(String s){

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

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

        }

        return true;

    }

    private static int[] getSuffixArray(String s) {

        int n=s.length();

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

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

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

        }

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

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

        }

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

        int ind[]=new int[n];

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

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

            su[0][1]=0;

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

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

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

                    su[i][1]=rank;

                } else {

                    prev=su[i][1];

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

                }

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

            }

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

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

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

            }

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

        }

        int suf[]=new int[n];

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

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

        }

        return suf;

    }

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

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

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

            while(n%i==0){

                pfSet.add(i);

                n/=i;

            }

        }

        if(n>1){

            pfSet.add(n);

        }

        return pfSet;

    }

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

        long START_TIME = System.currentTimeMillis();

        try (FastReader in = new FastReader();

             FastWriter out = new FastWriter()) {

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

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

            {

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

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

                x=in.nextLong();

                y=in.nextLong();

                z=gcd(x,y);

                y/=z;

                Set<Long>pf=getPrimeFactors(y);

                for(long p:pf){

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

                }

                out.println(y);

            }

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

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

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

            }*/

            out.commit();

        }

    }

    public static class FastReader implements Closeable {

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

        private StringTokenizer st;

        String next() {

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

                try {

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

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        @Override

        public void close() throws IOException {

            br.close();

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextIntArr(int n) {

            int[] arr = new int[n];

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

                arr[i] = nextInt();

            }

            return arr;

        }

        Integer[] nextIntegerArr(int n) {

            Integer[] arr = new Integer[n];

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

                arr[i] = nextInt();

            }

            return arr;

        }

        double[] nextDoubleArr(int n) {

            double[] arr = new double[n];

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

                arr[i] = nextDouble();

            }

            return arr;

        }

        long[] nextLongArr(int n) {

            long[] arr = new long[n];

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

                arr[i] = nextLong();

            }

            return arr;

        }

        List<Long> nextLongList(int n) {

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

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

                retList.add(nextLong());

            }

            return retList;

        }

        String[] nextStrArr(int n) {

            String[] arr = new String[n];

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

                arr[i] = next();

            }

            return arr;

        }

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

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

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

                arr[i] = nextIntArr(m);

            }

            return arr;

        }

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

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

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

                arr[i] = nextLongArr(m);

            }

            return arr;

        }

    }

    public static class FastWriter implements Closeable {

        BufferedWriter bw;

        StringBuilder sb = new StringBuilder();

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

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

        public FastWriter() {

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

        }

        <T> void commit() throws IOException {

            bw.write(sb.toString());

            bw.flush();

            sb = new StringBuilder();

        }

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

            sb.append(obj.toString());

            //commit();

        }

        public void println() throws IOException {

            print("\n");

        }

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

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

        }

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

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

                print(arr[i] + " ");

            }

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

        }

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

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

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

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

                }

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

            }

        }

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

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

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

        }

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

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

                print(c);

            }

        }

        void printIntArr(int []arr) throws IOException {

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

                print(arr[i] + " ");

            }

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

        }

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

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

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

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

                }

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

            }

        }

        @Override

        public void close() throws IOException {

            bw.close();

        }

    }

}


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

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

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

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

    }
}


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

/*

        "Everything in the universe is balanced. Every disappointment

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

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = sc.nextInt();

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

        int m = sc.nextInt();

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

        int[] freq = new int[n];

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

            int val = sc.nextInt();

            freq[val - 1]++;

        }

        freq[n - 1]++;

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

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

        }

        int[] res = new int[26];

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

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

        }

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

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

        }

        out.println();

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

import java.util.List;

import java.util.ArrayList;

public class Solution {

    static Reader input = new Reader();

    static int n;

    static List<Integer>[] adjacents;

    static int[] parent, height, deep;

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

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

        n = input.nextInt();

        adjacents = new List[n];

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

        int u, v;

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

            u = input.nextInt()-1;

            v = input.nextInt()-1;

            adjacents[u].add(v);

            adjacents[v].add(u);

        }

        parent = new int[n];

        height = new int[n];

        deep = new int[n];

        dfs(0, -1);

        dfs(0);

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

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

        boolean[] inPath = new boolean[n];

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

        int[] t = null;

        for(int node : path) {

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

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

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

                t = temp;

            }

        }

        StringBuilder output = new StringBuilder();

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

        output.append(x);

        output.append("\n");

        output.append(start+1);

        output.append(" ");

        output.append(end+1);

        output.append(" ");

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

        System.out.print(output);

    }

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

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

        for(int adjacent : adjacents[node]) {

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

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

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

                    result = temp;

                }

            }

        }

        if(p != -1) {

            ++result[1];

        }

        return result;

    }

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

        if(node == dist) {

            path.add(node);

            return true;

        }

        for(int adjacent : adjacents[node]) {

            if(adjacent != p) {

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

                    path.add(node);

                    return true;

                }

            }

        }

        return false;

    }

    static void dfs(int node) {

        int max1 = -1, max2 = -1;

        for(int adjacent : adjacents[node]) {

            if(adjacent != parent[node]) {

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

                    max2 = max1;

                    max1 = adjacent;

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

                    max2 = adjacent;

                }

                dfs(adjacent);

            }

        }

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

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

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

                start = deep[max1];

                end = deep[max2];

            }

        } else if(max1 != -1) {

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

                v = height[max1]+1;

                start = deep[max1];

                end = node;

            }

        } else if(max2 != -1) {

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

                v = height[max2]+1;

                start = deep[max2]+1;

                end = node;

            }

        }

    }

    static void dfs(int node, int p) {

        parent[node] = p;

        int h = 0;

        int d = node;

        for(int adjacent : adjacents[node]) {

            if(adjacent != p) {

                dfs(adjacent, node);

                if(height[adjacent] > h) {

                    h = height[adjacent];

                    d = deep[adjacent];

                }

            }

        }

        height[node] = h+1;

        deep[node] = d;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


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

/*

    Author : Akshat Jindal

    from NIT Jalandhar , Punjab , India

    JAI MATA DI

 */

import java.util.*;

import javax.swing.text.Segment;

import java.io.*;

import java.math.*;

import java.sql.Array;

public class Main {

	  static class Scanner{

			BufferedReader br;

			StringTokenizer st;

			public Scanner() {

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

			}

			String next()

		    {

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

		        {

		            try

		            {

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

		            }

		            catch (IOException  e)

		            {

		                e.printStackTrace();

		            }

		        }

		        return st.nextToken();

		    }

		    int nextInt()

		    {

		        return Integer.parseInt(next());

		    }

		    long nextLong()

		    {

		        return Long.parseLong(next());

		    }

		    double nextDouble()

		    {

		        return Double.parseDouble(next());

		    }

		    String nextLine()

		    {

		        String str = "";

		        try

		        {

		            str = br.readLine();

		        }

		        catch (IOException e)

		        {

		            e.printStackTrace();

		        }

		        return str;

		    }

		}

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

	static void sort(long[] arr ) {

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

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

		 Collections.sort(al);

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

	 }

	static void sort(int[] arr ) {

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

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

		 Collections.sort(al);

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

	 }

	static void sort(char[] arr) {

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

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

		Collections.sort(al);

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

	}

	static void rvrs(int[] arr) {

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

		while(i>=j) {

			int temp = arr[i];

			arr[i] = arr[j];

			arr[j] = temp;

			i++;

			j--;

		}

	}

	static void rvrs(long[] arr) {

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

		while(i>=j) {

			long temp = arr[i];

			arr[i] = arr[j];

			arr[j] = temp;

			i++;

			j--;

		}

	}

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

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

	}

	 static long gcd(long a, long b)

	  {

	     if (b == 0)

	        return a;

	     return gcd(b, a % b);

	  }

	 static boolean[] prime(int num) {

			boolean[] bool = new boolean[num];

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

		         bool[i] = true;

		      }

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

		         if(bool[i] == true) {

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

		               bool[j] = false;

		            }

		         }

		      }

		      if(num >= 0) {

		    	  bool[0] = false;

		    	  bool[1] = false;

		      }

		      return bool;

		}

	 static long modInverse(long a, long m)

	    {

	        long g = gcd(a, m);

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

	    }

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

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

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

     static class Combinations{

	    	 private long[] z;

	    	 private long[] z1;

	    	 private long[] z2;

	    	  public Combinations(long N , long mod) {

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

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

				z[0] = 1;

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

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

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

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

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

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

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

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

			}

	    	  long fac(long n) {

	    		  return z[(int)n];

	    	  }

	    	  long invrsNum(long n) {

	    		  return z2[(int)n];

	    	  }

	    	  long invrsFac(long n) {

	    		  return invrsFac((int)n);

	    	  }

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

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

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

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

	    		             % mod;

	    		    return ans;

	    		}

	      }

	      static class DisjointUnionSets {

			    int[] rank, parent;

			    int n;

			    public DisjointUnionSets(int n)

			    {

			        rank = new int[n];

			        parent = new int[n];

			        this.n = n;

			        makeSet();

			    }

			    void makeSet()

			    {

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

			            parent[i] = i;

			        }

			    }

			    int find(int x)

			    {

			        if (parent[x] != x) {

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

			        }

			        return parent[x];

			    }

			    void union(int x, int y)

			    {

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

			        if (xRoot == yRoot)

			            return;

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

			            parent[xRoot] = yRoot;

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

			            parent[yRoot] = xRoot;

			        else

			        {

			            parent[yRoot] = xRoot;

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

			        }

			    }

			}

	      static int[] KMP(String str) {

	    	  int n = str.length();

	    	  int[] kmp = new int[n];

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

	    		  int j = kmp[i-1];

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

	    			  j = kmp[j-1];

	    		  }

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

	    		  kmp[i] = j;

	    	  }

	    	  return kmp;

	      }

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

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

	      static class SparseTable{

	    		private long[][] st;

	    		SparseTable(long[] arr){

	    			int n = arr.length;

	    			st = new long[n][25];

	    			log = new int[n+2];

	    			build_log(n+1);

	    			build(arr);

	    		}

	    		private void build(long[] arr) {

	    			int n = arr.length;

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

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

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

	    					if(r>=n) break;

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

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

	    				}

	    			}

	    		}

	    		public long gcd(long a  ,long b) {

	    			if(a == 0) return b;

	    			return gcd(b%a , a);

	    		}

	    		public long query(int l ,int r) {

	    			int w = r-l+1;

	    			int power = log[w];

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

	    		}

	    		private int[] log;

	    		void build_log(int n) {

	    			log[1] = 0;

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

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

	    			}

	    		}

	    	}

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

/**

	 	 static class SegmentTree{

			 long[] tree;

			 long[] arr;

			 int n;

			 SegmentTree(long[] arr){

				 this.n = arr.length;

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

				 this.arr = arr;

				 buildTree(0, n-1, 1);

			 }

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

					if(s == e) {

						tree[index] = arr[s];

						return;

					}

					int mid = (s+e)/2;

					buildTree( s,  mid, 2*index);

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

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

				}

			 long query(int si ,int ei) {

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

			 }

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

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

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

					int mid = (ss + se)/2;

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

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

					return Math.min(left, right);

				}

			 public void update(int index , int val) {

				 arr[index] = val;

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

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

			 }

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

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

				 if(si == ei ) {

					 tree[index] = arr[id];

					 return;

				 }

				 if(si > ei) return;

				 int mid = (ei + si)/2;

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

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

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

			 }

		 }

		 */

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

	      static Scanner sc = new Scanner();

	 static StringBuilder sb = new StringBuilder();

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

		 int tc = 1;

//		  tc = sc.nextInt();

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

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

			 TEST_CASE();

		 }

		 System.out.println(sb);

	 }

	 static void TEST_CASE() {

		 String str = sc.next();

		 int n = str.length();

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

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

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

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

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

		 }

		 int q = sc.nextInt();

		 while(q-- > 0) {

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

			 int c = 0;

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

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

			 }

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

				 sb.append("YES\n");

			 }else {

				 sb.append("NO\n");

			 }

		 }

	 }

}

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

/**

	abb - > bab - > bba

	abc - > cba

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

 	abbb -> bb

 	dbccbba

 */


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

import java.util.*;

public class A {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

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

            String tar = "";

            int q = in.nextInt();

            while (q!=0){

                if(q%2==0){

                    tar+="1";

                    q-=2;

                }else{

                    tar+="7";

                    q-=3;

                }

            }

            System.out.println(tar);

        }

    }

}


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

import java.util.*;

public class Task {

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

        new Task().go();

    }

    PrintWriter out;

    Reader in;

    BufferedReader br;

    Task() throws IOException {

        try {

            //br = new BufferedReader( new FileReader("input.txt") );

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

            in = new Reader("input.txt");

            out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) );

        }

        catch (Exception e) {

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

            in = new Reader();

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

        }

    }

    void go() throws Exception {

        //int t = in.nextInt();

        int t = 1;

        while (t > 0) {

            solve();

            t--;

        }

        out.flush();

        out.close();

    }

    int inf = 2000000000;

    int mod = 1000000007;

    double eps = 0.000000001;

    int n;

    int m;

    ArrayList<Integer>[] g;

    void solve() throws IOException {

        int n = in.nextInt();

        String s = in.next();

        int[] a = new int[n];

        int cnt = 1;

        int[] d = new int[26];

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

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

            d[ch] = 1;

            for (int j = ch + 1; j < 26; j++)

                d[ch] = Math.max(d[ch], d[j] + 1);

            cnt = Math.max(cnt, d[ch]);

            a[i] = d[ch];

        }

        out.println(cnt);

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

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

    }

    class Pair implements Comparable<Pair> {

        int a;

        int b;

        Pair(int a, int b) {

            this.a = a;

            this.b = b;

        }

        public int compareTo(Pair p) {

            if (a != p.a)

                return Integer.compare(a, p.a);

            else

                return Integer.compare(-b, -p.b);

        }

    }

    class Item {

        int a;

        int b;

        int c;

        Item(int a, int b, int c) {

            this.a = a;

            this.b = b;

            this.c = c;

        }

    }

    class Reader {

        BufferedReader  br;

        StringTokenizer tok;

        Reader(String file) throws IOException {

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

        }

        Reader() throws IOException {

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

        }

        String next() throws IOException {

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

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

            return tok.nextToken();

        }

        int nextInt() throws NumberFormatException, IOException {

            return Integer.valueOf(next());

        }

        long nextLong() throws NumberFormatException, IOException {

            return Long.valueOf(next());

        }

        double nextDouble() throws NumberFormatException, IOException {

            return Double.valueOf(next());

        }

        String nextLine() throws IOException {

            return br.readLine();

        }

    }

    static class InputReader

    {

        final private int BUFFER_SIZE = 1 << 16;

        private DataInputStream din;

        private byte[] buffer;

        private int bufferPointer, bytesRead;

        public InputReader()

        {

            din = new DataInputStream(System.in);

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public InputReader(String file_name) throws IOException

        {

            din = new DataInputStream(new FileInputStream(file_name));

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public String readLine() throws IOException

        {

            byte[] buf = new byte[64]; // line length

            int cnt = 0, c;

            while ((c = read()) != -1)

            {

                if (c == '\n')

                    break;

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

            }

            return new String(buf, 0, cnt);

        }

        public int nextInt() throws IOException

        {

            int ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

            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;

        }

        public long nextLong() throws IOException

        {

            long ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

            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;

        }

        public double nextDouble() throws IOException

        {

            double ret = 0, div = 1;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do {

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

            }

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

            if (c == '.')

            {

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

                {

                    ret += (c - '0') / (div *= 10);

                }

            }

            if (neg)

                return -ret;

            return ret;

        }

        private void fillBuffer() throws IOException

        {

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

            if (bytesRead == -1)

                buffer[0] = -1;

        }

        private byte read() throws IOException

        {

            if (bufferPointer == bytesRead)

                fillBuffer();

            return buffer[bufferPointer++];

        }

        public void close() throws IOException

        {

            if (din == null)

                return;

            din.close();

        }

    }

}


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.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author Nikita Gorokhov <wackloner@yandex-team.ru>
 */
public class A1310 {

    // 420 remainder: use long everywhere

    private final static boolean MULTIPLE_TESTS = false;

    private FastReader reader;
    private FastWriter writer;

    private void solve() {
        int n = reader.readInt();
        int[] a = reader.readIntArray(n);
        int[] t = reader.readIntArray(n);

        var sorted = IntStream.range(0, n)
                .mapToObj(i -> Tuple.Tuple2.of(a[i], t[i]))
                .sorted()
                .collect(Collectors.toList());

        TreeMap<Integer, Integer> multiset = new TreeMap<>();
        long sumInSet = 0;
        long ans = 0;
        int last = -1;
        for (int i = 0; i < n; i++) {
            var cur = sorted.get(i);

            if (cur.first != last) {
                while (!multiset.isEmpty() && last < cur.first) {
                    var max = multiset.lastEntry();
                    var newVal = max.getValue() - 1;
                    sumInSet -= max.getKey();
                    if (newVal == 0) {
                        multiset.remove(max.getKey());
                    } else {
                        multiset.put(max.getKey(), max.getValue() - 1);
                    }
                    ans += sumInSet;
                    last++;
                }

                last = cur.first;
            }

            multiset.put(cur.second, multiset.getOrDefault(cur.second, 0) + 1);
            sumInSet += cur.second;
        }

        while (!multiset.isEmpty()) {
            var max = multiset.lastEntry();
            var newVal = max.getValue() - 1;
            sumInSet -= max.getKey();
            if (newVal == 0) {
                multiset.remove(max.getKey());
            } else {
                multiset.put(max.getKey(), max.getValue() - 1);
            }
            ans += sumInSet;
            last++;
        }

        writer.print(ans);
    }

    private void run() throws Exception {
        reader = new FastReader();
        writer = new FastWriter();

        int t = MULTIPLE_TESTS ? reader.readInt() : 1;

        for (int testNum = 0; testNum < t; testNum++) {
            solve();
        }

        writer.close();
        reader.close();
    }

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

    private final static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    private static class FastWriter implements AutoCloseable {
        @SuppressWarnings(value="all")
        private final static Optional<String> OUTPUT_FILENAME = Optional.empty();

        private final PrintWriter out;

        public FastWriter() throws FileNotFoundException {
            this.out = OUTPUT_FILENAME.isEmpty() ? new PrintWriter(System.out) : new PrintWriter(new File(OUTPUT_FILENAME.get()));
        }

        public void print(int value) {
            out.print(value);
        }

        public void print(long value) {
            out.print(value);
        }

        public void print(double value) {
            out.print(value);
        }

        public <T> void print(T value) {
            out.print(value);
        }

        public void println(int value) {
            out.println(value);
        }

        public void println(long value) {
            out.println(value);
        }

        public void println(double value) {
            out.println(value);
        }

        public <T> void println(T value) {
            out.println(value);
        }

        public <T> void printArray(T[] array) {
            for (int i = 0; i < array.length; i++) {
                out.print(array[i]);
                if (i + 1 < array.length) {
                    out.print(' ');
                }
            }
            out.println();
        }

        public void printArray(int[] array) {
            for (int i = 0; i < array.length; i++) {
                out.print(array[i]);
                if (i + 1 < array.length) {
                    out.print(' ');
                }
            }
            out.println();
        }

        public void printArray(long[] array) {
            for (int i = 0; i < array.length; i++) {
                out.print(array[i]);
                if (i + 1 < array.length) {
                    out.print(' ');
                }
            }
            out.println();
        }

        public void printArray(double[] array) {
            for (int i = 0; i < array.length; i++) {
                out.print(array[i]);
                if (i + 1 < array.length) {
                    out.print(' ');
                }
            }
            out.println();
        }

        @Override
        public void close() {
            out.close();
        }
    }

    private static class FastReader implements AutoCloseable {
        private final static String INPUT_FILENAME = "input.txt";

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

        private int bufferLen = 0;
        private int bufferPtr = 0;

        public FastReader() throws FileNotFoundException {
            this.inputStream = ONLINE_JUDGE ? System.in : new FileInputStream(INPUT_FILENAME);
        }

        public int[] readIntArray(int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = readInt();
            }
            return array;
        }

        public long[] readLongArray(int size) {
            long[] array = new long[size];
            for (int i = 0; i < size; i++) {
                array[i] = readLong();
            }
            return array;
        }

        public double[] readDoubleArray(int size) {
            double[] array = new double[size];
            for (int i = 0; i < size; i++) {
                array[i] = readLong();
            }
            return array;
        }

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

        public String readToken() {
            int b = skip();
            StringBuilder sb = new StringBuilder();
            while (!(isSpaceChar(b))) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }

        public int readInt() {
            int num = 0, b;
            boolean minus = false;

            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));

            if (b == '-') {
                minus = true;
                b = readByte();
            }

            while (true) {
                if (b >= '0' && b <= '9') {
                    num = num * 10 + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public long readLong() {
            long num = 0;
            int b;
            boolean minus = false;

            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));

            if (b == '-') {
                minus = true;
                b = readByte();
            }

            while (true) {
                if (b >= '0' && b <= '9') {
                    num = num * 10 + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public int readByte() {
            if (bufferLen == -1) {
                throw new InputMismatchException();
            }
            if (bufferPtr >= bufferLen) {
                bufferPtr = 0;
                try {
                    bufferLen = inputStream.read(buffer);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (bufferLen <= 0) {
                    return -1;
                }
            }
            return buffer[bufferPtr++];
        }

        public char readChar() {
            return (char) skip();
        }

        private int skip() {
            int b;
            while ((b = readByte()) != -1 && isSpaceChar(b));
            return b;
        }

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

        @Override
        public void close() throws Exception {
            inputStream.close();
            bufferPtr = bufferLen;
        }
    }

    private static class Tuple {
        public static <A, B> Tuple2<A, B> of(A first, B second) {
            return new Tuple2<>(first, second);
        }

        public static <A extends Comparable<A>, B extends Comparable<B>> Tuple2<A, B> of(A first, B second) {
            return new ComparableTuple2<>(first, second);
        }

        public static <A, B, C> Tuple3<A, B, C> of(A first, B second, C third) {
            return new Tuple3<>(first, second, third);
        }

        public static <A extends Comparable<A>, B extends Comparable<B>, C extends Comparable<C>> Tuple3<A, B, C> of(A first, B second, C third) {
            return new ComparableTuple3<>(first, second, third);
        }

        private static class Tuple2<A, B> extends Tuple {
            public final A first;
            public final B second;

            private Tuple2(A first, B second) {
                this.first = first;
                this.second = second;
            }

            @Override
            public String toString() {
                return "(" + first + ", " + second + ")";
            }
        }

        private static class Tuple3<A, B, C> extends Tuple2<A, B> {
            public final C third;

            private Tuple3(A first, B second, C third) {
                super(first, second);
                this.third = third;
            }

            @Override
            public String toString() {
                return "(" + first + ", " + second + ", " + third + ")";
            }
        }

        private static class ComparableTuple2<A extends Comparable<A>, B extends Comparable<B>> extends Tuple2<A, B> implements Comparable<ComparableTuple2<A, B>> {
            private ComparableTuple2(A first, B second) {
                super(first, second);
            }

            @Override
            @SuppressWarnings("unchecked")
            public int compareTo(ComparableTuple2 that) {
                var res = first.compareTo((A) that.first);
                return res == 0 ? second.compareTo((B) that.second) : res;
            }
        }

        private static class ComparableTuple3<A extends Comparable<A>, B extends Comparable<B>, C extends Comparable<C>>
                extends Tuple3<A, B, C> implements Comparable<ComparableTuple3<A, B, C>> {

            private ComparableTuple3(A first, B second, C third) {
                super(first, second, third);
            }

            @Override
            @SuppressWarnings("unchecked")
            public int compareTo(ComparableTuple3 that) {
                var firstR = first.compareTo((A) that.first);
                if (firstR == 0) {
                    var secondR = second.compareTo((B) that.second);
                    if (secondR == 0) {
                        return third.compareTo((C) that.third);
                    }
                    return secondR;
                }
                return firstR;
            }
        }
    }

    private static class Utils {
        private static final Random random = new Random(System.nanoTime());

        public static <T extends Comparable<T>> void sort(T[] array) {
            shuffle(array);
            Arrays.sort(array);
        }

        public static void sort(int[] array) {
            shuffle(array);
            Arrays.sort(array);
        }

        public static void sort(long[] array) {
            shuffle(array);
            Arrays.sort(array);
        }

        public static void sort(double[] array) {
            shuffle(array);
            Arrays.sort(array);
        }

        public static <T> void sort(T[] array, Comparator<T> comparator) {
            shuffle(array);
            Arrays.sort(array, comparator);
        }

        public static <T> void shuffle(T[] array) {
            for (int i = array.length - 1; i > 0; i--) {
                int index = random.nextInt(i + 1);
                T a = array[index];
                array[index] = array[i];
                array[i] = a;
            }
        }

        public static void shuffle(int[] array) {
            for (int i = array.length - 1; i > 0; i--) {
                int index = random.nextInt(i + 1);
                int a = array[index];
                array[index] = array[i];
                array[i] = a;
            }
        }

        public static void shuffle(long[] array) {
            for (int i = array.length - 1; i > 0; i--) {
                int index = random.nextInt(i + 1);
                long a = array[index];
                array[index] = array[i];
                array[i] = a;
            }
        }

        public static void shuffle(double[] array) {
            for (int i = array.length - 1; i > 0; i--) {
                int index = random.nextInt(i + 1);
                double a = array[index];
                array[index] = array[i];
                array[i] = a;
            }
        }

        public static <T extends Comparable<T>> void sort(List<T> list) {
            Collections.shuffle(list);
            Collections.sort(list);
        }

        public static <T> void sort(List<T> list, Comparator<T> comparator) {
            Collections.shuffle(list);
            list.sort(comparator);
        }

        public static int randomInt(int fromIncluded, int toExcluded) {
            return fromIncluded + random.nextInt(toExcluded - fromIncluded);
        }
    }
}


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

import java.util.*;

import java.io.*;

public class A {

	static class Pair {

		int x;

		int y;

		public Pair(int x, int y) {

			this.x = x;

			this.y = y;

		}

	}

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

		Scanner sc = new Scanner(System.in);

		StringBuilder str = new StringBuilder();

		int t = sc.nextInt();

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

			int n = sc.nextInt();

			int[] arr = new int[n];

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

				arr[i] = sc.nextInt();

			boolean ok = false;

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

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

				if (map.containsKey(arr[i])) {

					if (i - map.get(arr[i]) > 1)

						ok = true;

				} else

					map.put(arr[i], i);

			}

			if (ok)

				str.append("YES" + "\n");

			else

				str.append("NO" + "\n");

		}

		System.out.println(str);

		sc.close();

	}

}


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.

import java.io.*;

import java.math.BigInteger;

import java.util.*;

public class Main {

    static int MOD = 1000000007;

    // After writing solution, quick scan for:

    //   array out of bounds

    //   special cases e.g. n=1?

    //   npe, particularly in maps

    //

    // Big numbers arithmetic bugs:

    //   int overflow

    //   sorting, or taking max, after MOD

    void solve() throws IOException {

        int n = ri();

        int[] a = ril(n);

        Node root = new Node();

        for (int ai : a) {

            Node curr = root;

            for (int b = 29; b >= 0; b--) {

                int bit = ((1 << b) & ai) > 0 ? 1 : 0;

                if (bit == 0) {

                    if (curr.zero == null) curr.zero = new Node();

                    curr = curr.zero;

                } else {

                    if (curr.one == null) curr.one = new Node();

                    curr = curr.one;

                }

            }

        }

        dfs(root, 29, 0);

        pw.println(ans);

    }

    // IMPORTANT

    // DID YOU CHECK THE COMMON MISTAKES ABOVE?

    int ans = Integer.MAX_VALUE;

    void dfs(Node curr, int b, int sofar) {

        if (b < 0) {

            ans = Math.min(ans, sofar);

            return;

        }

        if (curr.zero == null) {

            dfs(curr.one, b-1, sofar);

        } else if (curr.one == null) {

            dfs(curr.zero, b-1, sofar);

        } else {

            sofar = sofar | (1 << b);

            dfs(curr.one, b-1, sofar);

            dfs(curr.zero, b-1, sofar);

        }

    }

    // Template code below

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

    PrintWriter pw = new PrintWriter(System.out);

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

        Main m = new Main();

        m.solve();

        m.close();

    }

    void close() throws IOException {

        pw.flush();

        pw.close();

        br.close();

    }

    int ri() throws IOException {

        return Integer.parseInt(br.readLine().trim());

    }

    long rl() throws IOException {

        return Long.parseLong(br.readLine().trim());

    }

    int[] ril(int n) throws IOException {

        int[] nums = new int[n];

        int c = 0;

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

            int sign = 1;

            c = br.read();

            int x = 0;

            if (c == '-') {

                sign = -1;

                c = br.read();

            }

            while (c >= '0' && c <= '9') {

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

                c = br.read();

            }

            nums[i] = x * sign;

        }

        while (c != '\n' && c != -1) c = br.read();

        return nums;

    }

    long[] rll(int n) throws IOException {

        long[] nums = new long[n];

        int c = 0;

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

            int sign = 1;

            c = br.read();

            long x = 0;

            if (c == '-') {

                sign = -1;

                c = br.read();

            }

            while (c >= '0' && c <= '9') {

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

                c = br.read();

            }

            nums[i] = x * sign;

        }

        while (c != '\n' && c != -1) c = br.read();

        return nums;

    }

    int[] rkil() throws IOException {

        int sign = 1;

        int c = br.read();

        int x = 0;

        if (c == '-') {

            sign = -1;

            c = br.read();

        }

        while (c >= '0' && c <= '9') {

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

            c = br.read();

        }

        return ril(x);

    }

    long[] rkll() throws IOException {

        int sign = 1;

        int c = br.read();

        int x = 0;

        if (c == '-') {

            sign = -1;

            c = br.read();

        }

        while (c >= '0' && c <= '9') {

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

            c = br.read();

        }

        return rll(x);

    }

    char[] rs() throws IOException {

        return br.readLine().toCharArray();

    }

    void sort(int[] A) {

        Random r = new Random();

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

            int j = r.nextInt(i+1);

            int temp = A[i];

            A[i] = A[j];

            A[j] = temp;

        }

        Arrays.sort(A);

    }

    void printDouble(double d) {

        pw.printf("%.16f", d);

    }

}

class Node {

    Node zero;

    Node one;

}


C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.BufferedOutputStream;

import java.io.UncheckedIOException;

import java.nio.charset.Charset;

import java.util.StringTokenizer;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.BufferedReader;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author mikit

 */

public class Main {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        LightScanner in = new LightScanner(inputStream);

        LightWriter out = new LightWriter(outputStream);

        C1MadhouseEasyVersion solver = new C1MadhouseEasyVersion();

        solver.solve(1, in, out);

        out.close();

    }

    static class C1MadhouseEasyVersion {

        public void solve(int testNumber, LightScanner in, LightWriter out) {

            // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);

            out.enableAutoFlush();

            int m = in.ints(), n = (m + 1) / 2;

            char[] p1 = guess(in, out, 1, n);

            char[] ans = new char[m];

            if (n == 1) {

                ans[0] = p1[0];

            } else {

                char[] p2 = guess(in, out, 1, n - 1);

                int[] cnt = new int[26];

                for (int i = 0; i < n; i++) cnt[p1[i] - 'a']++;

                for (int i = 0; i < n - 1; i++) cnt[p2[i] - 'a']--;

                for (int i = 0; i < 26; i++) if (cnt[i] > 0) ans[n - 1] = (char) (i + 'a');

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

                    if (ans[n - i - 1] != p1[n - i - 1]) ArrayUtil.swap(p1, i, n - i - 1);

                    ans[i] = p1[i];

                    if (ans[i] != p2[i]) ArrayUtil.swap(p2, i, n - i - 2);

                    ans[n - i - 2] = p2[n - i - 2];

                }

            }

            char[] p3 = guess(in, out, 1, m);

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

                if (p3[i] != ans[i]) ArrayUtil.swap(p3, i, m - i - 1);

            }

            out.ans('!').ans(String.valueOf(p3)).ln();

        }

        private static char[] guess(LightScanner in, LightWriter out, int from, int to) {

            int n = to - from + 1;

            if (n == 0) return new char[0];

            out.ans('?').ans(from).ans(to).ln();

            int n2 = (n + 1) / 2;

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

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

                char[] s = in.string().toCharArray();

                if (s.length < n2) continue;

                for (char c : s) cnt[c - 'a'][s.length]++;

            }

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

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

                    cnt[j][i] -= cnt[j][i + 1];

                }

            }

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

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

                    cnt[j][i] -= cnt[j][i - 1];

                }

            }

            char[] ans = new char[n];

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

                int ref = Math.max(n - i, i + 1);

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

                    if (cnt[j][ref] > 0) {

                        cnt[j][ref]--;

                        ans[i] = (char) ('a' + j);

                        break;

                    }

                }

            }

            return ans;

        }

    }

    static class LightScanner {

        private BufferedReader reader = null;

        private StringTokenizer tokenizer = null;

        public LightScanner(InputStream in) {

            reader = new BufferedReader(new InputStreamReader(in));

        }

        public String string() {

            if (tokenizer == null || !tokenizer.hasMoreTokens()) {

                try {

                    tokenizer = new StringTokenizer(reader.readLine());

                } catch (IOException e) {

                    throw new UncheckedIOException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public int ints() {

            return Integer.parseInt(string());

        }

    }

    static class LightWriter implements AutoCloseable {

        private final Writer out;

        private boolean autoflush = false;

        private boolean breaked = true;

        public LightWriter(Writer out) {

            this.out = out;

        }

        public LightWriter(OutputStream out) {

            this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));

        }

        public void enableAutoFlush() {

            autoflush = true;

        }

        public LightWriter print(char c) {

            try {

                out.write(c);

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter print(String s) {

            try {

                out.write(s, 0, s.length());

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter ans(char c) {

            if (!breaked) {

                print(' ');

            }

            return print(c);

        }

        public LightWriter ans(String s) {

            if (!breaked) {

                print(' ');

            }

            return print(s);

        }

        public LightWriter ans(int i) {

            return ans(Integer.toString(i));

        }

        public LightWriter ln() {

            print(System.lineSeparator());

            breaked = true;

            if (autoflush) {

                try {

                    out.flush();

                } catch (IOException ex) {

                    throw new UncheckedIOException(ex);

                }

            }

            return this;

        }

        public void close() {

            try {

                out.close();

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

        }

    }

    static final class ArrayUtil {

        private ArrayUtil() {

        }

        public static void swap(char[] a, int x, int y) {

            char t = a[x];

            a[x] = a[y];

            a[y] = t;

        }

    }

}