D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class App {
    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(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') {
                    if (cnt != 0) {
                        break;
                    }
                    else {
                        continue;
                    }
                }
                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();
        }
    }

    public static void main(String[] args) throws Exception {
        Reader in = new Reader();
        int opt = in.nextInt();
        int[] arr1 = new int[opt];
        Integer[] arr2 = new Integer[opt];

        for(int i = 0; i < opt; i++) {
            arr1[i] = in.nextInt();
        }

        for(int i = 0; i < opt; i++) {
            arr2[i] = arr1[i] - in.nextInt();
        }
        Arrays.sort(arr2);

        long cnt = 0;
        int right = opt - 1;
        int left = 0;
        while(arr2[right] > 0 && left < right) {
            if(arr2[right] + arr2[left] > 0) {
                cnt += right - left;
                right--;
            } else {
                left++;
            }
        }

        System.out.println(cnt);
        in.close();
    }
}


A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5
1 1 1 0 0
0 1 1 1 1
OutputCopy3
InputCopy3
0 0 0
0 0 0
OutputCopy-1
InputCopy4
1 1 1 1
1 1 1 1
OutputCopy-1
InputCopy9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
OutputCopy4
NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

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

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

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

    {

        FastReader sc =new FastReader();

        // int t=sc.nextInt();

      int t=1;

        O : while(t-->0)

        {

            int n = sc.nextInt();

            int a[]=sc.readArray(n);

            int b[]=sc.readArray(n);

            int ca = 0, cb = 0;

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

            {

                if (a[i] == b[i])

                    continue;

                if (a[i] == 1)

                    ca++;

                else

                    cb++;

            }

            if (ca == 0)

            {

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

            }

            else

            {

                int ans = cb / ca + 1;

                System.out.println(ans);

            }

        }

        out.flush();

    }

static void printN()

{

    System.out.println("NO");

}

static void printY()

{

    System.out.println("YES");

}

static int findfrequencies(int a[],int n)

{

    int count=0;

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

    {

        if(a[i]==n)

        {

            count++;

        }

    }

    return count;

}

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());

        }

        String nextLine()

        {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] readArray(int n) {

int[] a=new int[n];

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

return a;

}

long[] readArrayLong(int n) {

long[] a=new long[n];

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

return a;

}

    }

    public static int[] radixSort2(int[] a)

{

int n = a.length;

int[] c0 = new int[0x101];

int[] c1 = new int[0x101];

int[] c2 = new int[0x101];

int[] c3 = new int[0x101];

for(int v : a) {

c0[(v&0xff)+1]++;

c1[(v>>>8&0xff)+1]++;

c2[(v>>>16&0xff)+1]++;

c3[(v>>>24^0x80)+1]++;

}

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

c0[i+1] += c0[i];

c1[i+1] += c1[i];

c2[i+1] += c2[i];

c3[i+1] += c3[i];

}

int[] t = new int[n];

for(int v : a)t[c0[v&0xff]++] = v;

for(int v : t)a[c1[v>>>8&0xff]++] = v;

for(int v : a)t[c2[v>>>16&0xff]++] = v;

for(int v : t)a[c3[v>>>24^0x80]++] = v;

return a;

}

static int[] EvenOddArragement(int a[])

{

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

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

    {

        if(a[i]%2==0)

        {

            list.add(a[i]);

        }

    }

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

    {

        if(a[i]%2!=0)

        {

            list.add(a[i]);

        }

    }

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

    {

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

    }

    return a;

}

static int gcd(int a, int b) {

    while (b != 0) {

        int t = a;

        a = b;

        b = t % b;

    }

    return a;

}

    static int lcm(int a, int b)

    {

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

    }

    public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)

    {

        // Create a list from elements of HashMap

        List<Map.Entry<Integer, Integer> > list =

               new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());

        // Sort the list

        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {

            public int compare(Map.Entry<Integer, Integer> o1,

                               Map.Entry<Integer, Integer> o2)

            {

                return (o1.getValue()).compareTo(o2.getValue());

            }

        });

        // put data from sorted list to hashmap

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

        for (Map.Entry<Integer, Integer> aa : list) {

            temp.put(aa.getKey(), aa.getValue());

        }

        return temp;

    }

    static int DigitSum(int n)

    {

        int r=0,sum=0;

        while(n>=0)

        {

            r=n%10;

            sum=sum+r;

            n=n/10;

        }

        return sum;

    }

    static boolean checkPerfectSquare(int number)

    {

        double sqrt=Math.sqrt(number);

        return ((sqrt - Math.floor(sqrt)) == 0);

    }

    static boolean isPowerOfTwo(int n)

    {

        if(n==0)

        return false;

        return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2)))));

    }

    static boolean isPrime2(int n)

    {

        if (n <= 1)

        {

            return false;

        }

        if (n == 2)

        {

            return true;

        }

        if (n % 2 == 0)

        {

            return false;

        }

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

        {

            if (n % i == 0)

            {

                return false;

            }

        }

        return true;

    }

    static String minLexRotation(String str)

    {

        int n = str.length();

        String arr[] = new String[n];

        String concat = str + str;

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

        {

            arr[i] = concat.substring(i, i + n);

        }

        Arrays.sort(arr);

        return arr[0];

    }

static String maxLexRotation(String str)

    {

        int n = str.length();

        String arr[] = new String[n];

        String concat = str + str;

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

        {

            arr[i] = concat.substring(i, i + n);

        }

        Arrays.sort(arr);

        return arr[arr.length-1];

    }

    static class P implements Comparable<P> {

		int i, j;

		public P(int i, int j) {

			this.i=i;

			this.j=j;

		}

		public int compareTo(P o) {

			return Integer.compare(i, o.i);

		}

	}

	static int binary_search(int a[],int value)

	{

	    int start=0;

	    int end=a.length-1;

	    int mid=start+(end-start)/2;

	    while(start<=end)

	    {

	        if(a[mid]==value)

	        {

	            return mid;

	        }

	        if(a[mid]>value)

	        {

	            end=mid-1;

	        }

	        else

	        {

	            start=mid+1;

	        }

	        mid=start+(end-start)/2;

	    }

	    return -1;

	}

}


