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

//package round616;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.Arrays;

import java.util.InputMismatchException;

public class B {

	InputStream is;

	PrintWriter out;

	String INPUT = "";

	void solve()

	{

		char[] s = ns().toCharArray();

		int n = s.length;

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

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

			f[s[i]-'a'][i+1]++;

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

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

			}

		}

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

			int l = ni()-1, r = ni()-1;

			int fr = 0;

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

				if(f[i][r+1] - f[i][l] > 0){

					fr++;

				}

			}

			if(l == r){

				out.println("Yes");

			}else if(fr > 2){

				out.println("Yes");

			}else if(fr == 1){

				out.println("No");

			}else if(s[l] == s[r]){

				out.println("No");

			}else{

				out.println("Yes");

			}

		}

	}

	void run() throws Exception

	{

		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());

		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();

		solve();

		out.flush();

		tr(System.currentTimeMillis()-s+"ms");

	}

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

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

	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()

	{

		if(lenbuf == -1)throw new InputMismatchException();

		if(ptrbuf >= lenbuf){

			ptrbuf = 0;

			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }

			if(lenbuf <= 0)return -1;

		}

		return inbuf[ptrbuf++];

	}

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

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

	private double nd() { return Double.parseDouble(ns()); }

	private char nc() { return (char)skip(); }

	private String ns()

	{

		int b = skip();

		StringBuilder sb = new StringBuilder();

		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')

			sb.appendCodePoint(b);

			b = readByte();

		}

		return sb.toString();

	}

	private char[] ns(int n)

	{

		char[] buf = new char[n];

		int b = skip(), p = 0;

		while(p < n && !(isSpaceChar(b))){

			buf[p++] = (char)b;

			b = readByte();

		}

		return n == p ? buf : Arrays.copyOf(buf, p);

	}

	private char[][] nm(int n, int m)

	{

		char[][] map = new char[n][];

		for(int i = 0;i < n;i++)map[i] = ns(m);

		return map;

	}

	private int[] na(int n)

	{

		int[] a = new int[n];

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

		return a;

	}

	private int ni()

	{

		int num = 0, b;

		boolean minus = false;

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

		if(b == '-'){

			minus = true;

			b = readByte();

		}

		while(true){

			if(b >= '0' && b <= '9'){

				num = num * 10 + (b - '0');

			}else{

				return minus ? -num : num;

			}

			b = readByte();

		}

	}

	private long nl()

	{

		long num = 0;

		int b;

		boolean minus = false;

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

		if(b == '-'){

			minus = true;

			b = readByte();

		}

		while(true){

			if(b >= '0' && b <= '9'){

				num = num * 10 + (b - '0');

			}else{

				return minus ? -num : num;

			}

			b = readByte();

		}

	}

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

	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }

}


B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows:  The coordinates of the 00-th node is (x0,y0)(x0,y0)  For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions:  From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second.  If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0
2 4 20
OutputCopy3InputCopy1 1 2 3 1 0
15 27 26
OutputCopy2InputCopy1 1 2 3 1 0
2 2 1
OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows:   Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds.  Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows:   Collect the 33-rd node. This requires no seconds.  Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.

import java.util.*;

import java.io.*;

public class Main

{

    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')

