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;

		}

	}

}


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

import java.util.Scanner;

public class radio {

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        byte n = input.nextByte();

        int[] robot1 = new int[n];

        int[] robot2 = new int[n];

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

            robot1[i] = input.nextInt();

        }

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

            robot2[i] = input.nextInt();

        }

        input.close();

        int p1=0,p2=0,count=0;

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

            if(robot1[i]==robot2[i]){

                count++;

            }

            else{

                if(robot1[i]==1){

                    p1++;

                }

                if(robot2[i]==1){

                    p2++;

                }

            }

        }

        if((count==n) || (p1==0)){

            System.out.println(-1);

        }

        else{

            System.out.println((p2/p1)+1);

        }

    }

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

import java.util.*;

import java.io.*;

public class _practise {

	public static void main(String args[])

	{

		FastReader in=new FastReader();

		PrintWriter so = new PrintWriter(new BufferedWriter(new  OutputStreamWriter(System.out)));

		int t = in.nextInt();

		//int t = 1;

		while(t-->0)

		{

          int n = in.nextInt();

          int d = in.nextInt();

          int a[] = new int[n];

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

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

          {

              if(a[i]*i<=d)

              {

                  a[0]+=a[i];

                  d-=a[i]*i;

              }

              else

              {

                  a[0]+=d/i;

                  d=0;

                  break;

              }

          }

          so.println(a[0]);

		}

		so.flush();

		/*String s = in.next();

			int a[] = new int[n];

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

			StringBuilder sb = new StringBuilder();

			Set<Long> a = new HashSet<Long>();

			so.println("HELLO");*/

	}

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

		}

		int[] readIntArray(int n)

		{

			int a[]=new int[n];

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

			return a;

		}

		long[] readLongArray(int n)

		{

			long a[]=new long[n];

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

			return a;

		}

		String nextLine()

		{

			String str = "";

			try

			{

				str = br.readLine();

			}

			catch (IOException e)

			{

				e.printStackTrace();

			}

			return str;

		}

	}

}


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

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.io.BufferedWriter;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.util.InputMismatchException;

import java.io.IOException;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author Abhishek Patel

 */

public class Main {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        InputReader in = new InputReader(inputStream);

        OutputWriter out = new OutputWriter(outputStream);

        TaskA solver = new TaskA();

        solver.solve(1, in, out);

        out.close();

    }

    static class TaskA {

        public void solve(int testNumber, InputReader in, OutputWriter out) {

            int n = in.nextInt();

            int arr[] = in.nextIntArray(n);

            int i, ans = 0, cur = 0;

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

                if (arr[i] == 1) {

                    cur++;

                } else {

                    ans = Math.max(ans, cur);

                    cur = 0;

                }

            }

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

                if (arr[i] == 1) {

                    cur++;

                } else {

                    ans = Math.max(ans, cur);

                    cur = 0;

                }

            }

            out.println(ans);

        }

    }

    static class InputReader {

        private InputStream stream;

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

        private int curChar;

        private int numChars;

        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {

            this.stream = stream;

        }

        public int read() {

            if (numChars == -1) {

                throw new InputMismatchException();

            }

            if (curChar >= numChars) {

                curChar = 0;

                try {

                    numChars = stream.read(buf);

                } catch (IOException e) {

                    throw new InputMismatchException();

                }

                if (numChars <= 0) {

                    return -1;

                }

            }

            return buf[curChar++];

        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            int sgn = 1;

            if (c == '-') {

                sgn = -1;

                c = read();

            }

            int res = 0;

            do {

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

                    throw new InputMismatchException();

                }

                res *= 10;

                res += c - '0';

                c = read();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public boolean isSpaceChar(int c) {

            if (filter != null) {

                return filter.isSpaceChar(c);

            }

            return isWhitespace(c);

        }

        public static boolean isWhitespace(int c) {

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

        }

        public int[] nextIntArray(int n) {

            int[] array = new int[n];

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

            return array;

        }

        public interface SpaceCharFilter {

            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {

        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {

            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));

        }

        public OutputWriter(Writer writer) {

            this.writer = new PrintWriter(writer);

        }

        public void close() {

            writer.close();

        }

        public void println(int i) {

            writer.println(i);

        }

    }

}


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.

// I'm done with Java stack overflow.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Stack;

import java.util.StringTokenizer;