B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)).  Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2
3
1
2
NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).

import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;

public class JaiShreeRam{

	static Scanner in=new Scanner();

	static long mod = 1000000007;

	static ArrayList<ArrayList<Integer>> adj;

	static ArrayList<String> ans;

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

		int z=in.readInt();

		while(z-->0) {

			solve();

		}

	}

	static void solve() {

		int n=in.readInt();

		int x=in.readInt();

		int a[]=nia(n);

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

		int max=a[0];

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

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

			st.add(a[i]);

		}

		if(st.contains(x)) {

			System.out.println(1);

		}

		else if(x<max) {

			System.out.println(2);

		}

		else {

			System.out.println((int)Math.ceil((double)x/max));

		}

	}

	static int[] nia(int n){

		int[] arr= new int[n];

		int i=0;

		while(i<n){

			arr[i++]=in.readInt();

		}

		return arr;

	}

	static long[] nla(int n){

		long[] arr= new long[n];

		int i=0;

		while(i<n){

			arr[i++]=in.readLong();

		}

		return arr;

	}

	static int[] nia1(int n){

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

		int i=1;

		while(i<=n){

			arr[i++]=in.readInt();

		}

		return arr;

	}

	static long gcd(long a, long b) {

		if (b==0) return a;

		return gcd(b, a%b);

	}

	static class Scanner{

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

		StringTokenizer st=new StringTokenizer("");

		String readString() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		double readDouble() {

			return Double.parseDouble(readString());

		}

		int readInt() {

			return Integer.parseInt(readString());

		}

		long readLong() {

			return Long.parseLong(readString());

		}

	}

}


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

//some updates in import stuff

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

/*

    Always check before submitting list

    -> int to long conversion needed

    -> while loop mein break case shi ho

    -> extra kuch output na ho rha free fund mein

*/

//update this bad boi too

public class Main{