                    break;

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

            }

            return new String(buf, 0, cnt);

        }

        public int nextInt() throws IOException

        {

            int ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do

            {

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

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

            if (neg)

                return -ret;

            return ret;

        }

        public long nextLong() throws IOException

        {

            long ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do {

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

            }

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

            if (neg)

                return -ret;

            return ret;

        }

        public double nextDouble() throws IOException

        {

            double ret = 0, div = 1;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do {

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

            }

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

            if (c == '.')

            {

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

                {

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

                }

            }

            if (neg)

                return -ret;

            return ret;

        }

        private void fillBuffer() throws IOException

        {

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

            if (bytesRead == -1)

                buffer[0] = -1;

        }

        private byte read() throws IOException

        {

            if (bufferPointer == bytesRead)

                fillBuffer();

            return buffer[bufferPointer++];

        }

        public void close() throws IOException

        {

            if (din == null)

                return;

            din.close();

        }

    }

    public static long gcd(long a,long b)

    {

        if(b%a==0)

        return a;

        return gcd(b%a,a);

    }

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

    {

        Reader sc=new Reader();

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

        PrintWriter pw=new PrintWriter(System.out);

        int tc=1;//sc.nextInt();

        while(tc-->0)

        {

            long x0=sc.nextLong();

            long y0=sc.nextLong();

            long ax=sc.nextLong();

            long ay=sc.nextLong();

            long bx=sc.nextLong();

            long by=sc.nextLong();

            long xs=sc.nextLong();

            long ys=sc.nextLong();

            long t=sc.nextLong();

            long x=x0,y=y0;

            long ans=0;

            while(x<=(long)1e17&&y<=(long)1e17)

            {

                long mindist=(long)Math.abs(xs-x)+(long)Math.abs(ys-y);

                if(mindist<=t)

                {

                    long s=t-mindist;

                    long moves=1;

                    long minx=x,miny=y;

                    while(minx>x0&&miny>y0)

                    {

                        mindist=minx-(minx-bx)/ax+miny-(miny-by)/ay;

                        minx=(minx-bx)/ax;

                        miny=(miny-by)/ay;

                        if(s-mindist>=0)

                        {

                            moves++;

                            s-=mindist;

                        }

                        else

                        break;

                    }

                    if(minx==x0&&miny==y0)

                    {

                        minx=x*ax+bx;

                        miny=y*ay+by;

                        mindist=minx-x0+miny-y0;

                        if(s>=mindist)

                        {

                            s-=mindist;

                            moves++;

                            while(s>0)

                            {

                                mindist=minx*ax+bx-minx+miny*ay+by-miny;

                                minx=minx*ax+bx;

                                miny=miny*ay+by;

                                if(s-mindist>=0)

                                {

                                    moves++;

                                    s-=mindist;

                                }

                                else

                                break;

                            }

                        }

                    }

                    ans=Math.max(ans,moves);

                }

                x=ax*x+bx;

                y=ay*y+by;

            }

            pw.println(ans);

        }

        pw.flush();

        pw.close();

    }

}


A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

import java.util.*;

public class ErasingZeros {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();

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

			int count = 0;

			String s  = sc.next();

			for(int j = s.indexOf('1'); j < s.lastIndexOf('1'); j++) {

				if(s.charAt(j) == '0') {

					count++;

				}

			}

			System.out.println(count);

		}

	}

}


C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation:   z=acacez=acace (if we choose subsequence aceace);  z=acbcdz=acbcd (if we choose subsequence bcdbcd);  z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3
aabce
ace
abacaba
aax
ty
yyt
OutputCopy1
-1
3

import java.io.*;

import java.math.*;

import java.util.*;

public class C_Obtain_The_String

{

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

    {

        new Solver().solve();

    }

}

//*   Success is not final, failure is not fatal: it is the courage to continue that counts.

class Solver {

    void solve() throws Exception

    {

        int t = sc.nextInt();

        while(t-->0){

            String S = sc.next();

            String G = sc.next();

            // now what

            ArrayList<TreeSet<Integer>> A = new ArrayList<>();

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

                A.add(new TreeSet<>());

            }

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

                int c = S.charAt(i)-'a'+1;

                // now what

                A.get(c).add(i+1);

                // now what to do now Pushkar

            }

            // System.out.println(A);

            int cur =0;

            boolean isPos = true;

            int ans = 0;

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

                int c = G.charAt(i)-'a'+1;

                // System.out.println(c);

                if(A.get(c).isEmpty()){

                    isPos = false;

                    break;

                }