public class ScyScrapers {

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

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

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

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

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

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

            a[i]=Integer.parseInt(st.nextToken());

        }

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

        long right[]=new long[n+2];

        Stack<Integer> stack=new Stack<>();

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

            int p=0;

            while(!stack.isEmpty()){

                int top=stack.peek();

                if(a[top]>=a[i]){

                    stack.pop();

                }

                else{

                    p=top;

                    break;

                }

            }

            stack.push(i);

            left[i]=left[p]+1l*(i-p)*a[i];

//            System.out.println(stack.toString());

        }

        stack=new Stack<>();

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

            int p=n+1;

            while(!stack.isEmpty()){

                int top=stack.peek();

                if(a[top]>=a[i]){

                    stack.pop();

                }

                else{

                    p=top;

                    break;

                }

            }

            stack.push(i);

            right[i]=right[p]+1l*(p-i)*a[i];

        }

        int maxIndex=-1;

        long max=0;

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

            if(right[i]+left[i]-a[i]>max){

                max=right[i]+left[i]-a[i];

                maxIndex=i;

            }

//            System.out.println(left[i]+" "+right[i]);

        }

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

        int m=a[maxIndex];

        ans[maxIndex]=a[maxIndex];

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

            if(a[i]>m){

                ans[i]=m;

            }

            else{

                ans[i]=a[i];

                m=ans[i];

            }

        }

        m=a[maxIndex];

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

            if(a[i]>m){

                ans[i]=m;

            }

            else{

                ans[i]=a[i];

                m=ans[i];

            }

        }

        StringBuilder print=new StringBuilder();

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

            print.append(ans[i]+" ");

        }

        System.out.println(print.toString());

    }

}


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

import java.util.Scanner;

public class CF2111{

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int testCases = scan.nextInt();

		while(testCases>0){

			scan.nextInt();

			StringBuffer stringBuffer = new StringBuffer(scan.next());

			System.out.println(getReducedString(stringBuffer));

			testCases--;

		}

	}

	public static String getReducedString(StringBuffer stringBuffer){

		while(stringBuffer.length()>=1 && (stringBuffer.charAt(stringBuffer.length()-1)-'0')%2==0){

			stringBuffer.deleteCharAt(stringBuffer.length()-1);

		}

		//string buffer now contains last character odd.

		int i = stringBuffer.length()-2;

		boolean flag = false;

		while(i >= 0){

			if((stringBuffer.charAt(i)-'0')%2==1){

				stringBuffer.delete(0, i);

				flag = true;

				break;

			}

			i--;

		}

		if(flag	){

			return stringBuffer.toString();

		}

		return "-1";

	}

}


C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between 00 and n−2n−2 inclusive.  All the written labels are distinct.  The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:

import java.awt.image.AreaAveragingScaleFilter;

import java.awt.image.MemoryImageSource;

import java.io.*;

import java.sql.Array;

import java.util.*;

import java.util.StringTokenizer;

public class cf799 {

    static class FastReader{

        BufferedReader br;

        StringTokenizer st;

        public FastReader(){

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

        }

