E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair).  Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.

import java.io.*;

import java.util.Arrays;

import java.util.StringJoiner;

import java.util.StringTokenizer;

public class MainE {

    static int N;

    static int[] A;

    public static void main(String[] args) {

        var sc = new FastScanner(System.in);

        N = sc.nextInt();

        A = sc.nextIntArray(N);

        System.out.println(solve());

    }

    private static int solve() {

        // [L, R)

        var merged = new int[N][N+1];

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

            merged[i][i+1] = A[i];

        }

        for (int w = 2; w <= N; w++) {

            for (int l = 0; l < N-w+1; l++) {

                int r = l+w;

                int lr = -1;

                for (int m = l+1; m < r; m++) {

                    if( merged[l][m] != -1 && merged[l][m] == merged[m][r] ) {

                        lr = merged[l][m]+1;

                    }

                }

                merged[l][r] = lr;

            }

        }

        var len = new int[N][N+1];

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

            len[i][i+1] = 1;

        }

        for (int w = 2; w <= N; w++) {

            for (int l = 0; l < N-w+1; l++) {

                int r = l+w;

                int lr = Integer.MAX_VALUE;

                if( merged[l][r] != -1 ) {

                    len[l][r] = 1;

                    continue;

                }

                for (int m = l+1; m < r; m++) {

                    lr = Math.min(lr, len[l][m] + len[m][r]);

                }

                len[l][r] = lr;

            }

        }

        return len[0][N];

    }

    @SuppressWarnings("unused")

    static class FastScanner {

        private final BufferedReader reader;

        private StringTokenizer tokenizer;

        FastScanner(InputStream in) {

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

            tokenizer = null;

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

            }

            return tokenizer.nextToken();

        }

        String nextLine() {

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

                try {

                    return reader.readLine();

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

            }

            return tokenizer.nextToken("\n");

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        int[] nextIntArray(int n) {

            var a = new int[n];

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

            return a;

        }

        int[] nextIntArray(int n, int delta) {

            var a = new int[n];

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

            return a;

        }

        long[] nextLongArray(int n) {

            var a = new long[n];

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

            return a;

        }

    }

    static void writeLines(int[] as) {

        var pw = new PrintWriter(System.out);

        for (var a : as) pw.println(a);

        pw.flush();

    }

    static void writeLines(long[] as) {

        var pw = new PrintWriter(System.out);

        for (var a : as) pw.println(a);

        pw.flush();

    }

    static void writeSingleLine(int[] as) {

        var pw = new PrintWriter(System.out);

        for (var i = 0; i < as.length; i++) {

            if (i != 0) pw.print(" ");

            pw.print(as[i]);

        }

        pw.println();

        pw.flush();

    }

    static void debug(Object... args) {

        var j = new StringJoiner(" ");

        for (var arg : args) {

            if (arg == null) j.add("null");

            else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));

            else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));

            else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));

            else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));

            else j.add(arg.toString());

        }

        System.err.println(j.toString());

    }

}


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

import java.lang.*;

import java.io.*;

public class Main

{

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

    static final FastReader sc = new FastReader();

    //I invented a new word!Plagiarism!

    //Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them

    //What do Alexander the Great and Winnie the Pooh have in common? Same middle name.

    //I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!

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

    //PriorityQueue<Integer> pq=new PriorityQueue<>();

    //char[] a = s.toCharArray();

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

    public static boolean sorted(int a[])

    {

        int n=a.length,i;

        int b[]=new int[n];

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

        b[i]=a[i];

        Arrays.sort(b);

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

        {

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

            return false;

        }

        return true;

    }

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

	{

	    int tes=sc.nextInt();

	   lable: while(tes-->0)

	    {

	        int n=sc.nextInt();

	        int k=sc.nextInt();

	        int max=0,i,flag=0;

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

	        {

	              int x=sc.nextInt();

	              if(x==k)

	                   flag=1;

	              max=Math.max(max,x);

	        }

	        if(flag==1)

	        System.out.println(1);

	        else{

	              int good=(int)Math.ceil((double)k/max);

	              System.out.println(Math.max(2,good));

	        }

	     }

	}

	public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)

    {

        if (high >= low) {

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

            if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)

                return mid;

            else if (x > arr.get(mid))

                return first(arr, (mid + 1), high, x, n);

            else

                return first(arr, low, (mid - 1), x, n);

        }

        return -1;

    }

	public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)

    {

        if (high >= low) {

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

            if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)

                return mid;

            else if (x < arr.get(mid))

                return last(arr, low, (mid - 1), x, n);

            else

                return last(arr, (mid + 1), high, x, n);

        }

        return -1;

    }

	public static int lis(int[] arr) {

	int n = arr.length;

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

	al.add(arr[0]);

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

		int x = al.get(al.size()-1);

		if(arr[i]>=x) {

			al.add(arr[i]);

		}else {

			int v = upper_bound(al, 0, al.size(), arr[i]);

			al.set(v, arr[i]);

		}

	}

	return al.size();

}

	public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

        if (ar.get((int)mid) <k)

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

        if (ar.get(mid) <=k)

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

static boolean isPrime(long N)

    {

        if (N<=1)  return false;

        if (N<=3)  return true;

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

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

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

                return false;

        return true;

    }

    static int countBits(long a)

    {

        return (int)(Math.log(a)/Math.log(2)+1);

    }

    static long fact(long N)

    {

        long mod=1000000007;

        long n=2;

        if(N<=1)return 1;

        else

        {

            for(int i=3; i<=N; i++)n=(n*i)%mod;

        }

        return n;

    }

    private static boolean isInteger(String s) {

        try {

            Integer.parseInt(s);

        } catch (NumberFormatException e) {

            return false;

        } catch (NullPointerException e) {

            return false;

        }

        return true;

    }

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

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

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

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

    }

    private static boolean isPalindrome(String str) {

        int i = 0, j = str.length() - 1;

        while (i < j)

            if (str.charAt(i++) != str.charAt(j--))

                return false;

        return true;

    }

    private static String reverseString(String str) {

        StringBuilder sb = new StringBuilder(str);

        return sb.reverse().toString();

    }

	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;

        }

    }

}


