B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.ArrayDeque;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Comparator;

import java.util.HashMap;

import java.util.Objects;

import java.util.Queue;

import java.util.StringTokenizer;

import java.util.function.BiFunction;

import java.util.function.Function;

public class Main {

    static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);

    static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> {

        x.addAll(y);

        return x;

    };

    static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);

    static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);

    static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(x -> x.first + x.second);

    static long MOD = 1_000_000_000 + 7;

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

        long startTime = System.nanoTime();

        int t = in.nextInt();

        while (t-- > 0) {

            solve();

        }

        long endTime = System.nanoTime();

        err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");

        exit(0);

    }

    static void solve() {

        int n = in.nextInt();

        int[] data = ArrayUtils.reverse(ArrayUtils.MergeSort(in.readAllInts(n)));

        for(int a:data){

            out.print(a + " ");

        }

        out.println("");

    }

    static void debug(Object... args) {

        for (Object a : args) {

            out.println(a);

        }

    }

    static int dist(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {

        return Math.abs(a.first - b.first) + Math.abs(a.second - b.second);

    }

    static void y() {

        out.println("YES");

    }

    static void n() {

        out.println("NO");

    }

    static int[] stringToArray(String s) {

        return s.chars().map(x -> Character.getNumericValue(x)).toArray();

    }

    static <T> T min(T a, T b, Comparator<T> C) {

        if (C.compare(a, b) <= 0) {

            return a;

        }

        return b;

    }

    static <T> T max(T a, T b, Comparator<T> C) {

        if (C.compare(a, b) >= 0) {

            return a;

        }

        return b;

    }

    static void fail() {

        out.println("-1");

    }

    static class Pair<T, R> {

        public T first;

        public R second;

        public Pair(T first, R second) {

            this.first = first;

            this.second = second;

        }

        @Override

        public boolean equals(final Object o) {

            if (this == o) {

                return true;

            }

            if (o == null || getClass() != o.getClass()) {

                return false;

            }

            final Pair<?, ?> pair = (Pair<?, ?>) o;

            return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);

        }

        @Override

        public int hashCode() {

            return Objects.hash(first, second);

        }

        @Override

        public String toString() {

            return "Pair{" + "a=" + first + ", b=" + second + '}';

        }

        public T getFirst() {

            return first;

        }

        public R getSecond() {

            return second;

        }

    }

    static <T, R> Pair<T, R> make_pair(T a, R b) {

        return new Pair<>(a, b);

    }

    static long mod_inverse(long a, long m) {

        Number x = new Number(0);

        Number y = new Number(0);

        extended_gcd(a, m, x, y);

        return (m + x.v % m) % m;

    }

    static long extended_gcd(long a, long b, Number x, Number y) {

        long d = a;

        if (b != 0) {

            d = extended_gcd(b, a % b, y, x);

            y.v -= (a / b) * x.v;

        } else {

            x.v = 1;

            y.v = 0;

        }

        return d;

    }

    static class Number {

        long v = 0;

        public Number(long v) {

            this.v = v;

        }

    }

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

        return lcm(a, lcm(b, c));

    }

    static long lcm(long a, long b) {

        long p = 1L * a * b;

        return p / gcd(a, b);

    }

    static long gcd(long a, long b) {

        while (b != 0) {

            long t = b;

            b = a % b;

            a = t;

        }

        return a;

    }

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

        return gcd(a, gcd(b, c));

    }

    static class ArrayUtils {

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

            int temp = a[i];

            a[i] = a[j];

            a[j] = temp;

        }

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

            char temp = a[i];

            a[i] = a[j];

            a[j] = temp;

        }

        static void print(char[] a) {

            for (char c : a) {

                out.print(c);

            }

            out.println("");

        }

        static int[] reverse(int[] data) {

            int[] p = new int[data.length];

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

                p[i] = data[j];

            }

            return p;

        }

        static void prefixSum(long[] data) {

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

                data[i] += data[i - 1];

            }

        }

        static void prefixSum(int[] data) {

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

                data[i] += data[i - 1];

            }

        }

        static long[] reverse(long[] data) {

            long[] p = new long[data.length];

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

                p[i] = data[j];

            }

            return p;

        }

        static char[] reverse(char[] data) {

            char[] p = new char[data.length];

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

                p[i] = data[j];

            }

            return p;

        }

        static int[] MergeSort(int[] A) {

            if (A.length > 1) {

                int q = A.length / 2;

                int[] left = new int[q];

                int[] right = new int[A.length - q];

                System.arraycopy(A, 0, left, 0, q);

                System.arraycopy(A, q, right, 0, A.length - q);

                int[] left_sorted = MergeSort(left);

                int[] right_sorted = MergeSort(right);

                return Merge(left_sorted, right_sorted);

            } else {

                return A;

            }

        }

        static int[] Merge(int[] left, int[] right) {

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

            int i = 0;

            int j = 0;

            for (int k = 0; k < A.length; k++) {

                // To handle left becoming empty

                if (i == left.length && j < right.length) {

                    A[k] = right[j];

                    j++;

                    continue;

                }

                // To handle right becoming empty

                if (j == right.length && i < left.length) {

                    A[k] = left[i];

                    i++;

                    continue;

                }

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

                    A[k] = left[i];

                    i++;

                } else {

                    A[k] = right[j];

                    j++;

                }

            }

            return A;

        }

        static long[] MergeSort(long[] A) {

            if (A.length > 1) {

                int q = A.length / 2;

                long[] left = new long[q];

                long[] right = new long[A.length - q];

                System.arraycopy(A, 0, left, 0, q);

                System.arraycopy(A, q, right, 0, A.length - q);

                long[] left_sorted = MergeSort(left);

                long[] right_sorted = MergeSort(right);

                return Merge(left_sorted, right_sorted);

            } else {

                return A;

            }

        }

        static long[] Merge(long[] left, long[] right) {

            long[] A = new long[left.length + right.length];

            int i = 0;

            int j = 0;

            for (int k = 0; k < A.length; k++) {

                // To handle left becoming empty

                if (i == left.length && j < right.length) {

                    A[k] = right[j];

                    j++;

                    continue;

                }

                // To handle right becoming empty

                if (j == right.length && i < left.length) {

                    A[k] = left[i];

                    i++;

                    continue;

                }

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

                    A[k] = left[i];

                    i++;

                } else {

                    A[k] = right[j];

                    j++;

                }

            }

            return A;

        }

        static int upper_bound(int[] data, int num, int start) {

            int low = start;

            int high = data.length - 1;

            int mid = 0;

            int ans = -1;

            while (low <= high) {

                mid = (low + high) / 2;

                if (data[mid] < num) {

                    low = mid + 1;

                } else if (data[mid] >= num) {

                    high = mid - 1;

                    ans = mid;

                }

            }

            if (ans == -1) {

                return 100000000;

            }

            return data[ans];

        }

        static int lower_bound(int[] data, int num, int start) {

            int low = start;

            int high = data.length - 1;

            int mid = 0;

            int ans = -1;

            while (low <= high) {

                mid = (low + high) / 2;

                if (data[mid] <= num) {

                    low = mid + 1;

                    ans = mid;

                } else if (data[mid] > num) {

                    high = mid - 1;

                }

            }

            if (ans == -1) {

                return 100000000;

            }

            return data[ans];

        }

    }

    static boolean[] primeSieve(int n) {

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

        Arrays.fill(primes, true);

        primes[0] = false;

        primes[1] = false;

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

            if (primes[i]) {

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

                    primes[j] = false;

                }

            }

        }

        return primes;

    }

    // Iterative Version

    static HashMap<Integer, Boolean> subsets_sum_iter(int[] data) {

        HashMap<Integer, Boolean> temp = new HashMap<Integer, Boolean>();

        temp.put(data[0], true);

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

            HashMap<Integer, Boolean> t1 = new HashMap<Integer, Boolean>(temp);

            t1.put(data[i], true);

            for (int j : temp.keySet()) {

                t1.put(j + data[i], true);

            }

            temp = t1;

        }

        return temp;

    }

    static HashMap<Integer, Integer> subsets_sum_count(int[] data) {

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

        temp.put(data[0], 1);

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

            HashMap<Integer, Integer> t1 = new HashMap<>(temp);

            t1.merge(data[i], 1, ADD);

            for (int j : temp.keySet()) {

                t1.merge(j + data[i], temp.get(j) + 1, ADD);

            }

            temp = t1;

        }

        return temp;

    }

    static class Graph {

        ArrayList<Integer>[] g;

        boolean[] visited;

        ArrayList<Integer>[] graph(int n) {

            g = new ArrayList[n];

            visited = new boolean[n];

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

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

            }

            return g;

        }

        void BFS(int s) {

            Queue<Integer> Q = new ArrayDeque<>();

            visited[s] = true;

            Q.add(s);

            while (!Q.isEmpty()) {

                int v = Q.poll();

                for (int a : g[v]) {

                    if (!visited[a]) {

                        visited[a] = true;

                        Q.add(a);

                    }

                }

            }

        }

    }

    static class SparseTable {

        int[] log;

        int[][] st;

        public SparseTable(int n, int k, int[] data, BiFunction<Integer, Integer, Integer> f) {

            log = new int[n + 1];

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

            log[1] = 0;

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

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

            }

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

                st[i][0] = data[i];

            }

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

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

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

        }

        public int query(int L, int R, BiFunction<Integer, Integer, Integer> f) {

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

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

        }

    }

    static class InputReader {

        public BufferedReader reader;

        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {

            reader = new BufferedReader(new InputStreamReader(stream), 2048);

            tokenizer = null;

        }

        public String next() {

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

                try {

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

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public int[] readAllInts(int n) {

            int[] p = new int[n];

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

                p[i] = in.nextInt();

            }

            return p;

        }

        public int[] readAllInts(int n, int s) {

            int[] p = new int[n + s];

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

                p[i] = in.nextInt();

            }

            return p;

        }

        public long[] readAllLongs(int n) {

            long[] p = new long[n];

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

                p[i] = in.nextLong();

            }

            return p;

        }

        public long[] readAllLongs(int n, int s) {

            long[] p = new long[n + s];

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

                p[i] = in.nextLong();

            }

            return p;

        }

        public double nextDouble() {

            return Double.parseDouble(next());

        }

    }

    static void exit(int a) {

        out.close();

        err.close();

        System.exit(a);

    }

    static InputStream inputStream = System.in;

    static OutputStream outputStream = System.out;

    static OutputStream errStream = System.err;

    static InputReader in = new InputReader(inputStream);

    static PrintWriter out = new PrintWriter(outputStream);

    static PrintWriter err = new PrintWriter(errStream);

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

}