                if(cur==0){

                        cur = A.get(c).first();

                        ans++;

                }else{

                        // we need to find the ceiling of the current

                        Integer next = A.get(c).higher(cur);

                        if(next==null){

                            ans++;

                            cur = A.get(c).first();

                        }else{

                            cur = next;

                        }

                }

            }

            System.out.println(!isPos?-1:(ans));

        }

        sc.flush();

    }

    final Helper sc;

    final int MAXN = 1000_006;

    final long MOD = (long) 1e9 + 7;

    Solver() {

        sc = new Helper(MOD, MAXN);

        sc.initIO(System.in, System.out);

    }

}

class Helper {

    final long MOD;

    final int MAXN;

    final Random rnd;

    public Helper(long mod, int maxn) {

        MOD = mod;

        MAXN = maxn;

        rnd = new Random();

    }

    public static int[] sieve;

    public static ArrayList<Integer> primes;

    public void setSieve() {

        primes = new ArrayList<>();

        sieve = new int[MAXN];

        int i, j;

        for (i = 2; i*i < MAXN; ++i)

            if (sieve[i] == 0) {

                primes.add(i);

                for (j = i*i; j < MAXN; j += i) {

                    sieve[j] = i;

                }

            }

    }

    public static long[] factorial;

    public void setFactorial() {

        factorial = new long[MAXN];

        factorial[0] = 1;

        for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD;

    }

    public long getFactorial(int n) {

        if (factorial == null) setFactorial();

        return factorial[n];

    }

    public long ncr(int n, int r) {

        if (r > n) return 0;

        if (factorial == null) setFactorial();

        long numerator = factorial[n];

        long denominator = factorial[r] * factorial[n - r] % MOD;

        return numerator * pow(denominator, MOD - 2, MOD) % MOD;

    }

    public long[] getLongArray(int size) throws Exception {

        long[] ar = new long[size];

        for (int i = 0; i < size; ++i) ar[i] = nextLong();

        return ar;

    }

    public int[] getIntArray(int size) throws Exception {

        int[] ar = new int[size];

        for (int i = 0; i < size; ++i) ar[i] = nextInt();

        return ar;

        }

      public long gcd(long a, long b) {

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

    }

    public int gcd(int a, int b) {

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

    }

    public long max(long[] ar) {

        long ret = ar[0];

        for (long itr : ar) ret = Math.max(ret, itr);

        return ret;

    }

    public int max(int[] ar) {

        int ret = ar[0];

        for (int itr : ar) ret = Math.max(ret, itr);

        return ret;

    }

    public long min(long[] ar) {

        long ret = ar[0];

        for (long itr : ar) ret = Math.min(ret, itr);

        return ret;

    }

    public int min(int[] ar) {

        int ret = ar[0];

        for (int itr : ar) ret = Math.min(ret, itr);

        return ret;

    }

    public long sum(long[] ar) {

        long sum = 0;

        for (long itr : ar) sum += itr;

        return sum;

    }

    public long sum(int[] ar) {

        long sum = 0;

        for (int itr : ar) sum += itr;

        return sum;

    }