    static int mod = (int) (Math.pow(10, 9)+7);

	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };

	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };

	static final double eps = 1e-10;

	static Set<Integer> primeNumbers = new HashSet<>();

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

        MyScanner sc = new MyScanner();

        //changes in this line of code

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

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

        //Write Code Below (let's try to code it down bois) (if bigger then remove them first)

        //keep on making new stringbuilder again and again for sure (n is very less)

        int n = sc.nextInt();

        char[] inp = sc.nextLine().toCharArray();

        //since these strings are

        int[] pos = new int[n];

        for(int i = 26; i >= 1; i--){

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

            char prev = (char)('a' + (i-1));

            while(true){

                boolean terminate = true;

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

                    if(pos[j] == -1) continue;

                    if(inp[j] == curr){

                        //we found some bad boi

                        //we find recent left and recent right

                        int l = j-1;

                        int r = j+1;

                        boolean bingo = false;

                        while(l >= 0){

                            if(pos[l] != -1) break;

                            l--;

                        }

                        if( l >= 0 && inp[l] == prev) bingo = true;

                        while(r < n){

                            if(pos[r] != -1) break;

                            r++;

                        }

                        if(r < n && inp[r] == prev) bingo = true;

                        if(bingo){

                            terminate = false;

                            pos[j] = -1;

                        }

                    }

                }

                if(terminate) break;

            }

        }

        int count = 0;

        for(int i : pos) if(i == -1) count++;

        out.println(count);

        out.close();

    }

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

 //Updation Required

    //Fenwick Tree (customisable)

    //Segment Tree (customisable)

    //-----CURRENTLY PRESENT-------//

    //Graph

    //DSU

    //powerMODe

    //power

    //Segment Tree (work on this one)

    //Prime Sieve

    //Count Divisors

    //Next Permutation

    //Get NCR

    //isVowel

    //Sort (int)

    //Sort (long)

    //Binomial Coefficient

    //Pair

    //Triplet

    //lcm (int & long)

    //gcd (int & long)

    //gcd (for binomial coefficient)

    //swap (int & char)

    //reverse

    //SOME LATEST UPDATIONS!!!

    //mod_mul

    //mod_div

    //Fast input and output

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //finding combinations in O(1) (basically the most basic logic you can think of)

    //not that complicated as i though it of

    //GRAPH (basic structure)

    public static class Graph{

        public int V;

        public ArrayList<ArrayList<Integer>> edges;

        //2 -> [0,1,2] (current)

        Graph(int V){

            this.V  = V;

            edges = new ArrayList<>(V+1);

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

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

            }

        }

        public void addEdge(int from , int to){

            edges.get(from).add(to);

        }

    }

    //DSU (path and rank optimised)

    public static class DisjointUnionSets {

        int[] rank, parent;

        int n;

        public DisjointUnionSets(int n)

        {

            rank = new int[n];

            parent = new int[n];

            Arrays.fill(rank, 1);

            Arrays.fill(parent,-1);

            this.n = n;

        }

        public int find(int curr){

            if(parent[curr] == -1)

                return curr;

            //path compression optimisation

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

        }

        public void union(int a, int b){

            int s1 = find(a);

            int s2 = find(b);

            if(s1 != s2){

                if(rank[s1] < rank[s2]){

                    parent[s1] = s2;

                    rank[s2] += rank[s1];

                }else{

                    parent[s2] = s1;

                    rank[s1] += rank[s2];

                }

            }

        }

    }

    //with mod

    public static long powerMOD(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

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

                x %= mod;

                res %= mod;

                res = (res * x)%mod;

            }

            // y must be even now

            y = y >> 1; // y = y/2

            x%= mod;

            x = (x * x)%mod;  // Change x to x^2

        }

        return res%mod;

    }

    //without mod

    public static long power(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

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

                res = (res * x);

            }

            // y must be even now

            y = y >> 1; // y = y/

            x = (x * x);

        }

        return res;

    }

    public static class segmentTree{

        public long[] arr;

        public long[] tree;

        public long[] lazy;

        segmentTree(long[] array){

            int n = array.length;

            arr = new long[n];

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

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

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

        }

        public  void build(int[]arr, int s, int e, int[] tree, int index){

            if(s == e){

                tree[index] = arr[s];

                return;

            }

            //otherwise divide in two parts and fill both sides simply

            int mid = (s+e)/2;

            build(arr, s, mid, tree, 2*index);

            build(arr, mid+1, e, tree, 2*index+1);

            //who will build the current position dude

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

        }

        public  int query(int sr, int er, int sc, int ec, int index, int[] tree){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(sc != ec){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(sr > ec || sc > er) return Integer.MAX_VALUE;

            //found the index baby

            if(sr <= sc && ec <= er) return tree[index];

            //finding the index on both sides hehehehhe

            int mid = (sc + ec)/2;

            int left = query(sr, er, sc, mid, 2*index, tree);

            int right = query(sr, er, mid+1, ec, 2*index + 1, tree);

            return Integer.min(left, right);

        }

        //now we will do point update implementation

        //it should be simple then we expected for sure

        public  void update(int index, int indexr, int increment, int[] tree, int s, int e){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] = lazy[index];

                    lazy[2*index] = lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(indexr < s || indexr > e) return;

            //found the required index

            if(s == e){

                tree[index] += increment;

                return;

            }

            //search for the index on both sides

            int mid = (s+e)/2;

            update(2*index, indexr, increment, tree, s, mid);

            update(2*index+1, indexr, increment, tree, mid+1, e);

            //now update the current range simply

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

        }

        public  void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){

            //if not at all in the same range

            if(e < sr || er < s) return;

            //complete then also move forward

            if(s == e){

                tree[index] += increment;

                return;

            }

            //otherwise move in both subparts

            int mid = (s+e)/2;

            rangeUpdate(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);

            //update current range too na

            //i always forget this step for some reasons hehehe, idiot

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

        }

        public  void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){

            //update lazy values

            //resolve lazy value before going down

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap case

            if(sr > e || s > er) return;

            //complete overlap

            if(sr <= s && er >= e){

                tree[index] += increment;

                if(s != e){

                    lazy[2*index+1] += increment;

                    lazy[2*index] += increment;

                }

                return;

            }

            //otherwise go on both left and right side and do your shit

            int mid = (s + e)/2;

            rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);

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

            return;

        }

    }

    //prime sieve

    public static void primeSieve(int n){

        BitSet bitset = new BitSet(n+1);

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

            if (i == 0 || i == 1) {

                bitset.set((int) i);

                continue;

            }

            if(bitset.get((int) i)) continue;

            primeNumbers.add((int)i);

            for(long j = i; j <= n ; j+= i)

                bitset.set((int)j);

        }

    }

    //number of divisors

    // public static int countDivisors(long number){

    //     if(number == 1) return 1;

    //     List<Integer> primeFactors = new ArrayList<>();

    //     int index = 0;

    //     long curr = primeNumbers.get(index);

    //     while(curr * curr <= number){

    //         while(number % curr == 0){

    //             number = number/curr;

    //             primeFactors.add((int) curr);

    //         }

    //         index++;

    //         curr = primeNumbers.get(index);

    //     }

    //     if(number != 1) primeFactors.add((int) number);

    //     int current = primeFactors.get(0);

    //     int totalDivisors = 1;

    //     int currentCount = 2;

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

    //         if (primeFactors.get(i) == current) {

    //             currentCount++;

    //         } else {

    //             totalDivisors *= currentCount;

    //             currentCount = 2;

    //             current = primeFactors.get(i);

    //         }

    //     }

    //     totalDivisors *= currentCount;

    //     return totalDivisors;

    // }

    //now adding next permutation function to java hehe

    public static boolean next_permutation(int[] p) {

        for (int a = p.length - 2; a >= 0; --a)

          if (p[a] < p[a + 1])

            for (int b = p.length - 1;; --b)

              if (p[b] > p[a]) {

                int t = p[a];

                p[a] = p[b];

                p[b] = t;

                for (++a, b = p.length - 1; a < b; ++a, --b) {

                  t = p[a];

                  p[a] = p[b];

                  p[b] = t;

                }

                return true;

              }

        return false;

    }

    //is vowel function

    public static boolean isVowel(char c)

    {

        return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' ||     c=='u' || c=='U');

    }

    //to sort the array with better method

	public static void sort(int[] a) {

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

		for (int i:a) l.add(i);

		Collections.sort(l);

		for (int i=0; i<a.length; i++) a[i]=l.get(i);

	}

    //sort long

    public 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);

	}

    //for calculating binomialCoeff

    public static int binomialCoeff(int n, int k)

    {

        int C[] = new int[k + 1];

        // nC0 is 1

        C[0] = 1;

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

            // Compute next row of pascal

            // triangle using the previous row

            for (int j = Math.min(i, k); j > 0; j--)

                C[j] = C[j] + C[j - 1];

        }

        return C[k];

    }

    //Pair with int int

    public static class Pair{

        public int a;

        public int b;

        Pair(int a , int b){

            this.a = a;

            this.b = b;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Triplet with int int int

    public static class Triplet{

        public int a;

        public int b;

        public int c;

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

            this.a = a;

            this.b = b;

            this.c = c;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Shortcut function

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

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

    }

    //let's make one for calculating lcm basically

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

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

    }

    //int version for gcd

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

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

    //long version for gcd

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

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

     //for ncr calculator(ignore this code)

     public static long __gcd(long n1, long n2)

     {

         long gcd = 1;

         for (int i = 1; i <= n1 && i <= n2; ++i) {

             // Checks if i is factor of both integers

             if (n1 % i == 0 && n2 % i == 0) {

                 gcd = i;

             }

         }

         return gcd;

     }

    //swapping two elements in an array

    public static void swap(int[] arr, int left , int right){

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //for char array

    public static void swap(char[] arr, int left , int right){

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //reversing an array

    public static void reverse(int[] arr){

        int left = 0;

        int right = arr.length-1;

        while(left <= right){

            swap(arr, left,right);

            left++;

            right--;

        }

    }

    public static long expo(long a, long b, long mod) {

        long res = 1;

        while (b > 0) {

            if ((b & 1) == 1L) res = (res * a) % mod;  //think about this one for a second

            a = (a * a) % mod;

            b = b >> 1;

        }

        return res;

    }

    //SOME EXTRA DOPE FUNCTIONS

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

        return expo(a, b - 2, b);

    }

    public static long mod_add(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a + b) % m) + m) % m;

    }

    public static long mod_sub(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a - b) % m) + m) % m;

    }

    public static long mod_mul(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a * b) % m) + m) % m;

    }

    public static long mod_div(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (mod_mul(a, mminvprime(b, m), m) + m) % m;

    }

    //O(n) every single time remember that

    public static long nCr(long N, long K , long mod){

        long upper = 1L;

        long lower = 1L;

        long lowerr = 1L;

        for(long i = 1; i <= N; i++){

            upper = mod_mul(upper, i, mod);

        }

        for(long i = 1; i <= K; i++){

            lower = mod_mul(lower, i, mod);

        }

        for(long i = 1; i <= (N - K); i++){

            lowerr = mod_mul(lowerr, i, mod);

        }

        // out.println(upper + " " + lower + " " + lowerr);

        long answer = mod_mul(lower, lowerr, mod);

        answer = mod_div(upper, answer, mod);

        return answer;

    }

    // ll *fact = new ll[2 * n + 1];

	// ll *ifact = new ll[2 * n + 1];

	// fact[0] = 1;

	// ifact[0] = 1;

	// for (ll i = 1; i <= 2 * n; i++)

	// {

	// 	fact[i] = mod_mul(fact[i - 1], i, MOD1);

	// 	ifact[i] = mminvprime(fact[i], MOD1);

	// }

    //ifact is basically inverse factorial in here!!!!!(imp)

    public static long combination(long n, long r, long m, long[] fact, long[] ifact) {

        long val1 = fact[(int)n];

        long val2 = ifact[(int)(n - r)];

        long val3 = ifact[(int)r];

        return (((val1 * val2) % m) * val3) % m;

    }

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

    public static PrintWriter out;

    //-----------MyScanner class for faster input----------

    public static class MyScanner {

      BufferedReader br;

      StringTokenizer st;

        public MyScanner() {

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

        }

        // public MyScanner() throws FileNotFoundException {

        //     br = new BufferedReader(new FileReader("input.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;

        }

    }

   //--------------------------------------------------------

}


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