F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either:  find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:

import java.io.*;

import java.util.*;

public class Main{

	static LinkedList<Integer>[]adj;

	static int k,dep[],par[];

	static boolean[]take,v;

	static LinkedList<Integer>cycle;

	static void dfs(int i,boolean leaf) {

		v[i]=true;

		boolean isLeaf=true;

		boolean adjc=false;

		for(int j:adj[i]) {

			if(!v[j]) {

				isLeaf=false;

				dfs(j,leaf);

			}

			adjc|=take[j];

		}

		if(isLeaf) {

			take[i]=leaf;

			return;

		}

		if(!adjc) {

			take[i]=true;

		}

	}

	static void dfs2(int i,int depth) {

//		System.out.println(i);

		dep[i]=depth;

		v[i]=true;

		for(int j:adj[i]) {

			if(j==par[i])continue;

			if(!v[j]) {

				par[j]=i;

				dfs2(j,depth+1);

			}

			else {

				if(dep[i]<=dep[j])continue;

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

				if(cnt>=k && cycle==null) {

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

					cycle=new LinkedList<>();

					int cur=i;

					while(cur!=j) {

						cycle.add(cur);

						cur=par[cur];

					}

					cycle.add(j);

				}

			}

		}

	}

	static void main() throws Exception{

		int n=sc.nextInt(),m=sc.nextInt();

		k=1;

		while(k*k<n) {

			k++;

		}

		adj=new LinkedList[n];

		for(int i=0;i<n;i++)adj[i]=new LinkedList<>();

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

			int x=sc.nextInt()-1,y=sc.nextInt()-1;

			adj[x].add(y);

			adj[y].add(x);

		}

		dep=new int[n];

		par=new int[n];

		take=new boolean[n];

		v=new boolean[n];

		StringBuilder opt1=new StringBuilder(),opt2=new StringBuilder();

		dfs(0,true);

		int c=0;

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

			if(take[i]) {

				opt1.append((i+1)+" ");

				c++;

			}

		}

		if(c==k) {

			pw.println(1);

			pw.println(opt1);

			return;

		}

		take=new boolean[n];

		v=new boolean[n];

		dfs(0,false);

		c=0;

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

			if(take[i]) {

				opt2.append((i+1)+" ");

				c++;

			}

		}

		if(c==k) {

			pw.println(1);

			pw.println(opt2);

			return;

		}

		v=new boolean[n];

		par[0]=-1;

		dfs2(0, 0);

		pw.println(2);

		pw.println(cycle.size());

		while(!cycle.isEmpty()) {

			pw.print((cycle.poll()+1)+" ");

		}

		pw.println();

	}

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

		pw=new PrintWriter(System.out);

		sc = new MScanner(System.in);

//		int tc=sc.nextInt();

//		while(tc-->0)

			main();

		pw.flush();

	}

	static PrintWriter pw;

	static MScanner  sc;

	static class MScanner {

		StringTokenizer st;

		BufferedReader br;

		public MScanner(InputStream system) {

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

		}

		public MScanner(String file) throws Exception {

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

		}

		public String next() throws IOException {

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

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

			return st.nextToken();

		}

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

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

	        return in;

		}

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

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

	        return in;

		}

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

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

	        shuffle(in);

	        Arrays.sort(in);

	        return in;

		}

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

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

	        shuffle(in);

	        Arrays.sort(in);

	        return in;

		}

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

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

	        return in;

		}

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

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

	        return in;

		}

		public String nextLine() throws IOException {

			return br.readLine();

		}

		public int nextInt() throws IOException {

			return Integer.parseInt(next());

		}

		public double nextDouble() throws IOException {

			return Double.parseDouble(next());

		}

		public char nextChar() throws IOException {

			return next().charAt(0);

		}

		public long nextLong() throws IOException {

			return Long.parseLong(next());

		}

		public boolean ready() throws IOException {

			return br.ready();

		}

		public void waitForInput() throws InterruptedException {

			Thread.sleep(3000);

		}

	}

	static void shuffle(int[]in) {

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

			int idx=(int)(Math.random()*in.length);

			int tmp=in[i];

			in[i]=in[idx];

			in[idx]=tmp;

		}

	}

	static void shuffle(long[]in) {

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

			int idx=(int)(Math.random()*in.length);

			long tmp=in[i];

			in[i]=in[idx];

			in[idx]=tmp;

		}

	}

}


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

import java.util.*;

public class Main {

    static int[] depth;

	static int[][] table;

	static ArrayList<Integer>[] tree;

	static void dfs(int curr,int p) {

		table[curr][0]=p;

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

            table[curr][i]=table[table[curr][i-1]][i-1];

        }

		for(int child:tree[curr]) {

			if(child!=p) {

				depth[child]=1+depth[curr];

				dfs(child,curr);

			}

		}

	}

	static int lca(int u, int v)

    {

        if(depth[u]<depth[v]) {

            int temp=u;

            u=v;

            v=temp;

        }

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

            if ((depth[u]-(int)Math.pow(2, i))>=depth[v]) {

                u=table[u][i];

            }

        }

        if (u==v) {

            return u;

        }

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

            if (table[u][i]!=table[v][i]) {

                u=table[u][i];

                v=table[v][i];

            }

        }

        return table[u][0];

    }

	static int dist(int a, int b) {

		  int c = lca(a, b);

		  int ans = depth[a] + depth[b] - 2*depth[c];

		  return ans;

	}

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

	{

		FastScanner f = new FastScanner();

		int ttt=1;

//		ttt=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

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

			int n=f.nextInt();

			tree=new ArrayList[n];

			depth=new int[n];

			table=new int[n][19];

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

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

				int u=f.nextInt()-1;

				int v=f.nextInt()-1;

				tree[u].add(v);

				tree[v].add(u);

			}

			dfs(0,0);

			int q=f.nextInt();

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

				int x=f.nextInt()-1;

				int y=f.nextInt()-1;

				int a=f.nextInt()-1;

				int b=f.nextInt()-1;

				int k=f.nextInt();

				int d1 = dist(a, b);

			    int d2 = dist(a, x) + 1 + dist(y, b);

			    int d3 = dist(a, y) + 1 + dist(x, b);

			    boolean w1 = d1 <= k && d1 % 2 == k % 2;

			    boolean w2 = d2 <= k && d2 % 2 == k % 2;

			    boolean w3 = d3 <= k && d3 % 2 == k % 2;

			    if (w1 || w2 || w3) {

			      System.out.println("YES");

			    } else {

			      System.out.println("NO");

			    }

			}

		}

		out.close();

	}

	static void sort(int[] p) {

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

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

        Collections.sort(q);

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

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}