        String next(){

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt(){

            return Integer.parseInt(next());

        }

        long nextLong(){

            return Long.parseLong(next());

        }

        double nextDouble(){

            return Double.parseDouble(next());

        }

        String nextLine(){

            String str="";

            try {

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

            } catch (Exception e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    static class FastWriter {

        private final BufferedWriter bw;

        public FastWriter() {

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

        }

        public void print(Object object) throws IOException {

            bw.append("" + object);

        }

        public void println(Object object) throws IOException {

            print(object);

            bw.append("\n");

        }

        public void close() throws IOException {

            bw.close();

        }

    }

    static int []   parent=new int[100001];

    static int [] rank=new int[100001];

    public static void makeSet(){

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

            parent[i]=i;

            rank[i]=0;

        }

    }

    public static int findParent(int num){

        if(parent[num]==num)return num;

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

    }

    public static void union(int a,int b){

        int ff=findParent(a);

        int ss=findParent(b);

        if(rank[ff]<rank[ss]){

            parent[ff]=ss;

        }

        else if(rank[ss]<rank[ff]){

            parent[ss]=ff;

        }

        else{

            parent[ff]=ss;

            rank[ss]++;

        }

    }

static class ArrayMaxComparator implements Comparator<int[]> {

    public int compare(int[] a, int[] b) {

        return b[0] - a[0];

    }

}

    public static void main(String[] args) {

        try {

            FastReader sc = new FastReader();

            FastWriter out = new FastWriter();

            int n=sc.nextInt();

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

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

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

              int a=sc.nextInt();

              int b=sc.nextInt();

              arr[a]++;

              arr[b]++;

              air.add(new Pair(a,b));

          }

          int count=0;

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

              if(arr[i]==1)count++;

          }

          if(count<=2){

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

                  System.out.println(i);

              }

          }else{

              int diff=0;

              int normal=3;

              int num=0;

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

                  if(arr[air.get(i).a]>=3 ){

                      num=air.get(i).a;

                      break;

                  }

                  if(arr[air.get(i).b]>=3 ){

                      num=air.get(i).b;

                      break;

                  }

              }

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

                  if(diff<3 && (air.get(i).a==num || air.get(i).b==num)){

                      System.out.println(diff++);

                  }else{

                      System.out.println(normal++);

                  }

              }

          }

        }catch (Exception e) {

            return;

        }

    }

    public static long doncr(int n,int r){

        long ans=1;

        while(r>0){

            ans=((ans%1000000007)*n)%1000000007;

r--;

n--;

        }

        return ans;

    }

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

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

    }

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

        if(b==0)return a;

        return gcd(b,a%b);

    }

    static class Pair {

        int a;

        int b;

        // int c;

        Pair(int a, int b ) {

            this.a = a;

            this.b = b;

            //     this.c=c;

        }

    }

    static class Pair2 {

        String a;

        int b;

        // int c;

        Pair2(String a, int b ) {

            this.a = a;

            this.b = b;

            //     this.c=c;

        }

    }

    static   class ArrayKey {

        private int[] array;

        public ArrayKey(int[] array) {

            this.array = array;

        }

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            ArrayKey arrayKey = (ArrayKey) o;

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

        }

        @Override

        public int hashCode() {

            return Arrays.hashCode(array);

        }

    }

}


B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png   When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4];  Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]);  Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4];  Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3

import java.io.*;

import java.util.*;

public class Main implements Runnable {

    static boolean use_n_tests = false;

    static int stack_size = 1 << 27;

    static long mod = 1_000_000_007;

    void solve(FastScanner in, PrintWriter out, int testNumber) {

        int n, m;

        n = in.nextInt();

        m = in.nextInt();

        List<Integer>[] graph = new ArrayList[n];

        List<Integer>[] inverseg = new ArrayList[n];

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

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

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

        }

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

            int v, u;

            v = in.nextInt() - 1;

            u = in.nextInt() - 1;

            graph[v].add(u);

            inverseg[u].add(v);

        }

        int q;

        q = in.nextInt();

        int[] p = new int[q];

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

            p[i] = in.nextInt();

        }

        int[] distance = new int[n];

        Deque<Integer> deq = new ArrayDeque<>();

        deq.addLast(p[q - 1] - 1);

        boolean[] mark = new boolean[n];

        while (!deq.isEmpty()) {

            int v = deq.pollFirst();

            mark[v] = true;

            for (int x : inverseg[v]) {

                if (!mark[x]) {

                    distance[x] = distance[v] + 1;

                    deq.addLast(x);

                    mark[x] = true;

                }

            }

        }

        int ansMin = 0;

        int ansMax = 0;

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

            int v = p[i - 1] - 1;

            int u = p[i] - 1;

            if (distance[u] > distance[v] - 1) {

                ansMin++;

                ansMax++;

            } else {

                for (int j = 0; j < graph[v].size(); j++) {

                    int w = graph[v].get(j);

                    if (w != u && distance[w] == distance[v] - 1) {

                        ansMax++;

                        break;

                    }

                }

            }

        }

        out.println(ansMin + " " + ansMax);

    }

    // ****************************** template code ***********

    static class Range {

        int l, r;

        int id;

        public int getL() {

            return l;

        }

        public int getR() {

            return r;

        }

        public Range(int l, int r, int id) {

            this.l = l;

            this.r = r;

            this.id = id;

        }

    }

    static class Array {

        static Range[] readRanges(int n, FastScanner in) {

            Range[] result = new Range[n];

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

                result[i] = new Range(in.nextInt(), in.nextInt(), i);

            }

            return result;

        }

        static public Integer[] read(int n, FastScanner in) {

            Integer[] out = new Integer[n];

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

                out[i] = in.nextInt();

            }

            return out;

        }

        static public int[] readint(int n, FastScanner in) {

            int[] out = new int[n];

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

                out[i] = in.nextInt();

            }

            return out;

        }

    }

    class Graph {

        List<List<Integer>> create(int n) {

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

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

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

            }

            return graph;

        }

    }

    class FastScanner {

        BufferedReader br;

        StringTokenizer st;

        public FastScanner(InputStream io) {

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

        }

        public String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

    }

    void run_t_tests() {

        int t = in.nextInt();

        int i = 0;

        while (t-- > 0) {

            solve(in, out, i++);

        }

    }

    void run_one() {

        solve(in, out, -1);

    }

    @Override

    public void run() {

        in = new FastScanner(System.in);

        out = new PrintWriter(System.out);

        if (use_n_tests) {

            run_t_tests();

        } else {

            run_one();

        }

        out.close();

    }

    static FastScanner in;

    static PrintWriter out;

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

        Thread thread = new Thread(null, new Main(), "", stack_size);

        thread.start();

        thread.join();

    }

}