import java.util.Arrays;

import java.util.Scanner;

public class B1311 {

	static Scanner sc = new Scanner(System.in);

	static int t = sc.nextInt();

	static int []a = new int[110];

	static boolean []c = new boolean[110];

	static int []p = new int[110];

	public static void main(String[] args) {

		while((t--) > 0) {

			Arrays.fill(c,false);

			boolean flag = true;

			int n = sc.nextInt();

			int m = sc.nextInt();

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

				a[i] = sc.nextInt();

			}

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

				p[j] = sc.nextInt();

				c[p[j]] = true;

			}

			int k = 0;

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

				for(int j = 1; j <= n - i1; j++) {

					if(a[j] > a[j + 1]) {

						if(c[j]) {

							k = a[j];

							a[j] = a[j + 1];

							a[j + 1] = k;

						}

						else {

							flag = false;

						}

					}

				}

			}

			if(!flag) {

				System.out.println("NO");

			}else {

				System.out.println("YES");

			}

		}

	}

 }


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

/*

Created on = 14-Mar-2022 / 8:07:56 PM

*/

import java.util.*;

import java.io.*;

import java.lang.*;

import java.math.*;

public class Main {

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

		try {

			solve();

			out.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	// SOLUTION STARTS HERE

	// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

	static void solve() {

		String s = sc.next();

		/*

		 * (()()) 122333 333221

		 */

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

		while (true) {

			char a[] = s.toCharArray();

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

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

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

				if (a[i] == '(')

					o.add(i + 1);

				else

					c.add(i + 1);

			}

			int pref[] = new int[a.length];

			int suff[] = new int[a.length];

			if (a[0] == '(')

				pref[0]++;

			if (a[a.length - 1] == ')')

				suff[a.length - 1]++;

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

				pref[i] += pref[i - 1] + (a[i] == '(' ? 1 : 0);

			}

			for (int i = a.length - 2; i >= 0; i--) {

				suff[i] += suff[i + 1] + (a[i] == ')' ? 1 : 0);

			}

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

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

//			System.out.println("xxxxxxxxxxxxx");

			int max = 0;

			int ind = -1;

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

				if (a[i] == '(') {

					if (max < Math.min(pref[i], suff[i + 1])) {

						max = Math.min(pref[i], suff[i + 1]);

						ind = i + 1;

					}

				}

			}

			if (max == 0) {

				break;

			}

			int temp = max;

			boolean t[] = new boolean[a.length + 1];

			StringBuilder sb = new StringBuilder();

			for (int i : o) {

				if (i <= ind && temp > 0) {

					t[i] = true;

					temp--;

				}

			}

			temp = max;

			for (int i = c.size() - 1; i >= 0; i--) {

				if (c.get(i) > ind && temp > 0) {

					t[c.get(i)] = true;

					temp--;

				}

			}

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

				if (!t[i + 1])