A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES

import java.util.*;

import java.util.Scanner;

public class CollectingCoins {

    static java.util.Scanner reader=new Scanner(System.in);

    public static void main(String[] args) {

        int t=reader.nextInt();

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

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

            int a=reader.nextInt();

            int b=reader.nextInt();

            int c=reader.nextInt();

            int n=reader.nextInt();

            list.add(a);

            list.add(b);

            list.add(c);

            Collections.sort(list);

            int max=Collections.max(list);

            int rem=0;

            int coins=0;

            for (int x=0;x<list.size()-1;x++){

                rem+=max-list.get(x);

            }

            if (rem>n){

                System.out.println("NO");

            }

            else {

                if ((n-rem)%3==0){

                    System.out.println("YES");

                }

                else {

                    System.out.println("NO");

                }

            }

        }

    }

}


A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after 11 minute — AAPAAPPAAPPP  after 22 minutes — AAAAAAPAAAPP  after 33 minutes — AAAAAAAAAAAP  after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.

import java.util.*;
public class JavaApplication51 {
static Scanner z = new Scanner(System.in);
    public static void main(String[] args) {
       int d=z.nextInt();

       while(d-->0){
            int s=z.nextInt();
           String c=z.next();
    StringBuffer k = new StringBuffer(c);
    int count=0;
   while(true){
    boolean h=false;
    String l=k.toString();
    StringBuffer r=new StringBuffer("") ;
        for (int i = 1; i < s; i++) {
            if(k.charAt(i-1)=='A'&&k.charAt(i)=='P'){
                k.setCharAt(i, 'A');
                h=true;
             i++;
            }
        }
         r=k;
        if(h){
           count++;
        }
      if(l.equals(r.toString())){
          break;
      }
    }
       System.out.println(count);
        }
       }
    }


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

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

import java.io.*;

import java.util.*;

public class D {

	static void query(int l, int r) {

		System.out.printf("? %d %d\n", l, r);

	}

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

		Scanner sc = new Scanner();

		int n = sc.nextInt();

		query(1, n);

		char[] ans = new char[n];

		if (n == 1) {

			ans = sc.next().toCharArray();

		} else {

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

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

				String s = sc.get();

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

			}

			query(2, n);

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

				String s = sc.get();

				map.put(s, map.get(s) - 1);

			}

			ArrayList<String> a = new ArrayList();

			for (String x : map.keySet()) {

				if (map.get(x) > 0)

					a.add(x);

			}

			Collections.sort(a, (x, y) -> x.length() - y.length());

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

				String curr = a.get(i);

				int[] f = new int[26];

				for (char c : curr.toCharArray())

					f[c - 'a']++;

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

					f[ans[j] - 'a']--;

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

					if (f[c] > 0)

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

			}

		}

		System.out.printf("! %s\n", new String(ans));

	}

	static class Scanner {

		BufferedReader br;

		StringTokenizer st;

		Scanner() {

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

		}

		String get() throws IOException {

			String ans = next();

			char[] s = ans.toCharArray();

			Arrays.sort(s);

			return new String(s);

		}

		Scanner(String fileName) throws FileNotFoundException {

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

		}

		String next() throws IOException {

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

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

			return st.nextToken();

		}

		String nextLine() throws IOException {

			return br.readLine();

		}

		int nextInt() throws IOException {

			return Integer.parseInt(next());

		}

		long nextLong() throws NumberFormatException, IOException {

			return Long.parseLong(next());

		}

		double nextDouble() throws NumberFormatException, IOException {

			return Double.parseDouble(next());

		}

		boolean ready() throws IOException {

			return br.ready();

		}

	}

	static void sort(int[] a) {

		shuffle(a);

		Arrays.sort(a);

	}

	static void shuffle(int[] a) {

		int n = a.length;

		Random rand = new Random();

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

			int tmpIdx = rand.nextInt(n);

			int tmp = a[i];

			a[i] = a[tmpIdx];

			a[tmpIdx] = tmp;

		}

	}

}


C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

// practice with kaiboy
import java.io.*;
import java.util.*;