    public void shuffle(int[] ar) {

        int r;

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

            r = rnd.nextInt(ar.length);

            if (r != i) {

                ar[i] ^= ar[r];

                ar[r] ^= ar[i];

                ar[i] ^= ar[r];

            }

        }

    }

    public void shuffle(long[] ar) {

        int r;

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

            r = rnd.nextInt(ar.length);

            if (r != i) {

                ar[i] ^= ar[r];

                ar[r] ^= ar[i];

                ar[i] ^= ar[r];

            }

        }

    }

    public long pow(long base, long exp, long MOD) {

        base %= MOD;

        long ret = 1;

        while (exp > 0) {

            if ((exp & 1) == 1) ret = ret * base % MOD;

            base = base * base % MOD;

            exp >>= 1;

        }

        return ret;

    }

    static byte[] buf = new byte[1000_006];

    static int index, total;

    static InputStream in;

    static BufferedWriter bw;

    public void initIO(InputStream is, OutputStream os) {

        try {

            in = is;

            bw = new BufferedWriter(new OutputStreamWriter(os));

        } catch (Exception e) {

        }

    }

    public void initIO(String inputFile, String outputFile) {

        try {

            in = new FileInputStream(inputFile);

            bw = new BufferedWriter(new OutputStreamWriter(

                    new FileOutputStream(outputFile)));

        } catch (Exception e) {

        }

    }

    private int scan() throws Exception {

        if (index >= total) {

            index = 0;

            total = in.read(buf);

            if (total <= 0)

                return -1;

        }

        return buf[index++];

    }

    public String nextLine() throws Exception {

        int c;

        for (c = scan(); c <= 32; c = scan()) ;

        StringBuilder sb = new StringBuilder();

        for (; c >= 32; c = scan())

            sb.append((char) c);

        return sb.toString();

    }

    public String next() throws Exception {

        int c;

        for (c = scan(); c <= 32; c = scan()) ;

        StringBuilder sb = new StringBuilder();

        for (; c > 32; c = scan())

            sb.append((char) c);

        return sb.toString();

    }

    public int nextInt() throws Exception {

        int c, val = 0;

        for (c = scan(); c <= 32; c = scan()) ;

        boolean neg = c == '-';

        if (c == '-' || c == '+')

            c = scan();

        for (; c >= '0' && c <= '9'; c = scan())

            val = (val << 3) + (val << 1) + (c & 15);

        return neg ? -val : val;

    }

    public long nextLong() throws Exception {

        int c;

        long val = 0;

        for (c = scan(); c <= 32; c = scan()) ;

        boolean neg = c == '-';

        if (c == '-' || c == '+')

            c = scan();

        for (; c >= '0' && c <= '9'; c = scan())

            val = (val << 3) + (val << 1) + (c & 15);

        return neg ? -val : val;

    }

    public void print(Object a) throws Exception {

        bw.write(a.toString());

    }

    public void printsp(Object a) throws Exception {

        print(a);

        print(" ");

    }

    public void println() throws Exception {

        bw.write("\n");

    }

    public void printArray(int[] arr) throws Exception{

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

            print(arr[i]+ " ");

        }

        println();

    }

    public void println(Object a) throws Exception {

        print(a);

        println();

    }

    public void flush() throws Exception {

        bw.flush();

    }

}


A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.

import java.util.Arrays;

import java.util.Scanner;

public class Restaurant {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int cases = input.nextInt();

        while(cases-- > 0)

        {

            int arr[] = new int[3];

            arr[0] = input.nextInt();

		    arr[1] = input.nextInt();

		    arr[2] = input.nextInt();

		    Arrays.sort(arr);

		    int a = arr[0];

		    int b = arr[1];

		    int c = arr[2];

		    int count = 0;

		    if(a != 0){

		        count++;

		        a--;

		    }

		    if(b != 0){

		        count++;

		        b--;

		    }

		    if(c != 0){

		        count++;

		        c--;

		    }

		    if(c != 0 && b != 0){

		        count++;

		        c--;

		        b--;

		    }

		    if(c != 0 && a != 0){

		        count++;

		        c--;

		        a--;

		    }

		    if(b != 0 && a != 0){

		        count++;

		        a--;

		        b--;

		    }

            if(a > 0 && b > 0 && c > 0)

            {

                a--; b--; c--; count++;

            }

            System.out.println(count);

        }

        input.close();

    }

}


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

//package educational.round82;

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.Arrays;

import java.util.InputMismatchException;

public class E {

	InputStream is;

	PrintWriter out;

	String INPUT = "";

	void solve()