					sb.append(a[i]);

			}

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

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

				if (t[i])

					al.add(i);

			}

			ans.add(al);

			s = sb.toString();

			if (s.length() == 0)

				break;

		}

		System.out.println(ans.size());

		for (List<Integer> x : ans) {

			System.out.println(x.size());

			for (int i : x) {

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

			}

			System.out.println();

		}

	}

	// SOLUTION ENDS HERE

	// :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

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

		long ans = 1;

		while (b != 0) {

			if ((b & 1) == 1)

				ans = (ans * a) % mod;

			a = (a * a) % mod;

			b >>= 1;

		}

		return ans;

	}

	static class DSU {

		int rank[];

		int parent[];

		DSU(int n) {

			rank = new int[n + 1];

			parent = new int[n + 1];

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

				parent[i] = i;

			}

		}

		int findParent(int node) {

			if (parent[node] == node)

				return node;

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

		}

		boolean union(int x, int y) {

			int px = findParent(x);

			int py = findParent(y);

			if (px == py)

				return false;

			if (rank[px] < rank[py]) {

				parent[px] = py;

			} else if (rank[px] > rank[py]) {

				parent[py] = px;

			} else {

				parent[px] = py;

				rank[py]++;

			}

			return true;

		}

	}

	static void sort(int[] a) {

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

		for (int i : a)

			l.add(i);

		Collections.sort(l);

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

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

	}

	static boolean[] seiveOfEratosthenes(int n) {

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

		Arrays.fill(isPrime, true);

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

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

				isPrime[j] = false;

			}

		}

		return isPrime;

	}

	static int gcd(int a, int b) {

		if (b == 0)

			return a;

		return gcd(b, a % b);

	}

	static boolean isPrime(long n) {

		if (n < 2)

			return false;

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

			if (n % i == 0)

				return false;

		}

		return true;

	}

	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[] readIntArray(int n) {

			int[] a = new int[n];

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

				a[i] = nextInt();

			return a;

		}

		long[] readLongArray(int n) {

			long[] a = new long[n];

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

				a[i] = nextLong();

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

	}

	private static final FastScanner sc = new FastScanner();

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

}


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

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.TreeSet;
import java.util.Objects;
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);
        DMinimaxProblem solver = new DMinimaxProblem();
        solver.solve(1, in, out);
        out.close();
    }

    static class DMinimaxProblem {
        int n;
        int m;
        int[][] arr;
        int id1;
        int id2;
        int p;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.nextInt();
            m = in.nextInt();
            arr = in.nextIntMatrix(n, m);
            p = (int) Math.pow(2, m) - 1;
            int lo = 0;
            int hi = (int) 1e9;
            id1 = -1;
            id2 = -1;
            int ans = 0;
            while (lo <= hi) {
                int mid = (lo + hi) / 2;
                if (check(mid)) {
                    ans = mid;
                    lo = mid + 1;
                } else {
                    hi = mid - 1;
                }
            }
            out.println(id1, id2);
        }

        boolean check(int mid) {
            TreeSet<Pair> set = new TreeSet<>();
            for (int i = 0; i < n; i++) {
                int mask = 0;
                for (int j = 0; j < m; j++) {
                    if (arr[i][j] >= mid) mask |= (1 << j);
                }
                set.add(new Pair(mask, i));
            }
            for (Pair a : set) {
                for (Pair b : set) {
                    if ((a.a | b.a) == p) {
                        id1 = a.b + 1;
                        id2 = b.b + 1;
                        return true;
                    }
                }
            }
            return false;
        }

        class Pair implements Comparable<Pair> {
            int a;
            int b;

            Pair(int a, int b) {
                this.a = a;
                this.b = b;
            }

            public int hashCode() {
                return Objects.hash(a, b);
            }

            public boolean equals(Object obj) {
                Pair that = (Pair) obj;
                return a == that.a && b == that.b;
            }

            public String toString() {
                return "[" + a + ", " + b + "]";
            }

            public int compareTo(Pair v) {
                return a - v.a;
            }

        }

    }

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

    }

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

        public int[][] nextIntMatrix(int rows, int cols) {
            int[][] matrix = new int[rows][cols];
            for (int i = 0; i < rows; i++)
                for (int j = 0; j < cols; j++)
                    matrix[i][j] = nextInt();
            return matrix;
        }

    }
}


A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands:  'L' (Left) sets the position x:=x−1x:=x−1;  'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully):   "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00;  "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well;  "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4
LRLR
OutputCopy5
NoteIn the example; Zoma may end up anywhere between −2−2 and 22.

import java.util.*;

public class java {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int x = scan.nextInt();

        String g = scan.next();

        int c = 0, q = 0;

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

            if(g.charAt(i)=='R'){

                c++;

            }

            else{

                q++;

            }

        }

        System.out.println(c+q+1);

    }

}


B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).

import java.io.OutputStreamWriter;

import java.util.Scanner;

import java.io.BufferedWriter;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.IOException;

public class math {

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

	Scanner in = new Scanner(System.in);

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

		int tt = in.nextInt();

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

		int a = in.nextInt();

		int b = in.nextInt();

		int p = 9;

		int c = 0;

		while(p<=b) {

			p = p*10 +9;

			c++;

		}

		if(c==0) {

			log.write(0+"\n");

		}

		else {

			long t = (long) c*a;

			log.write(t+"\n");

		}

		log.flush();

		}

	}

}


import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.math.BigInteger;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Map.Entry;

import java.util.StringTokenizer;

import java.util.function.Supplier;

import java.util.stream.Collectors;

public class cf {

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

    public static PrintWriter out;

    public static int cnt;

    //-----------MyScanner class for faster input----------

    public static class MyScanner {

        BufferedReader br;

        StringTokenizer st;

        public MyScanner() {

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

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine(){

            String str = "";

        try {

            str = br.readLine();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return str;

        }

		public void close() {

			// TODO Auto-generated method stub

		}

	        }

    static boolean isPrime(int n)

{

    // Corner cases

    if (n <= 1)

        return false;

    if (n <= 3)

        return true;

    // This is checked so that we can skip

    // middle five numbers in below loop

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

        return false;

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

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

            return false;

    return true;

}

    public static int reverseBits(int n)

    {

        int rev = 0;

        // traversing bits of 'n'

        // from the right

        while (n > 0)

        {

            // bitwise left shift

            // 'rev' by 1

            rev <<= 1;

            // if current bit is '1'

            if ((int)(n & 1) == 1)

                rev ^= 1;

            // bitwise right shift

            //'n' by 1

            n >>= 1;

        }

        // required number

        return rev;

    }

    public static ArrayList<String> getSequence(String str)

    {

        // If 1

//    	string is empty

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

            // Return an empty arraylist

            ArrayList<String> empty = new ArrayList<>();

            empty.add("");

            return empty;

        }

        // Take first character of str

        char ch = str.charAt(0);

        // Take sub-string starting from the

        // second character

        String subStr = str.substring(1);

        // Recursive call for all the sub-sequences

        // starting from the second character

        ArrayList<String> subSequences =

                              getSequence(subStr);

        // Add first character from str in the beginning

        // of every character from the sub-sequences

        // and then store it into the resultant arraylist

        ArrayList<String> res = new ArrayList<>();

        for (String val : subSequences) {

            res.add(val);

            res.add(ch + val);

        }

        return res;

    }

