D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

//package com.example.practice.codeforces.sc2500;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
//D. Happy New Year
public class Solution1 {
    public static void main (String [] args) throws IOException {
        // Use BufferedReader rather than RandomAccessFile; it's much faster
        final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        // input file name goes above
        //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out")));

        StringTokenizer st = new StringTokenizer(input.readLine());
        int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        int[][] ns = new int[n][2];
        for(int i=0;i<n;++i){
            st = new StringTokenizer(input.readLine());
            ns[i][0] = Integer.parseInt(st.nextToken());
            ns[i][1] = Integer.parseInt(st.nextToken());
        }
        System.out.println(calc(n, m, k, ns));
        //out.close();       // close the output file
    }

    private static int calc(final int n, final int m, final int k, int[][] ns) {
        HashMap<Integer, Node> map = new HashMap<>();
        int p = 0, pre = 0, finished = 0;
        for (int[] kk : ns){
            if (!map.containsKey(kk[0])){
                map.put(kk[0], new Node(kk[0]));
            }
            map.get(kk[0]).st.add(p);
            if (!map.containsKey(kk[1]+1)){
                map.put(kk[1]+1, new Node(kk[1]+1));
            }
            map.get(kk[1]+1).en.add(p++);
        }
        Node[] nds = new Node[map.size()];
        p = 0;
        for (Node nd : map.values()){
            nds[p++] = nd;
        }
        Arrays.sort(nds);
        final int ks = 1<<k;
        int[][] dp = new int[nds.length][ks];
        int[] mask = new int[n], bitCount = new int[ks];
        for (int i=1;i<ks;++i){
            if((i&1) == 1)bitCount[i]=bitCount[i-1]+1;
            else bitCount[i]=bitCount[i>>1];
        }
        for (int i=0;i<dp.length-1;++i){
            pre -= finished;
            int d = 1, added = 0;
            for (int a : nds[i].st){
                while((d&pre) != 0) {
                    d = d << 1;
                }
                mask[a] = d;
                added += d;
                pre += d;
            }
            finished = 0;
            for (int a : nds[i+1].en){
                finished += mask[a];
            }
            for (int j=0;j<ks;++j) {
                if ((j & pre) == j) {
                    int t = 0;
                    if ((bitCount[j] & 1) == 1) {
                        t += nds[i + 1].start - nds[i].start;
                    }
                    if (i > 0) {
                        t += dp[i - 1][j - (j & added)];
                    }
                    dp[i][j - (j & finished)] = Math.max(dp[i][j - (j & finished)], t);
                }
            }
        }
        return dp[dp.length-2][0];
    }

    static class Node implements Comparable<Node>{
        int start;
        ArrayList<Integer> st;
        ArrayList<Integer> en;
        public Node(int a){
            start = a;
            st = new ArrayList<>(4);
            en = new ArrayList<>(4);
        }
        @Override
        public int compareTo(Node nd){
            return this.start - nd.start;
        }
    }
}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashMap;

import java.util.InputMismatchException;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.util.stream.Collectors;

public class cf {

	static class FastReader {

		BufferedReader br;

		StringTokenizer st;

		public FastReader() {

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

		}

		String next() {

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

				try {

					String str = br.readLine();

					if(str == null)

						throw new InputMismatchException();

					st = new StringTokenizer(str);

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

			}

			if(str == null)

				throw new InputMismatchException();

			return str;

		}

	}

    static boolean pal(String s)

    {

    	StringBuilder sb=new StringBuilder();

    	sb.append(s);

    	sb.reverse();

    	String s1=sb.toString();

    	if(s1.contentEquals(s))

    	{

    		return true;

    	}

    	else

    	{

    		return false;

    	}

    }

    static boolean isPrime(long arr)

{

    // Corner cases

    if (arr <= 1)

        return false;

    if (arr <= 3)

        return true;

    // This is checked so that we can skip

    // middle five numbers in below loop

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

        return false;

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

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

            return false;

    return true;

}

    public static int reverseBits(int n)

    {

        int rev = 0;

        // traversing bits of 'n'

        // from the right

        while (n > 0)

        {

            // bitwise left shift

            // 'rev' by 1

            rev <<= 1;

            // if current bit is '1'

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

                rev ^= 1;

            // bitwise right shift

            //'n' by 1

            n >>= 1;

        }

        // required number

        return rev;

    }

    static int fact(int n)

    {

    	int fact=1;

    	while(n>=1)

    	{

    		fact=fact*n;

    		n--;

    	}

    	return fact;

    }

    static long __gcd(long a, long b)

    {

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

            return 0;

        if (a == b)

            return a;

        if (a > b)

            return __gcd(a-b, b);

        return __gcd(a, b-a);

    }

    static boolean coprime(long a, long b) {

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

            return true;

        else

            return false;

    }

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

    {

		if(n>0)

		{

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

			return a^b;

		}

		else

		{

			return a^b;

		}

    }

	public static void main(String[] args)

	{

		FastReader sc = new FastReader();

	    PrintWriter out = new PrintWriter(System.out);

        int t=sc.nextInt();

        while(t-->0)

        {

        	long n=sc.nextLong();

			long s=sc.nextLong();

			long k=sc.nextLong();

			long arr[]=new long[(int) k];

			HashMap<Long,Boolean> x=new HashMap<Long,Boolean>();

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

			{

				x.put(sc.nextLong(),false);

			}

			long s1=s,s2=s;

			while(true)

			{

				if(!x.containsKey(s) && s<=n)

				{

					out.println(Math.abs(s2-s));

					break;

				}

				if(!x.containsKey(s1) && s1>=1)

				{

					out.println(Math.abs(s1-s2));

					break;

				}

				s++;

				s1--;

			}

        }

	    out.close();

	}

}


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