	{

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

			char[] s = ns().toCharArray();

			char[] t = ns().toCharArray();

			if(ok(s, t)) {

				out.println("YES");

			}else {

				out.println("NO");

			}

		}

	}

	boolean ok(char[] s, char[] t)

	{

		int n = s.length, m = t.length;

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

			// [0,K), [K,m)

			int[] dp = new int[K+1];

			Arrays.fill(dp, -999999999);

			dp[0] = 0;

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

				for(int j = K;j >= 0;j--) {

					if(dp[j] >= 0) {

						if(j < K && s[i] == t[j]) {

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

						}

						if(dp[j] < m-K && s[i] == t[K+dp[j]]) {

							dp[j]++;

						}

					}

				}

			}

			if(dp[K] == m-K)return true;

		}

		return false;

	}

	void run() throws Exception

	{

		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());

		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();

		solve();

		out.flush();

		tr(System.currentTimeMillis()-s+"ms");

	}

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

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

	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()

	{

		if(lenbuf == -1)throw new InputMismatchException();

		if(ptrbuf >= lenbuf){

			ptrbuf = 0;

			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }

			if(lenbuf <= 0)return -1;

		}

		return inbuf[ptrbuf++];

	}

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

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

	private double nd() { return Double.parseDouble(ns()); }

	private char nc() { return (char)skip(); }

	private String ns()

	{

		int b = skip();

		StringBuilder sb = new StringBuilder();

		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')

			sb.appendCodePoint(b);

			b = readByte();

		}

		return sb.toString();

	}

	private char[] ns(int n)

	{

		char[] buf = new char[n];

		int b = skip(), p = 0;

		while(p < n && !(isSpaceChar(b))){

			buf[p++] = (char)b;

			b = readByte();

		}

		return n == p ? buf : Arrays.copyOf(buf, p);

	}

	private char[][] nm(int n, int m)

	{

		char[][] map = new char[n][];

		for(int i = 0;i < n;i++)map[i] = ns(m);

		return map;

	}

	private int[] na(int n)

	{

		int[] a = new int[n];

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

		return a;

	}

	private int ni()

	{

		int num = 0, b;

		boolean minus = false;

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

		if(b == '-'){

			minus = true;

			b = readByte();

		}

		while(true){

			if(b >= '0' && b <= '9'){

				num = num * 10 + (b - '0');

			}else{

				return minus ? -num : num;

			}

			b = readByte();

		}

	}

	private long nl()

	{

		long num = 0;

		int b;

		boolean minus = false;

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

		if(b == '-'){

			minus = true;

			b = readByte();

		}

		while(true){

			if(b >= '0' && b <= '9'){

				num = num * 10 + (b - '0');

			}else{

				return minus ? -num : num;

			}

			b = readByte();

		}

	}

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

	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }

}


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

import java.util.*;

public class YetAnotherPalindromeProblem {

    public static void main(String args[]) {

        Scanner sr = new Scanner(System.in);

        int t = sr.nextInt();

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

        int prevNum;

        int length;

        int currentNum;

        boolean check;

        int count;

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

            length=sr.nextInt();

            currentNum=sr.nextInt();

            prevNum=currentNum;

            check=false;

            count=0;

            foundNums.put(currentNum,true);

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

                currentNum=sr.nextInt();

                if(foundNums.get(currentNum)!=null){

                    if(currentNum==prevNum){

                        count++;

                        if(count==2){

                            check=true;

                        }

                    }

                    else {

                        check=true;

                    }

                }

                else {

                    count=0;

                }

                prevNum=currentNum;

                foundNums.put(currentNum, true);

            }

            if(check){

                System.out.println("YES");

            }

            else {

                System.out.println("NO");

            }

            foundNums.clear();

        }

    }

}