    static int fact(int n)

    {

    	int fact=1;

    	while(n>=1)

    	{

    		fact=fact*n;

    		n--;

    	}

    	return fact;

    }

    static long __gcd(long a, long b)

    {

        if (a == 0 || b == 0)

            return 0;

        if (a == b)

            return a;

        if (a > b)

            return __gcd(a-b, b);

        return __gcd(a, b-a);

    }

    static boolean coprime(long a, long b) {

        if ( __gcd(a, b) == 1)

            return true;

        else

            return false;

    }

    static int xor(int n,int a,int b)

    {

		if(n>0)

		{

			xor(n-1,b,a^b);

			return a^b;

		}

		else

		{

			return a^b;

		}

    }

    static ArrayList<ArrayList<Integer>> printSubArrays(int[] arr, int start, int end,ArrayList<ArrayList<Integer>> x)

    {

        if (end == arr.length)

        {

            return x;

        }

        else if (start > end)

        {

            printSubArrays(arr, 0, end + 1,x);

        }

        else

        {

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

            for (int i = start; i < end; i++)

            {

               x1.add(arr[i]);

            }

           x1.add(arr[end]);

           x.add(x1);

            printSubArrays(arr, start + 1, end,x);

        }

        return x;

    }

    public static ArrayList<ArrayList<Integer>> printSubsequences(int[] arr, int index,

            ArrayList<Integer> path)

{

// Print the subsequence when reach

// the leaf of recursion tree

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

if (index == arr.length)

{

// Condition to avoid printing

// empty subsequence

if (path.size() > 0)

x.add(path);

return x;

}

else

{

// Subsequence without including

// the element at current index

printSubsequences(arr, index + 1, path);

path.add(arr[index]);

x.add(path);

// Subsequence including the element

// at current index

printSubsequences(arr, index + 1, path);

x.add(path);

// Backtrack to remove the recently

// inserted element

path.remove(path.size() - 1);

x.add(path);

}

return x;

}

	public static void main(String[] args)

	{

		MyScanner sc = new MyScanner();

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

		int t=sc.nextInt();

		while(t-->0)

		{

//			int n=sc.nextInt();

//			int k=sc.nextInt();

//			int i=1,s=0;

//			while(s<k)

//			{

//				s=s+i;

//				i++;

//			}

        long a=sc.nextLong();

        long b=sc.nextLong();

        long a1=10;

        long x=1;

        while(a1-1<=b)

        {

        	a1=a1*10;

        	x++;

        }

        a1=a1/10;

        x--;

        out.println(x*a);

		}

		out.close();

	}

}


E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2

import java.util.*;

import java.io.*;

public class E81 {

    public static void main(String[] args) {

        MyScanner sc = new MyScanner();

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

        int n = sc.nextInt();

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

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

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

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

            p[i] = sc.nextInt();

            where[p[i]] = i;

        }

        for (int i = 1; i <= n; i++) cost[p[i]] = sc.nextLong();

        RangeTree seg = new RangeTree(n + 1);

        long cur = cost[p[1]];

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

            seg.update(i, i, cur);

            cur += cost[p[i + 1]];

        }

        long ans = seg.minQuery(1, n - 1);

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

            long c = cost[val];

            if (where[val] > 1) seg.update(1, where[val] - 1, c);

            if (where[val] < n) seg.update(where[val], n - 1, -c);