public class CF1313C2 extends PrintWriter {
	CF1313C2() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF1313C2 o = new CF1313C2(); o.main(); o.flush();
	}

	void main() {
		int n = sc.nextInt();
		int[] aa = new int[n + 2];
		for (int i = 1; i <= n; i++)
			aa[i] = sc.nextInt();
		long[] dp = new long[n + 2];
		long[] dq = new long[n + 2];
		int[] pp = new int[n + 2]; pp[0] = -1;
		int[] qq = new int[n + 2]; qq[n + 1] = n + 2;
		int[] qu = new int[n + 2];
		int cnt = 0;
		qu[cnt++] = 0;
		for (int p, i = 1; i <= n; i++) {
			while (aa[p = qu[cnt - 1]] >= aa[i])
				cnt--;
			qu[cnt++] = i;
			pp[i] = p;
			dp[i] = dp[p] + (long) (i - p) * aa[i];
		}
		cnt = 0;
		qu[cnt++] = n + 1;
		for (int q, i = n; i >= 1; i--) {
			while (aa[q = qu[cnt - 1]] >= aa[i])
				cnt--;
			qu[cnt++] = i;
			qq[i] = q;
			dq[i] = dq[q] + (long) (q - i) * aa[i];
		}
		int h = 0;
		for (int i = 1; i <= n; i++)
			if (h == 0 || dp[h] + dq[h] - aa[h] < dp[i] + dq[i] - aa[i])
				h = i;
		for (int i = h; i >= 1; ) {
			int a = aa[i];
			int p = pp[i];
			while (i != p) {
				aa[i] = a;
				i--;
			}
		}
		for (int i = h; i <= n; ) {
			int a = aa[i];
			int q = qq[i];
			while (i != q) {
				aa[i] = a;
				i++;
			}
		}
		for (int i = 1; i <= n; i++)
			print(aa[i] + " ");
		println();
	}
}


D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10
codeforces
dodivthree
OutputCopy5
7 8
4 9
2 2
9 10
3 1
InputCopy7
abaca?b
zabbbcc
OutputCopy5
6 5
2 3
4 6
7 4
1 2
InputCopy9
bambarbia
hellocode
OutputCopy0
InputCopy10
code??????
??????test
OutputCopy10
6 2
1 6
7 3
3 5
4 8
9 7
5 1
2 4
10 9
8 10

import java.io.*;
import java.util.*;

public class EvenorOdd {
	public static void main(String[] args) throws IOException {
		BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		int n=Integer.parseInt(f.readLine());
		String s=f.readLine();
		String s2=f.readLine();
		TreeSet<Integer>[] arr=new TreeSet[27];
		TreeSet<Integer>[] barr=new TreeSet[27];
		for(int i=0;i<27;i++) {
			arr[i]=new TreeSet<Integer>();
			barr[i]=new TreeSet<Integer>();
		}
		for(int i=0;i<n;i++) {
			if(s.charAt(i)=='?') {
				arr[26].add(i+1);
			}
			else {
				arr[s.charAt(i)-97].add(i+1);
			}
			if(s2.charAt(i)=='?') {
				barr[26].add(i+1);
			}
			else {
				barr[s2.charAt(i)-97].add(i+1);
			}
		}
		int ans=0;
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<26;i++) {
			while(!arr[i].isEmpty()&&!barr[i].isEmpty()) {
				ans++;
				sb.append(arr[i].pollFirst()+" "+barr[i].pollFirst()+"\n");
			}
		}
		for(int i=0;i<26;i++) {
			while(!arr[i].isEmpty()&&!barr[26].isEmpty()) {
				ans++;
				sb.append(arr[i].pollFirst()+" "+barr[26].pollFirst()+"\n");
			}
			while(!arr[26].isEmpty()&&!barr[i].isEmpty()) {
				ans++;
				sb.append(arr[26].pollFirst()+" "+barr[i].pollFirst()+"\n");
			}
		}
		while(!arr[26].isEmpty()&&!barr[26].isEmpty()) {
			ans++;
			sb.append(arr[26].pollFirst()+" "+barr[26].pollFirst()+"\n");
		}
		out.println(ans);
		out.println(sb.toString());
		out.close();
		f.close();
	}
}


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main {

	static int[] ft;

	static void update(int i, int n, int x) {

		while (i < n) {

			ft[i] += x;

			i |= i + 1;

		}

	}

	static int query(int i) {

		int x = 0;

		while (i >= 0) {

			x += ft[i];

			i &= i + 1; i--;

		}

		return x;

	}

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

		int n1=m-l+1;

		int n2=r-m;

		int L[]=new int[n1];

		int R[]=new int[n2];

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

		{

		  L[i]=arr[l+i];

		}

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

		{

		  R[j]=arr[m+1+j];

		}

		int i=0;

		int j=0;

		int k=l;

		while(i<n1 && j<n2)

		{

		  if(L[i]<=R[j])

		  {

			arr[k]=L[i];

			++i;

		  }

		  else{

			arr[k]=R[j];

			++j;

		  }

		  ++k;

		}

		while(i<n1)

		{

		  arr[k]=L[i];

		  ++i;

		  ++k;

		}

		while(j<n2)

		{

		  arr[k]=R[j];

		  ++j;

		  ++k;

		}

	}

	public static void r2(int arr[],int l,int r)

	{

	  if(l<r)

	  {

		int m=(l+r)/2;

		r2(arr,l,m);

		r2(arr,m+1,r);

		r(arr,l,m,r);

	  }

	}

	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 int gcd(int a, int b)

	{

		if (a == 0)

			return b;

		return gcd(b % a, a);

	}

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