B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows:  However, the results of the Olympiad could also look like this:  In the first case Nikolay would have taken first place, and in the second — third place.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
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
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        BDifferentRules solver = new BDifferentRules();
        int testCount = Integer.parseInt(in.next());
        for (int i = 1; i <= testCount; i++)
            solver.solve(i, in, out);
        out.close();
    }

    static class BDifferentRules {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt(), x = in.nextInt(), y = in.nextInt();
//        out.println(x-1-Math.min(x-1,n-y-1),y-1-Math.min(y-1,n-x-1));
            out.println(Math.max(x - 1 - Math.min(x - 1, Math.max(0, n - y - 1)), y - 1 - Math.min(y - 1, Math.max(0, n - x - 1))) + 1, (n - Math.min(n - x - Math.min(n - x, y - 1), n - y - Math.min(n - y, x - 1))));
        }

    }

    static class InputReader {
        BufferedReader reader;
        StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

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

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }
}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class A_ConnerR_and_the_A_R_C_Markland_N {

    public static void main(String[] args) {

        OutputStream outputStream = System.out;

        PrintWriter out = new PrintWriter(outputStream);

        FastReader f = new FastReader();

        int t = f.nextInt();

        while(t-- > 0){

            solve(f, out);

        }

        out.close();

    }

    public static void solve(FastReader f, PrintWriter out) {

        int n = f.nextInt();

        int s = f.nextInt();

        int k = f.nextInt();

        HashSet<Integer> hs = new HashSet<>();

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

            hs.add(f.nextInt());

        }

        int ans = 0;

        int i = s;

        int j = s;

        while(hs.contains(i) && hs.contains(j)) {

            ans++;

            if(i > 1) {

                i--;

            }

            if(j < n) {

                j++;

            }

        }

        out.println(ans);

    }

    public static void sort(int arr[]) {

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

        for(int i: arr) {

            al.add(i);

        }

        Collections.sort(al);

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

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

        }

    }

    public static void allDivisors(int n) {

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

            if(n%i == 0) {

                System.out.println(i + " ");

                if(i != n/i) {

                    System.out.println(n/i + " ");

                }

            }

        }

    }

    public static boolean isPrime(int n) {

        if(n < 1) return false;

        if(n == 2 || n == 3) return true;

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

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

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

                return false;

            }

        }

        return true;

    }

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

        int dividend = a > b ? a : b;

        int divisor =  a < b ? a : b;

        while(divisor > 0) {

            int reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

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

        int lcm = gcd(a, b);

        int hcf = (a * b) / lcm;

        return hcf;

    }

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

                try {

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

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextArray(int n) {

            int[] a = new int[n];

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

                a[i] = nextInt();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

---------                           ---------     ---------     ----------

  0  NUL (null)                      32  SPACE     64  @         96  `

  1  SOH (start of heading)          33  !         65  A         97  a

  2  STX (start of text)             34  "         66  B         98  b

  3  ETX (end of text)               35  #         67  C         99  c

  4  EOT (end of transmission)       36  $         68  D        100  d

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

  9  TAB (horizontal tab)            41  )         73  I        105  i

 10  LF  (NL line feed, new line)    42  *         74  J        106  j

 11  VT  (vertical tab)              43  +         75  K        107  k

 12  FF  (NP form feed, new page)    44  ,         76  L        108  l

 13  CR  (carriage return)           45  -         77  M        109  m

 14  SO  (shift out)                 46  .         78  N        110  n

 15  SI  (shift in)                  47  /         79  O        111  o

 16  DLE (data link escape)          48  0         80  P        112  p

 17  DC1 (device control 1)          49  1         81  Q        113  q

 18  DC2 (device control 2)          50  2         82  R        114  r

 19  DC3 (device control 3)          51  3         83  S        115  s

 20  DC4 (device control 4)          52  4         84  T        116  t

 21  NAK (negative acknowledge)      53  5         85  U        117  u

 22  SYN (synchronous idle)          54  6         86  V        118  v

 23  ETB (end of trans. block)       55  7         87  W        119  w

 24  CAN (cancel)                    56  8         88  X        120  x

 25  EM  (end of medium)             57  9         89  Y        121  y

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

 28  FS  (file separator)            60  <         92  \        124  |

 29  GS  (group separator)           61  =         93  ]        125  }

 30  RS  (record separator)          62  >         94  ^        126  ~

 31  US  (unit separator)            63  ?         95  _        127  DEL

 */


B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.

import java.util.*;

public class gh{

    public static void main(String[] args)

    {

        Scanner sc=new Scanner(System.in);

        int t=sc.nextInt();

        while(t-->0)

        {

            int n=sc.nextInt();

            int[] ar=new int[2*n];

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

            ar[i]=sc.nextInt();

            Arrays.sort(ar);

            int min=Integer.MAX_VALUE;

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

            {

                min=Math.min(min,ar[n]-ar[i]);

            }

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

            {

                min=Math.min(min,ar[i]-ar[n-1]);

            }

            System.out.println(min);

        }

    }

}


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

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int ttt=1;

		ttt=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

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

			int n=f.nextInt();

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

			int num = n, last = 0;

			int[] ans=new int[n];

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

			{

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

				{

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

						ans[j] = num--;

					last = i + 1;

				}

			}

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

			System.out.println();

			ans=new int[n];

			num = 1;

			last = 0;

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

			{

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

				{

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

						ans[j] = num++;

					last = i + 1;

				}

			}

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

			System.out.println();

		}

		out.close();

	}

	static void sort(int[] p) {

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

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

        Collections.sort(q);

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

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}


D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

//package com.company;

import java.io.*;

import java.util.*;

public class Main {

    public static class Task {

        boolean insertVector(int[] base, int vector) {

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

                if ((vector & (1 << i)) == 0) continue;

                if ((base[i] & (1 << i)) == 0) {

                    base[i] = vector;

                    for (int j = i + 1; j < 5; j++) if (base[j] > 0 && (base[i] & (1 << j)) != 0) {

                        base[i] ^= base[j];

                    }

                    for (int j = i - 1; j >= 0; j--) if ((base[j] & (1 << i)) != 0) {

                        base[j] ^= base[i];

                    }

                    return true;

                }

                vector ^= base[i];

            }

            return false;

        }

        public class ArrayHash {

            int[] array;

            public ArrayHash(int[] array) {

                this.array = Arrays.copyOf(array, array.length);

            }

            @Override

            public boolean equals(Object o) {

                if (this == o) return true;

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

                ArrayHash arrayHash = (ArrayHash) o;

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

            }

            @Override

            public int hashCode() {

                return Arrays.hashCode(array);

            }

        }

        public class DisjointSet {

            int[] arr;

            public DisjointSet(int n) {

                arr = new int[n];

                Arrays.fill(arr, -1);

            }

            int find(int x) {

                if (arr[x] < 0) return x;

                return arr[x] = find(arr[x]);

            }

            boolean union(int a, int b) {

                int ra = find(a), rb = find(b);

                if (ra == rb) return false;

                arr[ra] = rb;

                return true;

            }

        }

        public class Pair {

            int a, b;

            public Pair(int a, int b) {

                this.a = a;

                this.b = b;

            }

        }

        public class Triple {

            int a, b, c;

            public Triple(int a, int b, int c) {

                this.a = a;

                this.b = b;

                this.c = c;

            }

            public Triple(int[] z) {

                this.a = z[0];

                this.b = z[1];

                this.c = z[2];

            }

        }

        int S = 374;

        int[] xorValues;

        int[] root;

        int[] parent;

        int[][] inputEdges;

        int[][] dpVal;

        boolean[] off;

        List<Triple> additionalEdges;

        List<Pair>[] treeEdges;

        List<Integer>[] treeBasis;

        int[] treeBasisIndex;

        Map<ArrayHash, Integer> basisToIndex;

        List<ArrayHash> indexToBasis;

        int[][] basisTransition = new int[S][S];

        void dfs(int u, int p, int r, int val) {

            root[u] = r;

            parent[u] = p;

            xorValues[u] = val;

            for (Pair v: treeEdges[u]) if (v.a != p) {

                dfs(v.a, u, r, val ^ v.b);

            }

        }

        int mod = 1_000_000_007;

        int add(int a, int b) {

            int c = a + b;

            if (c >= mod) return c - mod;

            return c;

        }

        int getIndexOfBasis(int[] basis) {

            ArrayHash ar = new ArrayHash(basis);

            if (!basisToIndex.containsKey(ar)) {

                basisToIndex.put(ar, basisToIndex.size());

                indexToBasis.add(ar);

            }

            if (basisToIndex.size() > S) throw new RuntimeException();

            return basisToIndex.get(ar);

        }

        int merge(int basisIndex1, int basisIndex2) {

            if (basisTransition[basisIndex1][basisIndex2] == -2) {

                int[] basis1 = Arrays.copyOf(indexToBasis.get(basisIndex1).array, 5);

                int[] basis2 = Arrays.copyOf(indexToBasis.get(basisIndex2).array, 5);

                boolean valid = true;

                for (int b : basis2) {

                    if (b != 0) {

                        if (!insertVector(basis1, b)) {

                            valid = false;

                        }

                    }

                }

                if (valid) {

                    basisTransition[basisIndex1][basisIndex2] = basisTransition[basisIndex2][basisIndex1] = getIndexOfBasis(basis1);

                } else {

                    basisTransition[basisIndex1][basisIndex2] = basisTransition[basisIndex2][basisIndex1] = -1;

                }

            }

            return basisTransition[basisIndex1][basisIndex2];

        }

        public void solve(Scanner sc, PrintWriter pw) throws IOException {

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

                Arrays.fill(basisTransition[i], -2);

            }

            basisToIndex = new HashMap<>();

            indexToBasis = new ArrayList<>();

            int n = sc.nextInt();

            int m = sc.nextInt();

            xorValues = new int[n];

            root = new int[n];

            parent = new int[n];

            off = new boolean[n];

            Arrays.fill(off, true);

            treeEdges = new List[n];

            additionalEdges = new ArrayList<>();

            treeBasis = new List[n];

            treeBasisIndex = new int[n];

            getIndexOfBasis(new int[5]);

            DisjointSet djs = new DisjointSet(n);

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

                treeEdges[i] = new ArrayList<>();

                treeBasis[i] = new ArrayList<>();

            }

            inputEdges = new int[m][3];

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

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

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

                }

            }

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

                inputEdges[i][0]--;

                inputEdges[i][1]--;

                if (inputEdges[i][0] == 0 || inputEdges[i][1] == 0) {

                    djs.union(inputEdges[i][0], inputEdges[i][1]);

                    treeEdges[inputEdges[i][0]].add(new Pair(inputEdges[i][1], inputEdges[i][2]));

                    treeEdges[inputEdges[i][1]].add(new Pair(inputEdges[i][0], inputEdges[i][2]));

                }

            }

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

                if (inputEdges[i][0] != 0 && inputEdges[i][1] != 0) {

                    if (djs.union(inputEdges[i][0], inputEdges[i][1])) {

                        treeEdges[inputEdges[i][0]].add(new Pair(inputEdges[i][1], inputEdges[i][2]));

                        treeEdges[inputEdges[i][1]].add(new Pair(inputEdges[i][0], inputEdges[i][2]));

                    } else {

                        additionalEdges.add(new Triple(inputEdges[i]));

                    }

                }

            }

            for (Pair p: treeEdges[0]) {

                off[p.a] = false;

                dfs(p.a, 0, p.a, p.b);

            }

            List<Triple> pairedTrees = new ArrayList<>();

            for (Triple tri: additionalEdges) {

                int a = tri.a;

                int b = tri.b;

                if (root[a] != root[b]) {

                    if (a != root[a] || b != root[b]) throw new RuntimeException();

                    pairedTrees.add(tri);

                    // across

                } else {

                    int cycle = tri.c ^ xorValues[a] ^ xorValues[b];

                    treeBasis[root[a]].add(cycle);

                }

            }

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

            for (int i = 1; i < n; i++) if (root[i] == i) {

                int[] basis = new int[5];

                for (int cycle: treeBasis[i]) {

                    if (!insertVector(basis, cycle)) {

                        off[i] = true;

                    }

                }

                if (!off[i]) {

                    treeBasisIndex[i] = getIndexOfBasis(basis);

                }

            }

            for (Triple p: pairedTrees) {

                if (off[p.a] || off[p.b]) {

                    off[p.a] = off[p.b] = true;

                    continue;

                }

                off[p.a] = true;

                off[p.b] = true;

                int nr;

                if ((nr = merge(treeBasisIndex[p.a], treeBasisIndex[p.b])) != -1) {

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

                    int[] basis = Arrays.copyOf(indexToBasis.get(nr).array, 5);

                    choices.add(nr);

                    choices.add(nr);

                    if (insertVector(basis, p.c ^ xorValues[p.a] ^ xorValues[p.b])) {

                        choices.add(getIndexOfBasis(basis));

                    }

                    choicesForTree.add(choices);

                }

            }

            for (int i = 1; i < n; i++) if (root[i] == i && !off[i]) {

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

                choice.add(treeBasisIndex[i]);

                choicesForTree.add(choice);

            }

            dpVal = new int[2][S]; // \sum_{i=0}^5 {5 \choose i}_2

            dpVal[0][0] = 1;

            int cur = 0, next = 1;

            for (List<Integer> choices: choicesForTree) {

                System.arraycopy(dpVal[cur], 0, dpVal[next], 0, S);

                for (int choice: choices) {

                    for (int i = 0; i < S; i++) if (dpVal[cur][i] > 0) {

                        int nr;

                        if ((nr = merge(i, choice)) != -1) {

                            dpVal[next][nr] = add(dpVal[next][nr], dpVal[cur][i]);

                        }

                    }

                }

                cur ^= 1;

                next ^= 1;

            }

            int total = 0;

            for (int i = 0; i < S; i++) total = add(total, dpVal[cur][i]);

            pw.println(total);

        }

    }

    static long TIME_START, TIME_END;

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

        Scanner sc = new Scanner(System.in);

//        Scanner sc = new Scanner(new FileInputStream("input"));

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

//        PrintWriter pw = new PrintWriter(new FileOutputStream("input"));

        Runtime runtime = Runtime.getRuntime();

        long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();

        TIME_START = System.currentTimeMillis();

        Task t = new Task();

        t.solve(sc, pw);

        TIME_END = System.currentTimeMillis();

        long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();

        pw.close();

        System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);

        System.err.println("Time used: " + (TIME_END - TIME_START) + ".");

    }

    static class Scanner {

        StringTokenizer st;

        BufferedReader br;

        public Scanner(InputStream s) {

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

        }

        public Scanner(FileReader s) throws FileNotFoundException {

            br = new BufferedReader(s);

        }

        public String next() throws IOException {

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

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

            return st.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public String nextLine() throws IOException {

            return br.readLine();

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public boolean ready() throws IOException {

            return br.ready();

        }

    }

}


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.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;

public class Main {
    static FastReader fastReader;
    static PrintWriter out;
    static int mod = 998244353;
    public static void main(String[] args) {
        fastReader = new FastReader();

//        int tt = 1;

        int tt = fastReader.nextInt();
        out = new PrintWriter(System.out);
        while(tt-- > 0) {
            long a = fastReader.nextLong();
            long m = fastReader.nextLong();
            long gcd = gcd(a,m);
            out.println(solve(m/gcd));
        }
        out.close();
    }

    private static long solve(long x) {
        long temp = x;
        for(long i = 2; i*i <=x ; i++){
            if(x% i == 0){
                temp -=(temp/i);
                while(x % i == 0){
                    x/=i;
                }

            }
        }
        if(x > 1){
            temp -=(temp/x);
        }
        return temp;
    }

    public static class Pair{
        int val;
        int index;

        public Pair(int val, int index) {
            this.val = val;
            this.index = index;
        }

        @Override
        public String toString() {
            return "Pair{" +
                    "val=" + val +
                    ", index=" + index +
                    '}';
        }
    }

    // constants
    static final int IBIG = 1000000007;
    static final int IMAX = 2147483647;
    static final long LMAX = 9223372036854775807L;
    static Random __r = new Random();
    static int[][] direction = new int[][]{{-1,-1}, {-1,0}, {-1,1},  {0,1}, {1,1},  {1,0},  {1,-1},  {0, -1}};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return nonPrimes;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

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

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


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import java.util.*;
import java.io.*;
public class NewYearAndNaming{
    public static void main(String[] args){
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        int m = scn.nextInt();

        String[] pre = new String[n];
        String[] suff = new String[m];

        for(int i=0;i<n;i++){
            pre[i] = scn.next();
        }
        for(int j=0;j<m;j++){
            suff[j] = scn.next();
        }

        int t = scn.nextInt();

        while(t>0){
            int year = scn.nextInt();
            int preidx = (year-1)%n;
            int suffidx = (year-1)%m;

            String name = pre[preidx] + suff[suffidx];
            System.out.println(name);
            t--;
        }
    }
}


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

////package com.company;

import com.sun.source.tree.ArrayAccessTree;

import javax.swing.*;

import java.beans.IntrospectionException;

import java.math.BigInteger;

import java.util.*;

import java.io.*;

public class Main {

    static class pair implements Comparable<pair> {

        long a = 0;

        long b = 0;

        // int cnt;

        pair(long b, long a) {

            this.a = b;

            this.b = a;

            // cnt = x;

        }

        @Override

        public int compareTo(pair o) {

            if(this.a != o.a)

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

            else

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

        }

//        public boolean equals(Object o) {

//            if (o instanceof pair) {

//                pair p = (pair) o;

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

//            }

//            return false;

//        }

//

//        public int hashCode() {

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

//        }

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

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

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

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

        }

        public void prlong(Object object) throws IOException {

            bw.append("" + object);

        }

        public void prlongln(Object object) throws IOException {

            prlong(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

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

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    //HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS

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

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

//        int b = 0;

//        long h = 1;

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

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

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

//            if(b<=k){

//                set.add(h);

//            }

//        }

//    }

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

    //dsu

    static int[] par, rank;

    public static void dsu(int n) {

        par = new int[n];

        rank = new int[n];

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

            par[i] = i;

            rank[i] = 1;

        }

    }

    static int find(int u) {

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

    }

    static void union(int u, int v) {

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

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

            par[b] = a;

            rank[a] += rank[b];

        }

    }

    static void disunion(int u, int v) {

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

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

            par[a] = -1;

        }

    }

    static class Calc_nCr {

        private final long[] fact;

        private final long[] invfact;

        private final int p;

        Calc_nCr(int n, int prime) {

            fact = new long[n + 5];

            invfact = new long[n + 5];

            p = prime;

            fact[0] = 1;

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

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

            }

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

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

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

            }

        }

        private long nCr(int n, int r) {

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

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

        }

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

            long result = 1;

            while (b > 0) {

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

                    result = (result * a) % mod;

                }

                a = (a * a) % mod;

                b >>= 1;

            }

            return result;

        }

    }

    static void sort(long[] a ) {

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

        for(long i: a) {

            l.add(i);

        }

        Collections.sort(l);

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

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

        }

    }

    public static void main(String[] args) {

        try {

            FastReader in = new FastReader();

            FastWriter out = new FastWriter();

            int mx=10000000;

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

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

                isPrime[i] = true;

            }

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

                primeDiv[i]=i;

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

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

                if (isPrime[(int)i]) {

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

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

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

                        }

                        isPrime[(int)j] = false;

                    }

                }

            }

//            System.out.println(

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

            int testCases=1;

//            int n =in.nextInt();

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

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

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

//

//

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

//            Collections.sort(ans);

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

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

            fl:

            while (testCases-- > 0) {

long x =in.nextLong();

long ans =x;

for(long i =1;i*i<x;i++)

{

    if(x%i==0&&gcd(x/i,i)==1)

    {

        ans=Math.min(ans,x/i);

    }

}

                System.out.println(x/ans+" "+ans);

            }

            out.close();

        } catch (Exception e) {

            return;

        }

    }

    static long comb(int r,int n)

    {

        long result;

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

        return result;

    }

    static long factorial(int n) {

        int c;

        long result = 1;

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

            result = result*c;

        return result;

    }

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

//        String temp = str + '/';

//        str = reverse(str);

//        temp += str;

        String temp =str;

        int n = temp.length();

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

        {

            int len = lps[i - 1];

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

                    temp.charAt(i))

            {

                len = lps[len - 1];

            }

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

            {

                len++;

            }

            lps[i] = len;

        }

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

    }

    static String reverse(String input)

    {

        char[] a = input.toCharArray();

        int l, r = a.length - 1;

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

        {

            char temp = a[l];

            a[l] = a[r];

            a[r] = temp;

        }

        return String.valueOf(a);

    }

}

/*

 *

 *　　┏┓　　　┏┓+ +

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

 *　┃　　　　　　　┃

 *　┃　　　━　　　┃ ++ + + +

 *   ████━████+

 *  ◥██◤　◥██◤ +

 *　┃　　　┻　　　┃

 *　┃　　　　　　　┃ + +

 *　┗━┓　　　┏━┛

 *　　　┃　　┃      JACKS PET FROM ANOTHER WORLD

 *　　　┃　　┃

 *　　　┃　 　 ┗━━━┓

 *　　　┃ 　　　　　　 ┣┓-------

 *　　  ┃ 　　　　　 　┏┛-------

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

 *　　　　┃┫┫　┃┫┫

 *　　　　┗┻┛　┗┻┛+ + + +

 */

//RULES

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

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

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

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


A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class P1299A {

    public static void main(String[] args) {

        FastScanner s = new FastScanner();
        int n = s.nextInt();
        int[] arr = s.readArray(n);
        for (int i = 31; i >= 0; i--) {
            int count = 0;
            for (int j : arr) {
                if ((j & (1 << i)) > 0) {
                    count++;
                }
            }
            if (count == 1) {
                for (int j = 0; j < n; j++) {
                    if ((arr[j] & (1 << i)) > 0) {
                        int temp = arr[j];
                        arr[j] = arr[0];
                        arr[0] = temp;
                    }
                }
                break;
            }
        }
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < n; i++) {
            ans.append(arr[i]);
            if (i != n - 1) {
                ans.append(" ");
            }
        }
        System.out.println(ans);

    }

    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }
    }

}


G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:  if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second;  use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.

import java.io.*;

import java.util.*;

public class Main{

	static int[][]children;

	static boolean[]S;

	static int[]smaller,ans;

	static int counter;

	static void dfs(int i) {

		smaller[i]=counter;

		if(S[i])counter++;

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

			if(children[i][c]!=0) {

				dfs(children[i][c]);

			}

		}

	}

	static void dfs2(int i,int append,int autoC) {

		if(S[i]) {

			ans[i]=Math.min(append, autoC);

		}

		else {

			ans[i]=append;

		}

		if(autoC>append+1) {

			autoC=append+1;

		}

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

			int nxt=children[i][c];

			if(nxt!=0) {

				dfs2(nxt, ans[i]+1, autoC+smaller[nxt]-smaller[i]);

			}

		}

	}

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

		MScanner sc=new MScanner(System.in);

		PrintWriter pw=new PrintWriter(System.out);

		int n=sc.nextInt();

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

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

			int par=sc.nextInt();char c=sc.nextChar();

			children[par][c-'a']=i;

		}

		S=new boolean[n+1];

		int k=sc.nextInt();

		int[]ks=new int[k];

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

			ks[i]=sc.nextInt();

			S[ks[i]]=true;

		}

		smaller=new int[n+1];

		dfs(0);

		ans=new int[n+1];

		dfs2(0, 0, 1);

		for(int i=0;i<k;i++)pw.println(ans[ks[i]]);

		pw.flush();

	}

	static class MScanner {

		StringTokenizer st;

		BufferedReader br;

		public MScanner(InputStream system) {

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

		}

		public MScanner(String file) throws Exception {

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

		}

		public String next() throws IOException {

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

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

			return st.nextToken();

		}

		public int[] takearr(int n) throws IOException {

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

	        return in;

		}

		public long[] takearrl(int n) throws IOException {

	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();

	        return in;

		}

		public Integer[] takearrobj(int n) throws IOException {

	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();

	        return in;

		}

		public Long[] takearrlobj(int n) throws IOException {

	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();

	        return in;

		}

		public String nextLine() throws IOException {

			return br.readLine();

		}

		public int nextInt() throws IOException {

			return Integer.parseInt(next());

		}

		public double nextDouble() throws IOException {

			return Double.parseDouble(next());

		}

		public char nextChar() throws IOException {

			return next().charAt(0);

		}

		public Long nextLong() throws IOException {

			return Long.parseLong(next());

		}

		public boolean ready() throws IOException {

			return br.ready();

		}

		public void waitForInput() throws InterruptedException {

			Thread.sleep(3000);

		}

	}

}


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

Welcome to GDB Online.

GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,

C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.

Code, Compile, Run and Debug online from anywhere in world.

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

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

Welcome to GDB Online.

GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,

C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.

Code, Compile, Run and Debug online from anywhere in world.

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

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

Welcome to GDB Online.

GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,

C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.

Code, Compile, Run and Debug online from anywhere in world.

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

/* package codechef; // don't place package name! */

import java.util.*;

import java.lang.*;

import java.io.*;

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

public class Main

{

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

	{

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		for(int p1=0;p1<t;p1++)

		{

		  int n=sc.nextInt();

		 int[] arr=new int[n];

		  int[] ans=new int[n];

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

		 {

		     arr[p]=sc.nextInt();

		 }

		 Arrays.sort(arr);

		 for(int p=n-1;p>=0;p--)

		 {

		      ans[n-1-p]=arr[p];

		 }

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

		      {

		          System.out.print(ans[j]+" ");

		      }

		      System.out.println(" ");

		  }

	}

}