B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:  The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened;  The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1
OutputCopyYes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No
NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.

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 build(int node, int start, int end,int[]tree,int[]arr) {

      if (start == end) {

        tree[node] = arr[start];

      } else {

        int mid = (start + end) / 2;

        int left = node * 2;

        int right = node * 2 + 1;

        build(left, start, mid,tree,arr);

        build(right, mid + 1, end,tree,arr);

        tree[node] = Math.max(tree[left], tree[right]);

      }

    }

   static int query(int node, int start, int end, int l, int r,int[]tree,int[]arr) {

      if (end < l || r < start)return Integer.MIN_VALUE;

      if (start == end) {

        return tree[node];

      } else if (l <= start && end <= r) {

        return tree[node];

      } else {

        int mid = (start + end) / 2;

        int left = query(node * 2, start, mid, l, r,tree,arr);

        int right = query(node * 2 + 1, mid + 1, end, l, r,tree,arr);

        return Math.max(left, right);

      }

    }

    static int get(int v,int k,int max){

        int lo=1;

        int hi=k;

        int ans=-1;

        while(lo<=hi){

            int mid=(lo+hi)/2;

            if(v/mid>max){

                lo=mid+1;

            }

            else{

                ans=mid;

                hi=mid-1;

            }

        }

        return ans;

    }

    static long solve( ArrayList<Pair> ls,long time,long sx,long sy){

        long ans=0;

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

            Pair p=ls.get(i);

            long stx=p.x;

            long sty=p.y;

            long temp=(Math.abs(sx-stx)+Math.abs(sy-sty));

        long cans=0;

        if(temp<=time)cans++;

        else continue;

        for(int j=i+1;j<ls.size();j++){

            Pair p1=ls.get(j);

    long temp1=(Math.abs(p1.x-stx)+Math.abs(p1.y-sty));

    temp+=temp1;

    // System.out.println(cans+" "+temp+" "+p1.x);

    if(temp<=time)cans++;

    else break;

            stx=p1.x;

            sty=p1.y;

        }

        // System.out.println(time+" "+temp+" "+(time-temp));

        ans=Math.max(ans,cans);

        }

        return ans;

    }

	static void solve(int cnt) {

	    int n=i();

	    int[]arr=new int[n];

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

	    int[]ss=new int[n];

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

	        if(i==n-1)ss[i]=arr[i]-(n-1-i);

	        else ss[i]=Math.min(ss[i+1],arr[i]-(n-1-i));

	    }

	    int t=0;

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

	        t=Math.min(t,arr[i]-i);

	       if(t>=0&&ss[i]>=0){

	           sb.append("Yes\n");

	           return;

	       }

	    }

	    sb.append("No\n");

	}

	public static void main(String[] args) {

		sb = new StringBuilder();

		int test = i();

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

	 int cnt=1;

		while (test-- > 0) {

			solve(cnt);

			cnt++;

		}

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

		long x;

		long y;

		Pair(long 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;

	}

}


E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).  Possible paths for the queries with "YES" answers are:   11-st query: 11 – 33 – 22  22-nd query: 11 – 22 – 33  44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33

import java.io.BufferedOutputStream;

import java.io.Closeable;

import java.io.DataInputStream;