            ans = Math.min(ans, seg.minQuery(1, n - 1));

        }

        out.println(ans);

        out.close();

    }

    static class RangeTree {

        private long[] max;

        private long[] min;

        private long[] lazy;

        private long[] sum;

        private int size;

        public RangeTree(int size) {

            this.size = size;

            max = new long[4*size];

            min = new long[4*size];

            sum = new long[4*size];

            lazy = new long[4*size];

        }

        public void update(int l, int r, long inc) {

            update(1, 0, size-1, l, r, inc);

        }

        private void pushDown(int index, int l, int r) {

            min[index] += lazy[index];

            max[index] += lazy[index];

            sum[index] += lazy[index] * (r-l+1);

            if(l != r) {

                lazy[2*index] += lazy[index];

                lazy[2*index+1] += lazy[index];

            }

            lazy[index] = 0;

        }

        private void pullUp(int index, int l, int r) {

            int m = (l+r)/2;

            min[index] = Math.min(evaluateMin(2*index, l, m), evaluateMin(2*index+1, m+1, r));

            max[index] = Math.max(evaluateMax(2*index, l, m), evaluateMax(2*index+1, m+1, r));

            sum[index] = evaluateSum(2*index, l, m) + evaluateSum(2*index+1, m+1, r);

        }

        private long evaluateSum(int index, int l, int r) {

            return sum[index] + (r-l+1)*lazy[index];

        }

        private long evaluateMin(int index, int l, int r) {

            return min[index] + lazy[index];

        }

        private long evaluateMax(int index, int l, int r) {

            return max[index] + lazy[index];

        }

        private void update(int index, int l, int r, int left, int right, long inc) {

            if(r < left || l > right) return;

            if(l >= left && r <= right) {

                lazy[index] += inc;

                return;

            }

            pushDown(index, l, r);

            int m = (l+r)/2;

            update(2*index, l, m, left, right, inc);

            update(2*index+1, m+1, r, left, right, inc);

            pullUp(index, l, r);

        }

        public long minQuery(int l, int r) {

            return minQuery(1, 0, size-1, l, r);

        }

        private long minQuery(int index, int l, int r, int left, int right) {

            if(r < left || l > right) return Long.MAX_VALUE;

            if(l >= left && r <= right) {

                return evaluateMin(index, l, r);

            }

            pushDown(index, l, r);

            int m = (l+r)/2;

            long ret = Long.MAX_VALUE;

            ret = Math.min(ret, minQuery(2*index, l, m, left, right));

            ret = Math.min(ret, minQuery(2*index+1, m+1, r, left, right));

            pullUp(index, l, r);

            return ret;

        }

        public long maxQuery(int l, int r) {

            return maxQuery(1, 0, size-1, l, r);

        }

        private long maxQuery(int index, int l, int r, int left, int right) {

            if(r < left || l > right) return Long.MIN_VALUE;

            if(l >= left && r <= right) {

                return evaluateMax(index, l, r);

            }

            pushDown(index, l, r);

            int m = (l+r)/2;

            long ret = Long.MIN_VALUE;

            ret = Math.max(ret, maxQuery(2*index, l, m, left, right));

            ret = Math.max(ret, maxQuery(2*index+1, m+1, r, left, right));

            pullUp(index, l, r);

            return ret;

        }

        public long sumQuery(int l, int r) {

            return sumQuery(1, 0, size-1, l, r);

        }

        private long sumQuery(int index, int l, int r, int left, int right) {

            if(r < left || l > right) return 0;

            if(l >= left && r <= right) {

                return evaluateSum(index, l, r);

            }

            pushDown(index, l, r);

            int m = (l+r)/2;

            long ret = 0;

            ret += sumQuery(2*index, l, m, left, right);

            ret += sumQuery(2*index+1, m+1, r, left, right);

            pullUp(index, l, r);

            return ret;

        }

    }

    //-----------MyScanner class for faster input----------

    public static class MyScanner {

        BufferedReader br;

        StringTokenizer st;

        public MyScanner() {

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

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


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

import java.util.*;

import java.io.*;

public class Main {

	static StringBuilder sb;

	static dsu dsu;

	static long fact[];

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

	static void solve()

	{

	    int n=i();

	    int q=i();

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

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

	    HashSet<String> dg=new HashSet<>();

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

	        int x=i()-1;

	        int y=i()-1;

	       if(x==0&&arr[x+1][y]&&!arr[x][y])full.add(y);

	       if(x==1&&arr[x-1][y]&&!arr[x][y])full.add(y);

	       if(arr[x][y]){

	           if(full.contains(y))full.remove(y);

	       }

	      if(arr[x][y]){

	        if(dg.contains(x+"#"+y)){

	            dg.remove(x+"#"+y);

	        }

	         if(x==0){

                if(y>0&&arr[1][y-1]){

                    dg.remove(""+1+"#"+(y-1));

                }

                }

                else{

                if(y>0&&arr[0][y-1]){

                    dg.remove(""+0+"#"+(y-1));

                }

                }

	      }

	      else{

                if(x==0){

                if(y>0&&arr[1][y-1]){

                    dg.add(""+1+"#"+(y-1));

                }

                if(y<n-1&&arr[1][y+1]){

                       dg.add(""+0+"#"+(y));

                }

                }

                else{

                if(y>0&&arr[0][y-1]){

                    dg.add(""+0+"#"+(y-1));

                }

                if(y<n-1&&arr[0][y+1]){

                    dg.add(""+1+"#"+(y));

                }

                }

	      }

	       arr[x][y]=!arr[x][y];

	    if(full.size()>0||dg.size()>0){

	        sb.append("No\n");

	    }

	    else{

	        sb.append("Yes\n");

	    }

	    }

	}

	public static void main(String[] args) {

		sb = new StringBuilder();

		int test = 1;

			 fact=new long[(int)1e6+10];

			 fact[0]=fact[1]=1;

			 for(int i=2;i<fact.length;i++)

	 { fact[i]=((long)(i%mod)*(long)(fact[i-1]%mod))%mod; }

		while (test-- > 0) {

			solve();

		}

		System.out.println(sb);

	}

//**************NCR%P******************

	static long ncr(int n, int r) {

		if (r > n)

			return (long) 0;

		long res = fact[n] % mod;

		// System.out.println(res);

		res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;

		res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;

		// System.out.println(res);

		return res;

	}

	static long p(long x, long y)// POWER FXN //

	{

		if (y == 0)

			return 1;

		long res = 1;

		while (y > 0) {

			if (y % 2 == 1) {

				res = (res * x);

				y--;

			}

			x = (x * x) ;

			y = y / 2;

		}

		return res;

	}

//**************END******************

	// *************Disjoint set

	// union*********//

	static class dsu {

		int parent[];

		dsu(int n) {

			parent = new int[n];

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

				parent[i] = i;

		}

		int find(int a) {

			if (parent[a] ==a)

				return a;

			else {

				int x = find(parent[a]);

				parent[a] = x;

				return x;

			}

		}

		void merge(int a, int b) {

			a = find(a);

			b = find(b);

			if (a == b)

				return;

			parent[b] = a;

		}

	}

//**************PRIME FACTORIZE **********************************//

	static TreeMap<Integer, Integer> prime(long n) {

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

		long num = n;

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

			if (n % i == 0) {

				int nt = 0;

				while (n % i == 0) {

					n = n / i;

					nt++;

				}

				h.put(i, nt);

			}

		}

		if (n != 1)

			h.put((int) n, 1);

		return h;

	}

//****CLASS PAIR ************************************************

	static class Pair implements Comparable<Pair> {

		int x;

		long y;

		Pair(int x, long y) {

			this.x = x;

			this.y = y;

		}

		public int compareTo(Pair o) {

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

		}

	}

//****CLASS PAIR **************************************************

	static class InputReader {

		private InputStream stream;

		private byte[] buf = new byte[1024];

		private int curChar;

		private int numChars;

		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {

			this.stream = stream;

		}

		public int read() {

			if (numChars == -1)

				throw new InputMismatchException();

			if (curChar >= numChars) {

				curChar = 0;

				try {

					numChars = stream.read(buf);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (numChars <= 0)

					return -1;

			}

			return buf[curChar++];

		}

		public int Int() {

			int c = read();

			while (isSpaceChar(c))

				c = read();

			int sgn = 1;

			if (c == '-') {

				sgn = -1;

				c = read();

			}

			int res = 0;

			do {

				if (c < '0' || c > '9')

					throw new InputMismatchException();

				res *= 10;

				res += c - '0';

				c = read();

			} while (!isSpaceChar(c));

			return res * sgn;

		}

		public String String() {

			int c = read();

			while (isSpaceChar(c))

				c = read();

			StringBuilder res = new StringBuilder();

			do {

				res.appendCodePoint(c);

				c = read();

			} while (!isSpaceChar(c));

			return res.toString();

		}

		public boolean isSpaceChar(int c) {

			if (filter != null)

				return filter.isSpaceChar(c);

			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

		}

		public String next() {

			return String();

		}

		public interface SpaceCharFilter {

			public boolean isSpaceChar(int ch);

		}

	}

	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 printLine(Object... objects) {

			print(objects);

			writer.println();

		}

		public void close() {

			writer.close();

		}

		public void flush() {

			writer.flush();

		}

	}

	static InputReader in = new InputReader(System.in);

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

	public static long[] sort(long[] a2) {

		int n = a2.length;

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

		for (long i : a2)

			l.add(i);

		Collections.sort(l);

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

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

		return a2;

	}

	public static char[] sort(char[] a2) {

		int n = a2.length;

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

		for (char i : a2)

			l.add(i);

		Collections.sort(l);

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

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

		return a2;

	}

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

		long res = 1;

		while (y > 0) {

			if (y % 2 != 0) {

				res = (res * x);// % modulus;

				y--;

			}

			x = (x * x);// % modulus;

			y = y / 2;

		}

		return res;

	}