B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string:   Pick an integer kk, (1≤k≤n1≤k≤n).  For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length 22)  weqr (after reversing the second substring of length 22)  werq (after reversing the last substring of length 22)  Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds:   aa is a prefix of bb, but a≠ba≠b;  in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows :   for k=1k=1 : abab  for k=2k=2 : baba  for k=3k=3 : abab  for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;

public class Codeforces {
     public static void main(String[] args) {
        FastReader fastReader = new FastReader();
        PrintWriter out = new PrintWriter(System.out);
        int tt = fastReader.nextInt();
        while(tt-- > 0) {
        int n  = fastReader.nextInt();
        char c[] =fastReader.nextLine().toCharArray();
        char ans[] = c;
        int k = 1;
        for(int i = 1; i < n; i++){
            char cur [] = new char[n];
            int index = 0;
            for(int j = i  ;j < n; j++,index++) cur[index] = c[j];
            if((n-(i+1)+1)%2 == 1){
                for(int j = i-1; j>=0 ; j-- , index++) cur[index] = c[j];
            }else{
                for(int j = 0; j <  i ; j++ , index++) cur[index] = c[j];
            }
            if(isSmall(ans,cur)){
                ans = cur;
                k = (i+1);
            }
        }
        out.println(String.valueOf(ans));
        out.println(k);

        }
        out.close();
     }

    private static boolean isSmall(char[] ans, char[] cur) {
        int n = ans.length;
        for(int i = 0; i < n;i++){
            if(cur[i] < ans[i]) return true;
            if(cur[i] > ans[i]) return false;
        }
        return false;
     }

    // constants
    static final int IBIG = 1000000007;
    static final int IMAX = 2147483647;
    static final long LMAX = 9223372036854775807L;
    static Random __r = new Random();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return nonPrimes;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

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

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


B. Double Eliminationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2n2n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 11 to 2n2n and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with 2n−12n−1 teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round 2k2k teams play a game with each other (teams are split into games by team numbers). 2k−12k−1 loosing teams are eliminated from the championship, 2k−12k−1 winning teams are playing 2k−12k−1 teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have 2k−12k−1 teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers a1,a2,...,aka1,a2,...,ak. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?InputFirst input line has two integers n,kn,k — 2n2n teams are competing in the championship. You are a fan of kk teams (2≤n≤17;0≤k≤2n2≤n≤17;0≤k≤2n).Second input line has kk distinct integers a1,…,aka1,…,ak — numbers of teams you're a fan of (1≤ai≤2n1≤ai≤2n).OutputOutput single integer — maximal possible number of championship games that include teams you're fan of.ExamplesInputCopy3 1
6
OutputCopy6
InputCopy3 3
1 7 8
OutputCopy11
InputCopy3 4
1 3 5 7
OutputCopy14
NoteOn the image; each game of the championship is denoted with an English letter (aa to nn). Winner of game ii is denoted as WiWi, loser is denoted as LiLi. Teams you're a fan of are highlighted with red background.In the first example, team 66 will play in 6 games if it looses the first upper bracket game (game cc) and wins all lower bracket games (games h,j,l,mh,j,l,m). In the second example, teams 77 and 88 have to play with each other in the first game of upper bracket (game dd). Team 88 can win all remaining games in upper bracket, when teams 11 and 77 will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship.

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.Arrays;

import java.io.BufferedWriter;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.util.InputMismatchException;

import java.io.IOException;

import java.io.InputStream;

/**

 * Built using CHelper plug-in Actual solution is at the top

 *

 * @author ilyakor

 */

public class Main {