import java.io.Flushable;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.InputMismatchException;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

	static class TaskAdapter implements Runnable {

		@Override

		public void run() {

			InputStream inputStream = System.in;

			OutputStream outputStream = System.out;

			FastReader in = new FastReader(inputStream);

			Output out = new Output(outputStream);

			E1TreesAndQueries solver = new E1TreesAndQueries();

			solver.solve(1, in, out);

			out.close();

		}

	}

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

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

		thread.start();

		thread.join();

	}

	static class E1TreesAndQueries {

		ArrayList<Integer>[] graph;

		int time = 0;

		int[] tin;

		int[] tout;

		int[] rank;

		int[][] up;

		public E1TreesAndQueries() {

		}

		public void dfs(int u, int r) {

			tin[u] = time++;

			rank[u] = r;

			for(int v: graph[u]) {

				graph[v].remove((Integer) u);

				up[0][v] = u;

				dfs(v, r+1);

			}

			tout[u] = time-1;

		}

		public boolean ancestor(int u, int v) {

			return u==-1||(tin[u]<=tin[v]&&tout[u]>=tout[v]);

		}

		public int lca(int u, int v) {

			if(ancestor(u, v)) {

				return u;

			}

			for(int i = 17; i>=0; i--) {

				if(!ancestor(up[i][u], v)) {

					u = up[i][u];

				}

			}

			return up[0][u];

		}

		public int dist(int u, int v) {

			return rank[u]+rank[v]-(rank[lca(u, v)]<<1);

		}

		public boolean valid(int dist, int length) {

			return dist<=length&&(dist&1)==(length&1);

		}

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

			int n = in.nextInt();

			graph = in.nextUndirectedGraph(n, n-1);

			up = new int[18][n];

			tin = new int[n];

			tout = new int[n];

			rank = new int[n];

			up[0][0] = -1;

			dfs(0, 0);

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

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

					if(up[i-1][j]!=-1) {

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

					}

				}

			}

			int q = in.nextInt();

			while(q-->0) {

				int x = in.nextInt()-1, y = in.nextInt()-1, a = in.nextInt()-1, b = in.nextInt()-1, k = in.nextInt();

				if(valid(dist(a, b), k)||valid(dist(a, x)+dist(b, y)+1, k)||valid(dist(a, y)+dist(b, x)+1, k)) {

					pw.println("YES");

				}else {

					pw.println("NO");

				}

			}

		}

	}

	static class Output implements Closeable, Flushable {

		public StringBuilder sb;

		public OutputStream os;

		public int BUFFER_SIZE;

		public boolean autoFlush;

		public String LineSeparator;

		public Output(OutputStream os) {

			this(os, 1<<16);

		}

		public Output(OutputStream os, int bs) {

			BUFFER_SIZE = bs;

			sb = new StringBuilder(BUFFER_SIZE);

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

			autoFlush = false;

			LineSeparator = System.lineSeparator();

		}

		public void println(String s) {

			sb.append(s);

			println();

			if(autoFlush) {

				flush();

			}else if(sb.length()>BUFFER_SIZE >> 1) {

				flushToBuffer();

			}

		}

		public void println() {

			sb.append(LineSeparator);

		}

		private void flushToBuffer() {

			try {

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

			}catch(IOException e) {

				e.printStackTrace();

			}

			sb = new StringBuilder(BUFFER_SIZE);

		}

		public void flush() {

			try {

				flushToBuffer();

				os.flush();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

		public void close() {

			flush();

			try {

				os.close();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

	}

	static interface InputReader {

		int nextInt();

		default ArrayList<Integer>[] nextUndirectedGraph(int n, int m) {

			ArrayList<Integer>[] ret = new ArrayList[n];

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

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

			}

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

				int u = nextInt()-1, v = nextInt()-1;

				ret[u].add(v);

				ret[v].add(u);

			}

			return ret;

		}

	}

	static class FastReader implements InputReader {

		final private int BUFFER_SIZE = 1<<16;

		private DataInputStream din;

		private byte[] buffer;

		private int bufferPointer;

		private int bytesRead;

		public FastReader(InputStream is) {

			din = new DataInputStream(is);

			buffer = new byte[BUFFER_SIZE];

			bufferPointer = bytesRead = 0;

		}

		public int nextInt() {

			int ret = 0;

			byte c = skipToDigit();

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

			if(neg) {

				c = read();

			}

			do {

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

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

			if(neg) {

				return -ret;

			}

			return ret;

		}

		private boolean isDigit(byte b) {

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

		}

		private byte skipToDigit() {

			byte ret;

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

			return ret;

		}

		private void fillBuffer() {

			try {

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

			}catch(IOException e) {

				e.printStackTrace();

				throw new InputMismatchException();

			}

			if(bytesRead==-1) {

				buffer[0] = -1;

			}

		}

		private byte read() {

			if(bytesRead==-1) {

				throw new InputMismatchException();

			}else if(bufferPointer==bytesRead) {

				fillBuffer();

			}

			return buffer[bufferPointer++];

		}

	}

}


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

import java.util.*;

import java.io.*;

public class YetAnotherTetrisProblem {

    public static void main(String[] args){

        FastReader sc = new FastReader();

        int t = sc.nextInt();

        while (t-- > 0) {

            int n = sc.nextInt();

            boolean par = true;

            boolean res = true;

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

                int a = sc.nextInt();

                if(i == 0 && a % 2 == 0) par = true;

                else if(i == 0 && a % 2 == 1) par = false;

                if(par && i != 0){

                    if(a % 2 == 1) res = false;

                }

                else if(!par && i != 0){

                    if(a % 2 == 0) res = false;

                }

            }

            System.out.println(res ? "YES":"NO");

        }

    }

    static class Maths {

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

            if (b == 0)

                return a;

            return gcd(b, a % b);

        }

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

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

        }

    }

    static class NextPermutation {

        // Function to swap the data

        // present in the left and right indices

        public static int[] swap(int data[], int left, int right)

        {

            // Swap the data

            int temp = data[left];

            data[left] = data[right];

            data[right] = temp;

            // Return the updated array

            return data;

        }

        // Function to reverse the sub-array

        // starting from left to the right

        // both inclusive

        public static int[] reverse(int data[], int left, int right)

        {

            // Reverse the sub-array

            while (left < right) {

                int temp = data[left];

                data[left++] = data[right];

                data[right--] = temp;

            }

            // Return the updated array

            return data;

        }

        // Function to find the next permutation

        // of the given integer array

        public static boolean findNextPermutation(int data[])

        {

            // If the given dataset is empty

            // or contains only one element

            // next_permutation is not possible

            if (data.length <= 1)

                return false;

            int last = data.length - 2;

            // find the longest non-increasing suffix

            // and find the pivot

            while (last >= 0) {

                if (data[last] < data[last + 1]) {

                    break;

                }

                last--;

            }

            // If there is no increasing pair

            // there is no higher order permutation

            if (last < 0)

                return false;

            int nextGreater = data.length - 1;

            // Find the rightmost successor to the pivot

            for (int i = data.length - 1; i > last; i--) {

                if (data[i] > data[last]) {

                    nextGreater = i;

                    break;

                }

            }

            // Swap the successor and the pivot

            data = swap(data, nextGreater, last);

            // Reverse the suffix

            data = reverse(data, last + 1, data.length - 1);

            // Return true as the next_permutation is done

            return true;

        }

    }

    static class UnionFind { // OOP style

        private ArrayList<Integer> p, rank, setSize;

        private int numSets;

        public UnionFind(int N) {

            p = new ArrayList<Integer>(N);

            rank = new ArrayList<Integer>(N);

            setSize = new ArrayList<Integer>(N);

            numSets = N;

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

                p.add(i);

                rank.add(0);

                setSize.add(1);

            }

        }

        public int findSet(int i) {

            if (p.get(i) == i)

                return i;

            else {

                int ret = findSet(p.get(i));

                p.set(i, ret);

                return ret;

            }

        }

        public Boolean isSameSet(int i, int j) {

            return findSet(i) == findSet(j);

        }

        public void unionSet(int i, int j) {

            if (!isSameSet(i, j)) {

                numSets--;

                int x = findSet(i), y = findSet(j);

                // rank is used to keep the tree short

                if (rank.get(x) > rank.get(y)) {

                    p.set(y, x);

                    setSize.set(x, setSize.get(x) + setSize.get(y));

                } else {

                    p.set(x, y);

                    setSize.set(y, setSize.get(y) + setSize.get(x));

                    if (rank.get(x) == rank.get(y))

                        rank.set(y, rank.get(y) + 1);

                }

            }

        }

        public int numDisjointSets() {

            return numSets;

        }

        public int sizeOfSet(int i) {

            return setSize.get(findSet(i));

        }

    }

    static class Pair<A, B> {

        A first;

        B second;

        // Constructor

        public Pair(A first, B second) {

            this.first = first;

            this.second = second;

        }

    }

    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 {

                if (st.hasMoreTokens()) {

                    str = st.nextToken("\n");

                } else {

                    str = br.readLine();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        boolean hasNext() {

            if (st != null && st.hasMoreTokens()) {

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

    }

}


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

		}

	}

}