{

//  try {

// //   FileOutputStream output=new FileOutputStream("C:\\Users\\icons\\Desktop\\java\\output.txt");

// //   PrintStream out=new PrintStream(output);

// //   Diverting the output stream into file "temp.out".Comment the below line to use console

// //   System.setOut(out);

//   InputStream input=new FileInputStream("C:\\Users\\icons\\Desktop\\java\\input.txt");

//   //Diverting the input stream into file "temp.in".Comment the below line to use console

//   System.setIn(input);

//  } catch (FileNotFoundException e) {

//   e.printStackTrace();

//  }

  FastReader sc = new FastReader();

		int n = sc.nextInt();

		int m = sc.nextInt();

		int[] ii = new int[m];

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

			ii[h] = sc.nextInt() - 1;

		int[] imin = new int[n];

		int[] imax = new int[n];

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

			imin[i] = imax[i] = i;

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

			imin[ii[h]] = 0;

		int[] hh = new int[n];

		Arrays.fill(hh, m);

		for (int h = m - 1; h >= 0; h--)

			hh[ii[h]] = h;

		ft = new int[m];

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

			imax[i] += query(hh[i] - 1);

			update(hh[i], m, 1);

		}

		Arrays.fill(ft, 0);

		Arrays.fill(hh, m);

		for (int h = m - 1; h >= 0; h--) {

			int i = ii[h];

			imax[i] = Math.max(imax[i], query(hh[i] - 1));

			update(hh[i], m, -1);

			hh[i] = h;

			update(hh[i], m, 1);

		}

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

			System.out.println((imin[i] + 1) + " " + (imax[i] + 1));

	}

}


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

	public static int parts(int a, int b, int c) {

		int count = 0;

		if (a!=0) {

			count++;a--;

		}

		if (c!=0) {

			count++;c--;

		}

		if (b!=0) {

			count++;b--;

		}

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

			count++;

			a--;b--;

		}

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

			count++;

			a--;c--;

		}

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

			count++;

			c--;b--;

		}

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

			count++;

		}

		return count;

	}

	public static void main (String[] args) {

		Scanner m = new Scanner(System.in);

		int n = m.nextInt();

		int[] arr = new int[3];

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

			arr[0]= m.nextInt();;

			arr[1]= m.nextInt();;

			arr[2]= m.nextInt();;

			Arrays.sort(arr);

			System.out.println(parts(arr[2],arr[1],arr[0]));

		}

	}

}


B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5
1 0 1 0 1
OutputCopy2
InputCopy6
0 1 0 1 1 0
OutputCopy2
InputCopy7
1 0 1 1 1 0 1
OutputCopy3
InputCopy3
0 0 0
OutputCopy0
NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.

import java.util.ArrayList;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

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

        int count = 0;

        int counter = 0;

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

            arrayList.add(sc.nextInt());

        }

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

            if (arrayList.get(i % t) == 1) {

                counter++;

                count = Math.max(count, counter);

            } else {

                counter = 0;

            }

        }

        System.out.println(count);

    }

}


import java.util.Scanner;

public class zas {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int t = input.nextInt();

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

            int a, b, c, n;

            a = input.nextInt();

            b = input.nextInt();

            c = input.nextInt();

            n = input.nextInt();

            if ((a + b + c + n) % 3 == 0 && n >= Math.max(Math.max(a, b), c) * 3 - (a + b + c)) {

                System.out.println("YES");

            } else {

                System.out.println("NO");

            }

        }

    }

}


C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10

//package assignment;

import java.io.PrintWriter;

import java.util.*;

public class TreapMap<K extends Comparable<K>, V> implements Treap<K, V> {

    TreapNode<K, V> head;

    @Override

    public V lookup(K key) {

        TreapNode<K, V> tr = lookupH(key);

        if(tr == null) return null;

        else return tr.getValue();

    }

    private TreapNode<K, V> lookupH(K key) {

        TreapNode<K, V> curr = head;

        while (true) {

            if(curr == null) return null;

            int compareVal = curr.getKey().compareTo(key);

            if (compareVal > 0) curr = curr.getLeft();

            else if (compareVal < 0) curr = curr.getRight();

            else return curr;

        }

    }

    public void insert(K key, V value, int prio) {

        TreapNode<K, V> curr = head;

        TreapNode<K, V> toInsert = new TreapNode<>(key, value, prio);

        ArrayList<TreapNode<K, V>> path = new ArrayList<>();

        if(head == null) {

            head = toInsert;

            return;

        }

        while (true) {

            path.add(curr);

            int compareVal = curr.getKey().compareTo(key);

            if (compareVal > 0) {

                if(curr.getLeft() == null) {

                    curr.setLeft(toInsert);

                    break;

                }

                curr = curr.getLeft();

            }

            else if(compareVal == 0 && prio != Treap.MAX_PRIORITY) { // override if we're not adding a split node

                curr.setValue(value);

                return;

            }

            else {

                if(curr.getRight() == null) {

                    curr.setRight(toInsert);

                    break;

                }

                curr = curr.getRight();

            }

        }

        curr = toInsert;

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

            if(path.get(i).getPrio() < curr.getPrio()) {

                if(path.get(i - 1).getLeft() == path.get(i) && path.get(i).getLeft() == curr) {

                    rotateLL(path.get(i - 1));

                }

                else if(path.get(i - 1).getLeft() == path.get(i) && path.get(i).getRight() == curr) {

                    rotateLR(path.get(i - 1));

                }

                else if(path.get(i - 1).getRight() == path.get(i) && path.get(i).getLeft() == curr) {

                    rotateRL(path.get(i - 1));

                }

                else if(path.get(i - 1).getRight() == path.get(i) && path.get(i).getRight() == curr) {

                    rotateRR(path.get(i - 1));

                }

                else {

                    System.out.println("insert is BROKEN LOL");

                }

            }

            else break;

        }