  public static void main(String[] args) {

    InputStream inputStream = System.in;

    OutputStream outputStream = System.out;

    InputReader in = new InputReader(inputStream);

    OutputWriter out = new OutputWriter(outputStream);

    TaskB solver = new TaskB();

    solver.solve(1, in, out);

    out.close();

  }

  static class TaskB {

    static final int inf = 1000 * 1000 * 1000;

    int[] A;

    int[][] d;

    public void solve(int testNumber, InputReader in, OutputWriter out) {

      int n = in.nextInt();

      int k = in.nextInt();

      A = new int[(1 << (n + 1))];

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

        A[(1 << n) + in.nextInt() - 1] = 1;

      }

      if (k == 0) {

        out.printLine(0);

        return;

      }

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

        A[i / 2] += A[i];

      }

      d = new int[4][A.length];

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

        Arrays.fill(d[i], -inf - 1);

      }

      int res = Math.max(calc(1, 1), Math.max(calc(1, 2), calc(1, 3)));

      if (res < 0) {

        res = 0;

      }

      ++res;

      out.printLine(res);

    }

    int calc(int v, int s) {

      if (s == 0) {

        return 0;

      }

      if (A[v] == 0) {

        return -inf;

      }

      if (s == 3 && A[v] < 2) {

        return -inf;

      }

      if (v * 4 >= A.length) {

        return 1;

      }

      if (d[s][v] != -inf - 1) {

        return d[s][v];

      }

      int res = -inf;

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

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

          int val1 = calc(v * 2, s1);

          int val2 = calc(v * 2 + 1, s2);

          for (int mask = 0; mask < 8; ++mask) {

            int cur = val1 + val2;

            int w1 = mask % 2 == 0 ? s1 % 2 : s2 % 2;

            int l1 = mask % 2 == 0 ? s2 % 2 : s1 % 2;

            if (w1 + l1 > 0) {

              ++cur;

            }

            int w2 = (mask >> 1) % 2 == 0 ? (s1 >> 1) % 2 : (s2 >> 1) % 2;

            int l2 = (mask >> 1) % 2 == 0 ? (s2 >> 1) % 2 : (s1 >> 1) % 2;

            if (w2 + l2 > 0) {

              ++cur;

            }

            int w3 = (mask >> 2) % 2 == 0 ? l1 : w2;

            if (l1 + w2 > 0) {

              ++cur;

            }

            if (w3 * 2 + w1 != s) {

              continue;

            }

            if (cur > res) {

              res = cur;

            }

          }

        }

      }

      //System.err.println(s + " " + v + ": " + res);

      d[s][v] = res;

      return res;

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

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

        if (i != 0) {

          writer.print(' ');

        }

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

  }

  static class InputReader {

    private InputStream stream;

    private byte[] buffer = new byte[10000];

    private int cur;

    private int count;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public static boolean isSpace(int c) {

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

    }

    public int read() {

      if (count == -1) {

        throw new InputMismatchException();

      }

      try {

        if (cur >= count) {

          cur = 0;

          count = stream.read(buffer);

          if (count <= 0) {

            return -1;

          }

        }

      } catch (IOException e) {

        throw new InputMismatchException();

      }

      return buffer[cur++];

    }

    public int readSkipSpace() {

      int c;

      do {

        c = read();

      } while (isSpace(c));

      return c;

    }

    public int nextInt() {

      int sgn = 1;

      int c = readSkipSpace();

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

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

          throw new InputMismatchException();

        }

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

        c = read();

      } while (!isSpace(c));

      res *= sgn;

      return res;

    }

  }

}


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

import java.util.Scanner;

public class H {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        int a = s.nextInt();

        int b = s.nextInt();

        long tab[] = new long[250006];

        long v =1;

        tab[0]=v;

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

            v=(v*(i))%b;