//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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

		if (x == 0)

			return y;

		else

			return gcd(y % x, x);

	}

	// ******LOWEST COMMON MULTIPLE

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

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

		return (x * (y / gcd(x, y)));

	}

//INPUT PATTERN********************************************************

	public static int i() {

		return in.Int();

	}

	public static long l() {

		String s = in.String();

		return Long.parseLong(s);

	}

	public static String s() {

		return in.String();

	}

	public static int[] readArrayi(int n) {

		int A[] = new int[n];

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

			A[i] = i();

		}

		return A;

	}

	public static long[] readArray(long n) {

		long A[] = new long[(int) n];

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

			A[i] = l();

		}

		return A;

	}

}


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

import java.util.*;

import java.io.*;

public class Main

{

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(new

                     InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  e)

                {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException e)

            {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class Pair implements Comparable<Pair>

    {

        int f,s;

        Pair(int f,int s)

        {

            this.f=f;

            this.s=s;

        }

        public int compareTo(Pair p)

        {

            return this.s-p.s;

        }

    }

    static ArrayList<Integer> edge[];

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

    {

        FastReader fs=new FastReader();

        PrintWriter pw=new PrintWriter(System.out);

        int n=fs.nextInt();

        int m=fs.nextInt();

        int k=fs.nextInt();

        int arr[]=new int[k];

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

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

        {

            arr[i]=fs.nextInt();

            s[arr[i]]=true;

        }

        edge=new ArrayList[n+1];

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

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

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

        {

            int u=fs.nextInt();

            int v=fs.nextInt();

            edge[u].add(v);

            edge[v].add(u);

        }

        int [] d1=new int[n+1],dn=new int[n+1];

        Queue<Integer> queue=new LinkedList<>();

        boolean pres=false;

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

        vis[1]=true;

        queue.add(1);

        ArrayList<Pair> p=new ArrayList<>();

        if(s[1])p.add(new Pair(0,1));

        while(!queue.isEmpty())

        {

            int node=queue.poll();

            for(int v:edge[node])

            {

                if(s[v]&&s[node])pres=true;

                if(!vis[v])

                {

                    d1[v]=d1[node]+1;

                    vis[v]=true;

                    queue.add(v);

                    if(s[v])p.add(new Pair(d1[v],v));

                }

            }

        }

        if(pres)

        {

            System.out.println(d1[n]);

            return;

        }

        Arrays.fill(vis,false);

        vis[n]=true;

        queue.add(n);

        while(!queue.isEmpty())

        {

            int node=queue.poll();

            for(int v:edge[node])

            {

                if(!vis[v])

                {

                    dn[v]=dn[node]+1;

                    vis[v]=true;

                    queue.add(v);

                }

            }

        }

        int ans=0,curr=dn[p.get(k-1).s];

        for(int i=k-2;i>=0;i--)

        {

            ans=Math.max(ans,d1[p.get(i).s]+curr+1);

            curr=Math.max(curr,dn[p.get(i).s]);

        }

        ans=Math.min(ans,d1[n]);

        pw.println(ans);

        pw.flush();

        pw.close();

    }

}


C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5
64
32
97
2
12345
OutputCopyYES
2 4 8
NO
NO
NO
YES
3 5 823

import java.io.*;

public class Main {

    public static void productTriplet(int num) {

        int a, b;

        int c = 0;

        for (a = 2; a * a * a <= num; a++) {

            if(num % a == 0) {

                break;

            }

        }

        int rem = num / a;

        for (b = a + 1; b * b <= rem; b++) {

            if(rem % b == 0) {

                c = rem / b;

                if(b >= c) {

                    c = 0;

                }

                break;

            }

        }

        if(a * b * c == num) {

            out.println("YES");

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

        }

        else

            out.println("NO");

    }

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

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

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

        int q = Integer.parseInt(read.readLine());

        while(q-- > 0) {

            int num = Integer.parseInt(read.readLine());

            productTriplet(num);

        }

        out.close();

    }

}