        if(head.getPrio() < curr.getPrio()) {

            if(head.getLeft() == curr) {

                head.setLeft(curr.getRight());

                curr.setRight(head);

            }

            else {

                head.setRight(curr.getLeft());

                curr.setLeft(head);

            }

            head = curr;

        }

    }

    @Override

    public void insert(K key, V value) {

        Random r = new Random();

        insert(key, value, r.nextInt(Treap.MAX_PRIORITY));

    }

    @Override

    public V remove(K key) {

        TreapNode<K, V> par = null;

        TreapNode<K, V> curr = head;

        while (true) {

            if(curr == null) return null;

            if(curr.getKey() == null) break; // join case

            int compareVal = curr.getKey().compareTo(key);

            if (compareVal > 0) {

                par = curr;

                curr = curr.getLeft();

            }

            else if (compareVal < 0) {

                par = curr;

                curr = curr.getRight();

            }

            else break;

        }

        while(curr.getLeft() != null || curr.getRight() != null) {

            int lPrio = -1;

            if(curr.getLeft() != null) lPrio = curr.getLeft().getPrio();

            int rPrio = -1;

            if(curr.getRight() != null) rPrio = curr.getRight().getPrio();

            if(rPrio > lPrio) { // swap with right then

                if(par == null) { // curr = head

                    TreapNode<K, V> temp = curr.getRight();

                    assert temp != null;

                    curr.setRight(temp.getLeft());

                    temp.setLeft(curr);

                    head = temp;

                    par = temp;

                }

                else {

                    TreapNode<K, V> temp = curr.getRight();

                    if(par.getLeft() == curr) {

                        par.setLeft(temp);

                    }

                    else {

                        par.setRight(temp);

                    }

                    curr.setRight(temp.getLeft());

                    temp.setLeft(curr);

                    par = temp;

                }

            } else {

                if(par == null) { // curr = head

                    TreapNode<K, V> temp = curr.getLeft();

                    assert temp != null;

                    curr.setLeft(temp.getRight());

                    temp.setRight(curr);

                    head = temp;

                    par = temp;

                }

                else {

                    TreapNode<K, V> temp = curr.getLeft();

                    if(par.getLeft() == curr) {

                        par.setLeft(temp);

                    }

                    else {

                        par.setRight(temp);

                    }

                    curr.setLeft(temp.getRight());

                    temp.setRight(curr);

                    par = temp;

                }

            }

        }

        if(par == null) head = null; // head = node

        else if(par.getLeft() == curr) par.setLeft(null);

        else if(par.getRight() == curr) par.setRight(null);

        return curr.getValue();

    }

    @Override

    public Treap<K, V>[] split(K key) {

        Treap<K, V>[] ans = new TreapMap[2];

        this.insert(key, null, Treap.MAX_PRIORITY);

        TreapMap<K, V> t1 = new TreapMap<>();

        t1.head = head.getLeft();

        TreapMap<K, V> t2 = new TreapMap<>();

        t2.head = head.getRight();

        ans[0] = t1;

        ans[1] = t2;

        return ans;

    }

    @Override

    public void join(Treap<K, V> t) {

        if(!(t instanceof TreapMap)) throw new IllegalArgumentException();

        TreapMap<K, V> tTr = (TreapMap<K, V>) t;

        TreapNode<K, V> joiner = new TreapNode<>(null, null, Treap.MAX_PRIORITY);

        if(tTr.head.getKey().compareTo(this.head.getKey()) < 0) {

            joiner.setLeft(tTr.head);

            joiner.setRight(this.head);

        }

        else {

            joiner.setRight(tTr.head);

            joiner.setLeft(this.head);

        }

        head = joiner;

        remove(null);

    }

    @Override

    public void meld(Treap<K, V> t) throws UnsupportedOperationException {

        if(!(t instanceof TreapMap)) return;

        meldRec(((TreapMap<K, V>) t).head);

    }

    private void meldRec(TreapNode<K, V> curr) {

        if(curr == null) return;

        TreapNode<K, V> oldHead = head;

        this.insert(curr.getKey(), curr.getValue(), curr.getPrio());

        head = this.lookupH(curr.getKey());

        meldRec(curr.getLeft());

        meldRec(curr.getRight());

        head = oldHead;

    }

    @Override

    public void difference(Treap<K, V> t) throws UnsupportedOperationException {

        if(!(t instanceof TreapMap)) return;

        diffRec(((TreapMap<K, V>) t).head);

    }

    private void diffRec(TreapNode<K, V> curr) {

        if(curr == null) return;

        TreapNode<K, V> oldHead = head;

        TreapNode<K, V> tr = this.lookupH(curr.getKey());

        if(tr != null) {

            this.remove(curr.getKey());

            this.head = tr;

        }

        meldRec(curr.getLeft());

        meldRec(curr.getRight());

        head = oldHead;

    }

    @Override

    public Iterator<K> iterator() {

        ArrayList<K> arr = new ArrayList<>();

        dfs2(arr, head);

        return arr.iterator();

    }

    private void dfs2(ArrayList<K> trav, TreapNode<K, V> curr) {

        if(curr == null) return;

        dfs2(trav, curr.getLeft());

        trav.add(curr.getKey());

        dfs2(trav, curr.getRight());

    }

    @Override

    public double balanceFactor() throws UnsupportedOperationException {

        return 0;

    }

    private void rotateLL(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getLeft();

        TreapNode<K, V> c2 = c1.getLeft();

        TreapNode<K, V> temp = c2.getRight();

        p.setLeft(c2);

        c2.setRight(c1);

        c1.setLeft(temp);

    }

    private void rotateLR(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getLeft();

        TreapNode<K, V> c2 = c1.getRight();

        TreapNode<K, V> temp = c2.getLeft();

        p.setLeft(c2);

        c2.setLeft(c1);

        c1.setRight(temp);

    }

    private void rotateRL(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getRight();

        TreapNode<K, V> c2 = c1.getLeft();

        TreapNode<K, V> temp = c2.getRight();

        p.setRight(c2);

        c2.setRight(c1);

        c1.setLeft(temp);

    }

    private void rotateRR(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getRight();

        TreapNode<K, V> c2 = c1.getRight();

        p.setRight(c2);

        TreapNode<K, V> temp = c2.getLeft();

        c2.setLeft(c1);

        c1.setRight(temp);

    }

    private void dfs(ArrayList<String> trav, TreapNode<K, V> curr) {

        if(curr == null) return;

        trav.add(String.format("[%d] <%s, %s>%n", curr.getPrio(), curr.getKey().toString(), curr.getValue().toString()));

        dfs(trav, curr.getLeft());

        dfs(trav, curr.getRight());

    }

    public String toString() {

        StringBuilder sb = new StringBuilder();

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

        dfs(trav, head);

        for(String str : trav) sb.append(str);

        return sb.toString();

    }

    // testing- proof by ac

    // https://codeforces.com/contest/1278/problem/C

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        PrintWriter pw = new PrintWriter(System.out);

        int t = sc.nextInt();

        loop:

        while(t-- > 0) {

            int x = sc.nextInt();

            TreapMap<Integer, Integer> hs = new TreapMap<>();

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

                hs.insert(i, 0);

            }

            int[] arr = new int[2*x];

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

                arr[i]=sc.nextInt();

                hs.remove(arr[i]);

            }

            //pw.println(hs);

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

                if(hs.lookup(arr[i-1]+1) != null){

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

                    hs.remove(arr[i]);

                }

                else{

                    for(int j=arr[i-1];j<=2*x;j++){

                        if(hs.lookup(j) != null){

                            arr[i]=j;

                            hs.remove(j);

                            break;

                        }

                        if(j==2*x){

                            pw.println(-1);

                            continue loop;

                        }

                    }

                }

            }

            for(int trr : arr){

                pw.print(trr+" ");

            }

            pw.println();

        }

        pw.close();

    }

}