            tab[i]=v;

        }

        long rs=0;

        long  m;

        long n;

        long tot;

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

            n=(long) Math.pow(a-i,2)%b;

            tot = (tab[a-i-1]*tab[i+1])%b;

            m = (long) (n*tot)%b;

            rs= (rs+ m)%b;

        }

        System.out.println(rs);

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.math.BigInteger;

import java.util.*;

import java.util.List;

public class erasingzeroes {

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

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        int t=sc.nextInt();

        while(t-->0){

            String s=sc.next();

            boolean z=false;

            int first=s.length();

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

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

                    first=i;

                    break;

                }

            }

            int last=-1;

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

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

                    last=i;

                    break;

                }

            }

            int total=0;

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

                if(s.charAt(i)=='0')total++;

            }

            System.out.println(total);

        }

    }

}


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

import java.util.Scanner;
public class template {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int t = sc.nextInt();
        for (int i = 0; i < t; i++) {
            solve();
        }
    }
    public static void solve() {
        int n = sc.nextInt();
        int[] input = new int[n];
        for (int i = 0; i < n; i++) {
            input[i] = sc.nextInt();
        }
        int even = input[0] % 2;
        for (int i = 0; i < n; i++) {
            if (input[i] % 2 != even) {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
        return;
    }
}


B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class AnotA {

	long x1,x2;

	long y1,y2;

	AnotA(String s){

		StringTokenizer st = new StringTokenizer(s);

		this.x1 =Integer.parseInt(st.nextToken());

		this.y1 =Integer.parseInt(st.nextToken());

		this.x2 =Integer.parseInt(st.nextToken());

		this.y2 =Integer.parseInt(st.nextToken());

	}

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

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

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

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

			AnotA a = new AnotA(br.readLine());

			AnotA b = new AnotA(br.readLine());

			AnotA c = new AnotA(br.readLine());

			System.out.println(CC(a,b,c)||CC(b,c,a)||CC(c,a,b)?"YES":"NO");

		}

	}

	public static boolean CC(AnotA a, AnotA b, AnotA c) {

		return checkConstraints(a,b,c)&&(

				checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)||

				checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b));

	}

	//Took Dukkha code as reference

	private static boolean checkIntersection(long x, long y, AnotA a) {

		//check if the point is lying outside the segment

		if(x<Math.min(a.x1, a.x2)||x>Math.max(a.x1, a.x2)||y<Math.min(a.y1, a.y2)||y>Math.max(a.y1, a.y2))

			return false;

		//check ratio between parts

		int xpart = (int) Math.abs(a.x1-a.x2);

		int ypart = (int) Math.abs(a.y1-a.y2);

		int xmin = (int) Math.min(Math.abs(a.x1-x), Math.abs(a.x2-x));

		int ymin = (int) Math.min(Math.abs(a.y1-y), Math.abs(a.y2-y));

		return xpart<=5*xmin&&ypart<=5*ymin&& (long) (x-a.x2)*(a.y1-a.y2)==(long)(y-a.y2)*(a.x1-a.x2);

	}

	public static boolean checkConstraints(AnotA a, AnotA b, AnotA c) {

		if(a.x1==b.x1&&a.y1==b.y1) {

			return getAngle(a.x2,a.y2,b.x2,b.y2,a.x1,a.y1);

		}

		else if(a.x2==b.x1&&a.y2==b.y1) {

			return getAngle(a.x1, a.y1, b.x2, b.y2, a.x2, a.y2);

		}

		else if(a.x1==b.x2&&a.y1==b.y2) {

			return getAngle(a.x2, a.y2, b.x1, b.y1, a.x1, a.y1);

		}

		else if(a.x2==b.x2&&a.y2==b.y2) {

			return getAngle(a.x1, a.y1, b.x1, b.y1, a.x2, a.y2);

		}

		return false;

	}

	public static boolean getAngle(long x1, long y1, long x2, long y2, long x3, long y3) {

		boolean collinear =areCollinear( x1,  y1,  x2,  y2,  x3,  y3);

		//check angle <= 90

		long a13 = (long) (x1-x3) * (x1-x3) + (long) (y1-y3) *(y1-y3);

		long a23 = (long) (x2-x3) * (x2-x3) + (long) (y2-y3) *(y2-y3);

		long a12 = (long) (x1-x2) * (x1-x2) + (long) (y1-y2) *(y1-y2);

		return !collinear&&a13+a23>=a12;

	}

	private static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) {

		long area = (long) (x1-x3)*(y2-y3) - (long) (x2-x3)*(y1-y3);

		return area==0?true:false;

	}

}


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