import java.io.* ;

public class Main

{

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

    {

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

        PrintWriter out =  new PrintWriter ( System.out );

        int t = Integer.parseInt( br.readLine() ) ;

        int[] arr = new int [ t ] ;

        for( int i   = 0 ; i != t  ; ++i )

            arr[ i ] =Integer.parseInt( br.readLine() ) ;

        for( int item : arr )

            out.println( "1 " + ( item-1 ) );

        out.flush();

        return  ;

    }

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

import java.util.*;

public class Main

{

	public static void main(String[] args) {

		//System.out.println("Hello World");

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

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

		{

		    int a=sc.nextInt();

		    int b=sc.nextInt();

		    if(a==b)

		    {

		        System.out.println("0");

		    }

		    else if(a>b)

		    {

		        if((a-b)%2==0)

		        System.out.println("1");

		        else

		        System.out.println("2");

		    }

		    else

		    {

		        if((b-a)%2!=0)

		        System.out.println("1");

		        else

		        System.out.println("2");

		    }

		}

	}

}


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

import java.io.*;

import java.util.*;

public class Main {

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

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

    public static void main(String[] args) {

        int n = in.nextInt();

        Integer[] d = new Integer[n];

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

            d[i] = in.nextInt();

        }

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

            d[i] -= in.nextInt();

        }

        Arrays.sort(d);

        long ans = 0;

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

            int l = i + 1, r = n - 1, x = n;

            while (l <= r) {

                int mid = l + (r - l) / 2;

                if (d[mid] > -d[i]) {

                    r = mid - 1;

                    x = mid;

                }

                else l = mid + 1;

            }

            ans += n - x;

        }

        pw.println(ans);

        pw.close();

    }

    private static class Pair {

        private int first, second;

        public Pair(int first, int second) {

            this.first = first;

            this.second = second;

        }

    }

    private static class InputReader {

        public BufferedReader reader;

        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {

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

            tokenizer = null;

        }

        public boolean ready() throws IOException {

            return reader.ready();

        }

        public String next() {

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

                try {

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

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public String nextLine() {

            String str = null;

            try {

                str = reader.readLine();

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

            return str;

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

        public Double nextDouble() {

            return Double.parseDouble(next());

        }

    }

}


C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

import java.io.*;

import java.util.*;

import java.math.*;

public class Main{

	private static Scanner cin = new Scanner(new BufferedInputStream(System.in));

	private static PrintWriter cout = new PrintWriter(System.out,true);

	private static InputStream inputstream = System.in;

	private static FastScanner in = new FastScanner(inputstream);

	public static void main(String[] args){

		Task solver = new Task();

		int TaskCase = in.nextInt();

		solver.solve(TaskCase);

		cout.flush();

	}

	private static class Task{

		long value[];

		int n,m;

		TreeMap<Integer,Long> mp = new TreeMap<>();

		public void solve(int T){

			while(T-->0){

				n = in.nextInt();

				m = in.nextInt();

				value = new long[n];

				for(int i = 0; i < n; i++) value[i] = in.nextLong();

				if(n==1){

					in.nextInt();

					in.nextInt();

					cout.print(value[0]);

					cout.write('\n');

					continue;

				}

				ArrayList<Integer>[] G = Utils.ListArray(n);

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

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

					G[v].add(u);

				}

				mp.clear();

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

					if(G[i].isEmpty()) continue;

					G[i].sort((x,y)->{ return x-y; });

					int hx = G[i].hashCode();

					if(!mp.containsKey(hx)) mp.put(hx,value[i]);

					else mp.put(hx,mp.get(hx)+value[i]);

				}

				Long ans = 0l;

				for(long v : mp.values()) ans = gcd(ans,v);

				cout.write(ans.toString()+'\n');

			}

		}

		private long gcd(long A, long B){

			return B!=0 ? gcd(B,A%B) : A;

		}

	}

	private static class Utils{

		public static <T> ArrayList<T>[] ListArray(int _size){

			ArrayList<T>[] ret = new ArrayList[_size];

			for(int i = 0; i < _size; i++) ret[i] = new ArrayList<>();

			return ret;

		}

	}

	public static class FastScanner {

		BufferedReader br;

		StringTokenizer st;

		public FastScanner(InputStream in) {

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

		}

		public int nextInt() {

			return Integer.parseInt(next());

		}

		public boolean hasMoreTokens() {

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

				String line = null;

				try {

					line = br.readLine();

				} catch (IOException e) {

					return false;

				}

				if (line == null) {

					return false;

				}

				st = new StringTokenizer(line);

			}

			return true;

		}

		public String next() {

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

				String line = null;

				try {

					line = br.readLine();

				} catch (IOException e) {

				}

				st = new StringTokenizer(line);

			}

			return st.nextToken();

		}

		public long nextLong() {

			return Long.parseLong(next());

		}

		public double nextDouble() {

			return Double.parseDouble(next());

		}

		public int[] nextIntArray(int n) {

			int[] ret = new int[n];

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

				ret[i] = nextInt();

			}

			return ret;

		}

		public long[] nextLongArray(int n) {

			long[] ret = new long[n];

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

				ret[i] = nextLong();

			}

			return ret;

		}

	}

}


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

            }

        }

    }

}