class TreapNode<K, V> {

    private int prio;

    private K key;

    private V value;

    private TreapNode<K, V> left;

    private TreapNode<K, V> right;

    public int getPrio() {

        return prio;

    }

    public V getValue() {

        return value;

    }

    public K getKey() {

        return key;

    }

    public TreapNode<K, V> getLeft() {

        return left;

    }

    public TreapNode<K, V> getRight() {

        return right;

    }

    public void setLeft(TreapNode<K, V> left) {

        this.left = left;

    }

    public void setValue(V value) {

        this.value = value;

    }

    public void setRight(TreapNode<K, V> right) {

        this.right = right;

    }

    public TreapNode(K key, V value, int prio) {

        this.key = key;

        this.value = value;

        this.prio = prio;

    }

    public String toString() {

        return String.format("{%s, %d}", this.key.toString(), prio);

    }

}

interface Treap<K extends Comparable<K>, V> extends Iterable<K> {

    /**

     * The maximum priority that a node can have.

     */

    public static final int MAX_PRIORITY = 65535;

    /**

     * Retrieves the value associated with a key in this dictionary.

     * If the key is null or the key is not present in this

     * dictionary, this method returns null.

     *

     * @param key   the key whose associated value

     *              should be retrieved

     * @return      the value associated with the key, or

     *              null if the key is null or the key is not in

     *              this treap

     */

    V lookup(K key);

    /**

     * Adds a key-value pair to this dictionary.  Any old value

     * associated with the key is lost.  If the key or the value is

     * null, the pair is not added to the dictionary.

     *

     * @param key      the key to add to this dictionary

     * @param value    the value to associate with the key

     */

    void insert(K key, V value);

    /**

     * Removes a key from this dictionary.  If the key is not present

     * in this dictionary, this method does nothing.  Returns the

     * value associated with the removed key, or null if the key

     * is not present.

     *

     * @param key      the key to remove

     * @return         the associated with the removed key, or null

     */

    V remove(K key);

    /**

     * Splits this treap into two treaps.  The left treap should contain

     * values less than the key, while the right treap should contain

     * values greater than or equal to the key.

     *

     * @param key    the key to split the treap with

     * @return       the left treap in index 0, the right in index 1

     */

    Treap<K, V> [] split(K key);

    /**

     * Joins this treap with another treap.  If the other treap is not

     * an instance of the implementing class, both treaps are unmodified.

     * At the end of the join, this treap will contain the result.

     * This method may destructively modify both treaps.

     *

     * @param t    the treap to join with

     */

    void join(Treap<K, V> t);

    /**

     * Melds this treap with another treap.  If the other treap is not

     * an instance of the implementing class, both treaps are unmodified.

     * At the end of the meld, this treap will contain the result.  This

     * method may destructively modify both treaps.

     *

     * If you don't implement this method, just throw an

     * UnsupportedOperationException.

     *

     * @param t    the treap to meld with.  t may be modified.

     */

    void meld(Treap<K, V> t) throws UnsupportedOperationException;

    /**

     * Removes elements from another treap from this treap.  If the

     * other treap is not an instance of the implementing class,

     * both treaps are unmodified.  At the end of the difference,

     * this treap will contain no keys that were in the other

     * treap.  This method may destructively modify both treaps.

     *

     * If you don't implement this method, just throw an

     * UnsupportedOperationException.

     *

     * @param t   a treap containing elements to remove from this

     *            treap.  t may be destructively modified.

     */

    void difference(Treap<K, V> t) throws UnsupportedOperationException;

    /**

     * Build a human-readable version of the treap.

     * Each node in the treap will be represented as

     *

     *     [priority] <key, value>\n

     *

     * Subtreaps are indented one tab over from their parent for

     * printing.  This method prints out the string representations

     * of key and value using the object's toString(). Treaps should

     * be printed in pre-order traversal fashion.

     */

    String toString();

    /**

     * @return a fresh iterator that points to the first element in

     * this assignment.Treap and iterates in sorted order.

     */

    Iterator<K> iterator();

    /**

     * Returns the balance factor of the treap.  The balance factor

     * is the height of the treap divided by the minimum possible

     * height of a treap of this size.  A perfectly balanced treap

     * has a balance factor of 1.0.  If this treap does not support

     * balance statistics, throw an exception.

     *

     * If you don't implement this method, just throw an

     * UnsupportedOperationException.

     */

    double balanceFactor() throws UnsupportedOperationException;

}


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

import java.util.*;

public class Solution

{

     public static void main(String[] args)

     {

          Scanner sc = new Scanner(System.in);

          int testCases = sc.nextInt();

          while(testCases != 0)

          {

               int n = sc.nextInt() * 2;

               int[] arr = new int[n];

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

               {

                    arr[i] = sc.nextInt();

               }

               Arrays.sort(arr);

               int mid = arr.length / 2;

               System.out.println(Math.abs(arr[mid] - arr[mid - 1]));

               testCases -= 1;

          }

          return;

     }

     private static int getPartition(int[] arr)