import java.io.InputStream;

import java.io.PrintWriter;

import java.math.BigDecimal;

import java.math.RoundingMode;

import java.util.*;

import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

import java.beans.Visibility;

import java.io.File;

import java.io.FileDescriptor;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.io.UncheckedIOException;

import java.lang.Thread.State;

import java.lang.reflect.Field;

import java.nio.CharBuffer;

import java.nio.charset.CharacterCodingException;

import java.nio.charset.CharsetEncoder;

import java.nio.charset.StandardCharsets;

public class Main {

	static final long MOD1=1000000007;

	static final long MOD=998244353;

	static long ans=0;

	public static void main(String[] args){

		PrintWriter out = new PrintWriter(System.out);

		InputReader sc=new InputReader(System.in);

		int n  = sc.nextInt();

		int m = sc.nextInt();

		int[] a = sc.nextIntArray(m);

		int[] min = new int[n];

		int[] max = new int[n];

		Arrays.setAll(min, k->k+1);

		Arrays.setAll(max, k->k+1);

		int[] last = new int[n];

		Arrays.fill(last, -1);

		SegTree<Integer> seg1 = new SegTree<Integer>(n, (x,y)->x+y, 0);

		SegTree<Integer> seg2 = new SegTree<Integer>(m, (x,y)->x+y, 0);

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

			int id = a[i]-1;

			min[id] = 1;

			if (last[id]==-1) {

				max[id] += seg1.prod(a[i], n);

				seg1.set(id, 1);

				seg2.set(i, 1);

			}else {

				seg2.set(last[id], 0);

				seg2.set(i, 1);

				max[id] = Math.max(max[id], seg2.prod(last[id], i)+1);

			}

			last[id] = i;

		}

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

			if (last[i]==-1) {

				max[i] += seg1.prod(i, n);

			}else {

				max[i] = Math.max(max[i], seg2.prod(last[i], m));

			}

		}

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

			out.println(min[i]+" "+max[i]);

		}

		out.flush();

	}

	static class SegTree<S> {

	    final int MAX;

	    final int N;

	    final java.util.function.BinaryOperator<S> op;

	    final S E;

	    final S[] data;

	    @SuppressWarnings("unchecked")

	    public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) {

	        this.MAX = n;

	        int k = 1;

	        while (k < n) k <<= 1;

	        this.N = k;

	        this.E = e;

	        this.op = op;

	        this.data = (S[]) new Object[N << 1];

	        java.util.Arrays.fill(data, E);

	    }

	    public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) {

	        this(dat.length, op, e);

	        build(dat);

	    }

	    private void build(S[] dat) {

	        int l = dat.length;

	        System.arraycopy(dat, 0, data, N, l);

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

	            data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]);

	        }

	    }

	    public void set(int p, S x) {

	        exclusiveRangeCheck(p);

	        data[p += N] = x;

	        p >>= 1;

	        while (p > 0) {

	            data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]);

	            p >>= 1;

	        }

	    }

	    public S get(int p) {

	        exclusiveRangeCheck(p);

	        return data[p + N];

	    }

	    public S prod(int l, int r) {

	        if (l > r) {

	            throw new IllegalArgumentException(

	                String.format("Invalid range: [%d, %d)", l, r)

	            );

	        }

	        inclusiveRangeCheck(l);

	        inclusiveRangeCheck(r);

	        S sumLeft = E;

	        S sumRight = E;

	        l += N; r += N;

	        while (l < r) {

	            if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]);

	            if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight);

	            l >>= 1; r >>= 1;

	        }

	        return op.apply(sumLeft, sumRight);

	    }

	    public S allProd() {

	        return data[1];

	    }

	    public int maxRight(int l, java.util.function.Predicate<S> f) {

	        inclusiveRangeCheck(l);

	        if (!f.test(E)) {

	            throw new IllegalArgumentException("Identity element must satisfy the condition.");

	        }

	        if (l == MAX) return MAX;

	        l += N;

	        S sum = E;

	        do {

	            l >>= Integer.numberOfTrailingZeros(l);

	            if (!f.test(op.apply(sum, data[l]))) {

	                while (l < N) {

	                    l = l << 1;

	                    if (f.test(op.apply(sum, data[l]))) {

	                        sum = op.apply(sum, data[l]);

	                        l++;

	                    }

	                }

	                return l - N;

	            }

	            sum = op.apply(sum, data[l]);

	            l++;

	        } while ((l & -l) != l);

	        return MAX;

	    }

	    public int minLeft(int r, java.util.function.Predicate<S> f) {

	        inclusiveRangeCheck(r);

	        if (!f.test(E)) {

	            throw new IllegalArgumentException("Identity element must satisfy the condition.");

	        }

	        if (r == 0) return 0;

	        r += N;

	        S sum = E;

	        do {

	            r--;

	            while (r > 1 && (r & 1) == 1) r >>= 1;

	            if (!f.test(op.apply(data[r], sum))) {

	                while (r < N) {

	                    r = r << 1 | 1;

	                    if (f.test(op.apply(data[r], sum))) {

	                        sum = op.apply(data[r], sum);

	                        r--;

	                    }

	                }

	                return r + 1 - N;

	            }

	            sum = op.apply(data[r], sum);

	        } while ((r & -r) != r);

	        return 0;

	    }

	    private void exclusiveRangeCheck(int p) {

	        if (p < 0 || p >= MAX) {

	            throw new IndexOutOfBoundsException(

	                String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX)

	            );

	        }

	    }

	    private void inclusiveRangeCheck(int p) {

	        if (p < 0 || p > MAX) {

	            throw new IndexOutOfBoundsException(

	                String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX)

	            );

	        }

	    }

	}

	static class InputReader {

		private InputStream in;

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

		private int curbuf;

		private int lenbuf;

		public InputReader(InputStream in) {

			this.in = in;

			this.curbuf = this.lenbuf = 0;

		}

		public boolean hasNextByte() {

			if (curbuf >= lenbuf) {

				curbuf = 0;

				try {

					lenbuf = in.read(buffer);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (lenbuf <= 0)

					return false;

			}

			return true;

		}

		private int readByte() {

			if (hasNextByte())

				return buffer[curbuf++];

			else

				return -1;

		}

		private boolean isSpaceChar(int c) {

			return !(c >= 33 && c <= 126);

		}

		private void skip() {

			while (hasNextByte() && isSpaceChar(buffer[curbuf]))

				curbuf++;

		}

		public boolean hasNext() {

			skip();

			return hasNextByte();

		}

		public String next() {

			if (!hasNext())

				throw new NoSuchElementException();

			StringBuilder sb = new StringBuilder();

			int b = readByte();

			while (!isSpaceChar(b)) {

				sb.appendCodePoint(b);

				b = readByte();

			}

			return sb.toString();

		}

		public int nextInt() {

			if (!hasNext())

				throw new NoSuchElementException();

			int c = readByte();

			while (isSpaceChar(c))

				c = readByte();

			boolean minus = false;

			if (c == '-') {

				minus = true;

				c = readByte();

			}

			int res = 0;

			do {

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

					throw new InputMismatchException();

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

				c = readByte();

			} while (!isSpaceChar(c));

			return (minus) ? -res : res;

		}

		public long nextLong() {

			if (!hasNext())

				throw new NoSuchElementException();

			int c = readByte();

			while (isSpaceChar(c))

				c = readByte();

			boolean minus = false;

			if (c == '-') {

				minus = true;

				c = readByte();

			}

			long res = 0;

			do {

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

					throw new InputMismatchException();

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

				c = readByte();

			} while (!isSpaceChar(c));

			return (minus) ? -res : res;

		}

		public double nextDouble() {

			return Double.parseDouble(next());

		}

		public int[] nextIntArray(int n) {

			int[] a = new int[n];

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

				a[i] = nextInt();

			return a;

		}

		public double[] nextDoubleArray(int n) {

			double[] a = new double[n];

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

				a[i] = nextDouble();

			return a;

		}

		public long[] nextLongArray(int n) {

			long[] a = new long[n];

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

				a[i] = nextLong();

			return a;

		}

		public char[][] nextCharMap(int n, int m) {

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

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

				map[i] = next().toCharArray();

			return map;

		}

	}

}