     {

          Arrays.sort(arr);

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

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

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

          {

               if(i % 2 == 0)

               {

                    left.add(arr[i]);

               }

               else

               {

                    right.add(arr[i]);

               }

          }

          int mid = left.size() / 2;

          return Math.abs(left.get(mid) - right.get(mid));

     }

}


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        long t = sc.nextInt();

        while (t-- > 0) {

            int n = sc.nextInt();

            int arr[] = new int[n];

            long total = 0;

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

                arr[i] = sc.nextInt();

                total += arr[i];

            }

            long sum = 0;

            long maxi = Long.MIN_VALUE;

            ;

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

                sum += arr[i];

                if (sum > maxi) {

                    maxi = sum;

                }

                if (sum < 0) {

                    sum = 0;

                }

            }

            sum = 0L;

            long maxi2 = Long.MIN_VALUE;

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

                sum += arr[i];

                if (sum > maxi2) {

                    maxi2 = sum;

                }

                if (sum < 0) {

                    sum = 0;

                }

            }

            if (total > Math.max(maxi, maxi2)) {

                System.out.println("YES");

            } else {

                System.out.println("NO");

            }

        }

    }

}


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

import java.util.*;

public class Codeforces {

    public static void solve() {

        FastReader input = new FastReader();

        int testcases=input.nextInt();

        while(testcases-->0){

			String str=input.next();

			int first=0,last=0;

			int count1=0,count0=0;

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

				if(str.charAt(i)=='1'){

					count1++;

				}

				else if(str.charAt(i)=='0'){

					count0++;

				}

			}

			if(count1==0||count0==0){

				System.out.println(0);

				}

				else{

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

				if(str.charAt(i)=='1'){

					first=i;

					break;

				}

			}

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

				if(str.charAt(i)=='1'){

					last=i;

					break;

					}

			}

			int count=0;

			for(int i=first;i<=last;i++){

				if(str.charAt(i)=='0'){

					count++;

				}

			}

			System.out.println(count);

		}

		}

    }

    public static void input_output() {

        try {

            System.setIn(new FileInputStream("input.txt"));

            //System.setOut(new PrintStream("output.txt"));

        } catch (Exception e) {

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

        }

    }

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

        if (System.getProperty("ONLINE_JUDGE") == null) {

            input_output();

            solve();

            }

            else {

                solve();

            }

    }

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

        }

    }

}


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

import java.io.*;

import java.util.*;

import static java.lang.Math.*;

import static java.util.Arrays.*;

public class cf1286b {

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

        int n = ri();

        Node root = null, g[] = new Node[n];

        TreeSet<Integer> set = new TreeSet<>();

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

            g[i] = new Node();

            set.add(i + 1);

        }

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

            int p = rni() - 1, c = ni();

            if(p == -1) {

                root = g[i];

            } else {

                g[p].chd.add(g[i]);

            }

            g[i].c = c + 1;

        }

        boolean yes = root.dfs(set);

        prYN(yes);

        if(yes) {

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

                if(i > 0) {

                    pr(' ');

                }

                pr(g[i].a);

            }

            prln();

        }

        close();

    }

    static class Node {

        List<Node> chd = new ArrayList<>();

        int a, c;

        boolean dfs(TreeSet<Integer> set) {

            Iterator<Integer> iter = set.iterator();

            while(c --> 0) {

                if(!iter.hasNext()) {

                    return false;

                }

                a = iter.next();

            }

            set.remove(a);

            for(Node n : chd) {

                if(!n.dfs(set)) {

                    return false;

                }

            }

            return set.isEmpty() || set.first() > a;

        }

    }

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

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

    static StringTokenizer input;

    static Random rand = new Random();

    // references

    // IBIG = 1e9 + 7

    // IRAND ~= 3e8

    // IMAX ~= 2e10

    // LMAX ~= 9e18

    // constants

    static final int IBIG = 1000000007;

    static final int IRAND = 327859546;

    static final int IMAX = 2147483647;

    static final int IMIN = -2147483648;

    static final long LMAX = 9223372036854775807L;

    static final long LMIN = -9223372036854775808L;

    // util

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static void rsort(char[] a) {shuffle(a); Arrays.sort(a);}

    static <T> void rsort(T[] a) {shuffle(a); Arrays.sort(a);}

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

    // input

    static void r() throws IOException {input = new StringTokenizer(__in.readLine());}

    static int ri() throws IOException {return Integer.parseInt(__in.readLine());}

    static long rl() throws IOException {return Long.parseLong(__in.readLine());}

    static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}

    static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}

    static char[] rcha() throws IOException {return __in.readLine().toCharArray();}

    static String rline() throws IOException {return __in.readLine();}

    static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}

    static int ni() {return Integer.parseInt(input.nextToken());}

    static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}

    static long nl() {return Long.parseLong(input.nextToken());}

    // output

    static void pr(int i) {__out.print(i);}

    static void prln(int i) {__out.println(i);}

    static void pr(long l) {__out.print(l);}

    static void prln(long l) {__out.println(l);}

    static void pr(double d) {__out.print(d);}

    static void prln(double d) {__out.println(d);}

    static void pr(char c) {__out.print(c);}

    static void prln(char c) {__out.println(c);}

    static void pr(char[] s) {__out.print(new String(s));}

    static void prln(char[] s) {__out.println(new String(s));}

    static void pr(String s) {__out.print(s);}

    static void prln(String s) {__out.println(s);}

    static void pr(Object o) {__out.print(o);}

    static void prln(Object o) {__out.println(o);}

    static void prln() {__out.println();}

    static void pryes() {__out.println("yes");}

    static void pry() {__out.println("Yes");}

    static void prY() {__out.println("YES");}

    static void prno() {__out.println("no");}

    static void prn() {__out.println("No");}

    static void prN() {__out.println("NO");}

    static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};

    static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}

    static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}

    static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}

    static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}

    static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());}

    static void h() {__out.println("hlfd");}

    static void flush() {__out.flush();}

    static void close() {__out.close();}

}