A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets:  the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different),  the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — 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≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.

// Created on: 10:12:32 PM | 14-Mar-2022

import java.util.*;

import java.io.*;

import java.math.*;

import java.lang.*;

public class Main {

	static InputStream is;

	static PrintWriter out;

	static String INPUT = "";

	static void solve() {

		int caseNo = 1;

		for (int T = sc.nextInt(); T > 0; T--, caseNo++) {

			solveIt(caseNo);

		}

	}

	// Solution

	static void solveIt(int t) {

		int n = sc.nextInt();

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

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

		sort(a);

		sort(b);

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

			System.out.print(a[i] + " ");

		}

		System.out.println();

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

			System.out.print(b[i] + " ");

		}

		System.out.println();

	}

	static void revArray(int a[], int i, int j) {

		while (i <= j) {

			int temp = a[i];

			a[i] = a[j];

			a[j] = temp;

			i++;

			j--;

		}

	}

	static boolean isSorted(int a[], int s, int e, boolean strict) {

		for (int i = s + 1; i <= e; i++) {

			if (strict && a[i - 1] >= a[i])

				return false;

			if (!strict && a[i - 1] > a[i])

				return false;

		}

		return true;

	}

	static class DSU {

		int rank[];

		int parent[];

		DSU(int n) {

			rank = new int[n + 1];

			parent = new int[n + 1];

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

				parent[i] = i;

			}

		}

		int findParent(int node) {

			if (parent[node] == node)

				return node;

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

		}

		boolean union(int x, int y) {

			int px = findParent(x);

			int py = findParent(y);

			if (px == py)

				return false;

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

				parent[px] = py;

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

				parent[py] = px;

			} else {

				parent[px] = py;

				rank[py]++;

			}

			return true;

		}

	}

	static void sort(int[] a) {

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

		for (int i : a)

			l.add(i);

		Collections.sort(l);

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

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

	}

	static boolean[] seiveOfEratosthenes(int n) {

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

		Arrays.fill(isPrime, true);

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

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

				isPrime[j] = false;

			}

		}

		return isPrime;

	}

	public static int[] seiveOnlyPrimes(int n) {

		if (n <= 32) {

			int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };

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

				if (n < primes[i]) {

					return Arrays.copyOf(primes, i);

				}

			}

			return primes;

		}

		int u = n + 32;

		double lu = Math.log(u);

		int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];

		ret[0] = 2;

		int pos = 1;

		int[] isp = new int[(n + 1) / 32 / 2 + 1];

		int sup = (n + 1) / 32 / 2 + 1;

		int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };

		for (int tp : tprimes) {

			ret[pos++] = tp;

			int[] ptn = new int[tp];

			for (int i = (tp - 3) / 2; i < tp << 5; i += tp)

				ptn[i >> 5] |= 1 << (i & 31);

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

				for (int j = i; j < sup; j += tp)

					isp[j] |= ptn[i];

			}

		}

		int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17,

				9, 6, 16, 5, 15, 14 };

		int h = n / 2;

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

			for (int j = ~isp[i]; j != 0; j &= j - 1) {

				int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];

				int p = 2 * pp + 3;

				if (p > n)

					break;

				ret[pos++] = p;

				for (int q = pp; q <= h; q += p)

					isp[q >> 5] |= 1 << (q & 31);

			}

		}

		return Arrays.copyOf(ret, pos);

	}

	static int gcd(int a, int b) {

		if (b == 0)

			return a;

		return gcd(b, a % b);

	}

	static boolean isPrime(long n) {

		if (n < 2)

			return false;

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

			if (n % i == 0)

				return false;

		}

		return true;

	}

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

		long S = System.currentTimeMillis();

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

		out = new PrintWriter(System.out);

		solve();

		out.flush();

		long G = System.currentTimeMillis();

		sc.tr(G - S + "ms");

	}

	static class sc {

		private static boolean endOfFile() {

			if (bufferLength == -1)

				return true;

			int lptr = ptrbuf;

			while (lptr < bufferLength)

				if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++]))

					return false;

			try {

				is.mark(1000);

				while (true) {

					int b = is.read();

					if (b == -1) {

						is.reset();

						return true;

					} else if (!isThisTheSpaceCharacter(b)) {

						is.reset();

						return false;

					}

				}

			} catch (IOException e) {

				return true;

			}

		}

		private static byte[] inputBufffferBigBoi = new byte[1024];

		static int bufferLength = 0, ptrbuf = 0;

		private static int justReadTheByte() {

			if (bufferLength == -1)

				throw new InputMismatchException();

			if (ptrbuf >= bufferLength) {

				ptrbuf = 0;

				try {

					bufferLength = is.read(inputBufffferBigBoi);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (bufferLength <= 0)

					return -1;

			}

			return inputBufffferBigBoi[ptrbuf++];

		}

		private static boolean isThisTheSpaceCharacter(int c) {

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

		}

		private static int skipItBishhhhhhh() {

			int b;

			while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b))

				;

			return b;

		}

		private static double nextDouble() {

			return Double.parseDouble(next());

		}

		private static char nextChar() {

			return (char) skipItBishhhhhhh();

		}

		private static String next() {

			int b = skipItBishhhhhhh();

			StringBuilder sb = new StringBuilder();

			while (!(isThisTheSpaceCharacter(b))) {

				sb.appendCodePoint(b);

				b = justReadTheByte();

			}

			return sb.toString();

		}

		private static char[] readCharArray(int n) {

			char[] buf = new char[n];

			int b = skipItBishhhhhhh(), p = 0;

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

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

				b = justReadTheByte();

			}

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

		}

		private static char[][] readCharMatrix(int n, int m) {

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

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

				map[i] = readCharArray(m);

			return map;

		}

		private static int[] readIntArray(int n) {

			int[] a = new int[n];

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

				a[i] = nextInt();

			return a;

		}

		private static long[] readLongArray(int n) {

			long[] a = new long[n];

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

				a[i] = nextLong();

			return a;

		}

		private static int nextInt() {

			int num = 0, b;

			boolean minus = false;

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

				;

			if (b == '-') {

				minus = true;

				b = justReadTheByte();

			}

			while (true) {

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

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

				} else {

					return minus ? -num : num;

				}

				b = justReadTheByte();

			}

		}

		private static long nextLong() {

			long num = 0;

			int b;

			boolean minus = false;

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

				;

			if (b == '-') {

				minus = true;

				b = justReadTheByte();

			}

			while (true) {

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

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

				} else {

					return minus ? -num : num;

				}

				b = justReadTheByte();

			}

		}

		private static void tr(Object... o) {

			if (INPUT.length() != 0)

				System.out.println(Arrays.deepToString(o));

		}

	}

}


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

import java.io.*;

import java.util.StringTokenizer;

/**

 * * @author zhengnaishan

 * * @date 2023/2/13 9:21

 */

public class CF1324 {

    public static void main(String[] args) {

        Kattio io = new Kattio();

        int n = io.nextInt();

        int h = io.nextInt();

        int l = io.nextInt();

        int r = io.nextInt();

        int[] a = new int[n];

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

            a[i] = io.nextInt();

        }

        int ans = 0;

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

        long sum = 0;

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

            sum += a[i - 1];

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

                long v = (sum - j) % h;

                s[j] = s[j] + (v >= l && v <= r ? 1 : 0);

                if (j > 0) {

                    s[j] = Math.max(s[j - 1] + (v >= l && v <= r ? 1 : 0), s[j]);

                }

                ans = Math.max(ans, s[j]);

            }

        }

        io.println(ans);

        io.flush();

    }

    public static class Kattio extends PrintWriter {

        private BufferedReader r;

        private StringTokenizer st;

        // 标准 IO

        public Kattio() {

            this(System.in, System.out);

        }

        public Kattio(InputStream i, OutputStream o) {

            super(o);

            r = new BufferedReader(new InputStreamReader(i));

        }

        // 文件 IO

        public Kattio(String intput, String output) throws IOException {

            super(output);

            r = new BufferedReader(new FileReader(intput));

        }

        // 在没有其他输入时返回 null

        public String next() {

            try {

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

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

                return st.nextToken();

            } catch (Exception e) {

            }

            return null;

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public double nextDouble() {

            return Double.parseDouble(next());

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

    }

}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.Deque;

import java.util.HashMap;

import java.util.HashSet;

import java.util.LinkedList;

import java.util.Queue;

import java.util.Random;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.util.Vector;

public class Main {

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

    /* ======================DSU===================== */

    static class dsu {

        static int parent[], n;// min[],value[];

        static long size[];

        dsu(int n) {

            parent = new int[n + 1];

            size = new long[n + 1];

            // min=new int[n+1];

            // value=new int[n+1];

            Main.dsu.n = n;

            makeSet();

        }

        static void makeSet() {

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

                parent[i] = i;

                size[i] = 1;

                // min[i]=i;

            }

        }

        static int find(int a) {

            if (parent[a] == a)

                return a;

            else {

                return parent[a] = find(parent[a]);// Path Compression

            }

        }

        static void union(int a, int b) {

            int setA = find(a);

            int setB = find(b);

            if (setA == setB)

                return;

            if (size[setA] >= size[setB]) {

                parent[setB] = setA;

                size[setA] += size[setB];

            } else {

                parent[setA] = setB;

                size[setB] += size[setA];

            }

        }

    }

    /* ======================================================== */

    static class Pair<X extends Number, Y extends Number> implements Comparator<Pair> {

        X x;

        Y y;

        // Constructor

        public Pair(X x, Y y) {

            this.x = x;

            this.y = y;

        }

        public Pair() {

        }

        @Override

        public int compare(Main.Pair o1, Main.Pair o2) {

            return ((int) (o1.y.intValue() - o2.y.intValue()));// Ascending Order based on 'y'

        }

    }

    /* ===============================Tries================================= */

    static class TrieNode {

        private HashMap<Character, TrieNode> children = new HashMap<>();

        public int size;

        boolean endOfWord;

        public void putChildIfAbsent(char ch) {

            children.putIfAbsent(ch, new TrieNode());

        }

        public TrieNode getChild(char ch) {

            return children.get(ch);

        }

    }

    static private TrieNode root;

    public static void insert(String str) {

        TrieNode curr = root;

        for (char ch : str.toCharArray()) {

            curr.putChildIfAbsent(ch);

            curr = curr.getChild(ch);

            curr.size++;

        }

        // mark the current nodes endOfWord as true

        curr.endOfWord = true;

    }

    public static int search(String word) {

        TrieNode curr = root;

        for (char ch : word.toCharArray()) {

            curr = curr.getChild(ch);

            if (curr == null) {

                return 0;

            }

        }

        // size contains words starting with prefix- word

        return curr.size;

    }

    public boolean delete(TrieNode current, String word, int index) {

        if (index == word.length()) {

            // when end of word is reached only delete if currrent.endOfWord is true.

            if (!current.endOfWord) {

                return false;

            }

            current.endOfWord = false;

            // if current has no other mapping then return true

            return current.children.size() == 0;

        }

        char ch = word.charAt(index);

        TrieNode node = current.children.get(ch);

        if (node == null) {

            return false;

        }

        boolean shouldDeleteCurrentNode = delete(node, word, index + 1);

        // if true is returned then delete the mapping of character and trienode

        // reference from map.

        if (shouldDeleteCurrentNode) {

            current.children.remove(ch);

            // return true if no mappings are left in the map.

            return current.children.size() == 0;

        }

        return false;

    }

    /* ================================================================= */

    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 (long i = 5; i * i <= n; i = i + 6)

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

                return false;

        return true;

    }

    static Pair<Integer, Integer> lowerBound(long[] a, long x) { // x is the target, returns lowerBound. If not found

                                                                 // return -1

        int l = -1, r = a.length;

        while (l + 1 < r) {

            int m = (l + r) >>> 1;

            if (a[m] == x) {

                return new Pair<>(m, 1);

            }

            if (a[m] >= x)

                r = m;

            else

                l = m;

        }

        return new Pair<>(r, 0);

    }

    static Pair<Integer, Integer> upperBound(long[] a, long x) {// x is the target, returns upperBound. If not found

        int l = -1, r = a.length;

        while (l + 1 < r) {

            int m = (l + r) >>> 1;

            if (a[m] == x) {

                return new Pair<>(m, 1);

            }

            if (a[m] <= x)

                l = m;

            else

                r = m;

        }

        return new Pair<>(l + 1, 0);

    }

    static long gcd(long a, long b) {

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    static long lcm(long a, long b) {

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

    }

    static long power(long x, long y) {

        long res = 1;

        while (y > 0) {

            if (y % 2 == 1)

                res = (res * x);

            y >>= 1;

            x = (x * x);

        }

        return res;

    }

    public double binPow(double x, int n) {// binary exponentiation with negative power as well

        if (n == 0)

            return 1.0;

        double binPow = binPow(x, n / 2);

        if (n % 2 == 0) {

            return binPow * binPow;

        } else {

            return n > 0 ? (binPow * binPow * x) : (binPow * binPow / x);

        }

    }

    static long ceil(long x, long y) {

        return (x % y == 0 ? x / y : (x / y + 1));

    }

    /*

     * ===========Modular Operations==================

     */

    static long modPower(long x, long y, long p) {

        long res = 1;

        x = x % p;

        while (y > 0) {

            if (y % 2 == 1)

                res = (res * x) % p;

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

            x = (x * x) % p;

        }

        return res;

    }

    static long modInverse(long n, long p) {

        return modPower(n, p - 2, p);

    }

    static long modAdd(long a, long b) {

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

    }

    static long modMul(long a, long b) {

        return ((a % mod) * (b % mod)) % mod;

    }

    static long[] fac = new long[200000 + 5];

    static long[] invFac = new long[200000 + 5];

    static long nCrModPFermat(int n, int r) {

        if (r == 0)

            return 1;

        // return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod)

        // % mod) % mod;

        return (fac[n] * invFac[r] % mod * invFac[n - r] % mod) % mod;

    }

    /*

     * ===============================================

     */

    static void ruffleSort(long[] a) {

        int n = a.length;

        Random r = new Random();

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

            int oi = r.nextInt(n);

            long temp = a[i];

            a[i] = a[oi];

            a[oi] = temp;

        }

        Arrays.sort(a);

    }

    static void ruffleSort(int[] a) {

        int n = a.length;

        Random r = new Random();

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

            int oi = r.nextInt(n);

            int temp = a[i];

            a[i] = a[oi];

            a[oi] = temp;

        }

        Arrays.sort(a);

    }

    static boolean isVowel(char ch) {

        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';

    }

    static String binString32(int n) {

        StringBuilder str = new StringBuilder("");

        String bin = Integer.toBinaryString(n);

        if (bin.length() != 32) {

            for (int k = 0; k < 32 - bin.length(); k++) {

                str.append("0");

            }

            str.append(bin);

        }

        return str.toString();

    }

    static class sparseTable {

        public static int st[][];

        public static int log = 4;

        static int func(int a, int b) {// make func as per question(here min range query)

            return (int) gcd(a, b);

        }

        void makeTable(int n, int a[]) {

            st = new int[n][log];

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

                st[i][0] = a[i];

            }

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

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

                    st[i][j] = func(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);

                }

            }

        }

        static int query(int l, int r) {

            int length = r - l + 1;

            int k = 0;

            while ((1 << (k + 1)) <= length) {

                k++;

            }

            return func(st[l][k], st[r - (1 << k) + 1][k]);

        }

        static void printTable(int n) {

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

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

                    System.out.print(st[i][j] + " ");

                }

                System.out.println();

            }

        }

    }

    /*

     * ====================================Main=================================

     */

    // static int st[], a[];

    // static void buildTree(int treeIndex, int lo, int hi) {

    // if (hi == lo) {

    // st[treeIndex] = a[lo];

    // return;

    // }

    // int mid = (lo + hi) / 2;

    // buildTree(treeIndex * 2 + 1, lo, mid);

    // buildTree(treeIndex * 2 + 2, mid + 1, hi);

    // st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);

    // }

    // static void update(int treeIndex, int lo, int hi, int arrIndex, int val) {

    // if (hi == lo) {

    // st[treeIndex] = val;

    // a[arrIndex] = val;

    // return;

    // }

    // int mid = (hi + lo) / 2;

    // if (mid < arrIndex) {

    // update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val);

    // } else {

    // update(treeIndex * 2 + 1, lo, mid, arrIndex, val);

    // }

    // st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);

    // }

    // static int query(int treeIndex, int lo, int hi, int l, int r) {

    // if (l <= lo && r >= hi) {

    // return st[treeIndex];

    // }

    // if (l > hi || r < lo) {

    // return 0;

    // }

    // int mid = (hi + lo) / 2;

    // return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r));

    // }

    // static int merge(int a, int b) {

    // return a + b;

    // }

    public static long findKthPositive(long[] A, long k) {

        int l = 0, r = A.length, m;

        while (l < r) {

            m = (l + r) / 2;

            if (A[m] - 1 - m < k)

                l = m + 1;

            else

                r = m;

        }

        return l + k;

    }

    static int[] z_function(char ar[]) {

        int[] z = new int[ar.length];

        z[0] = ar.length;

        int l = 0;

        int r = 0;

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

            if (r < i) {

                l = i;

                r = i;

                while (r < ar.length && ar[r - l] == ar[r])

                    r++;

                z[i] = r - l;

                r--;

            } else {

                int k = i - l;

                if (z[k] < r - i + 1) {

                    z[i] = z[k];

                } else {

                    l = i;

                    while (r < ar.length && ar[r - l] == ar[r])

                        r++;

                    z[i] = r - l;

                    r--;

                }

            }

        }

        return z;

    }

    static void mergeSort(int a[]) {

        int n = a.length;

        if (n >= 2) {

            int mid = n / 2;

            int left[] = new int[mid];

            int right[] = new int[n - mid];

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

                left[i] = a[i];

            }

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

                right[i - mid] = a[i];

            }

            mergeSort(left);

            mergeSort(right);

            mergeSortedArray(left, right, a);

        }

    }

    static void mergeSortedArray(int left[], int right[], int a[]) {

        int i = 0, j = 0, k = 0, n = left.length, m = right.length;

        while (i != n && j != m) {

            if (left[i] < right[j]) {

                a[k++] = left[i++];

            } else {

                a[k++] = right[j++];

            }

        }

        while (i != n) {

            a[k++] = left[i++];

        }

        while (j != m) {

            a[k++] = right[j++];

        }

    }

    // BINARY SEARCH

    // count of set bits in a particular position

    // suffix max array/ suffix sum array/ prefix

    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;

        }

        int[] intArr(int n) {

            int res[] = new int[n];

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

                res[i] = nextInt();

            return res;

        }

        long[] longArr(int n) {

            long res[] = new long[n];

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

                res[i] = nextLong();

            return res;

        }

    }

    static FastReader f = new FastReader();

    static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));

    static ArrayList<ArrayList<Integer>> g = new ArrayList<>();

    static HashSet<Integer> set = new HashSet<>();

    static int maxLevel = 0, farthestNode = -1;

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

        int t = 1;

        // t = f.nextInt();

        int tc = 1;

        // fac[0] = 1;

        // for (int i = 1; i <= 200000; i++) {

        // fac[i] = fac[i - 1] * i % mod;

        // invFac[i] = modInverse(fac[i], mod);

        // }

        while (t-- != 0) {

            int n = f.nextInt();

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

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

            }

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

                int u = f.nextInt();

                int v = f.nextInt();

                g.get(u).add(v);

                g.get(v).add(u);

            }

            dfs(1, -1, 0);

            int endPt1 = farthestNode;

            dfs(farthestNode, -1, 0);

            int endPt2 = farthestNode;

            // w.write(endPt1 + " " + endPt2 + "\n");

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

            nodesInTheDia(endPt1, endPt2, n, stack);

            // w.write(set+"\n");

            int max = 0, maxNodeOutsideDiameter = -1;

            for (int node : set) {

                // int level[] = new int[n + 1];

                // int vis[] = new int[n + 1];

                // vis[node] = 1;

                // level[node] = 0;

                // Queue<Integer> q = new LinkedList<>();

                // q.add(node);

                // int flag = 0;

                // while (!q.isEmpty()) {

                //     int cur = q.poll();

                //     for (int child : g.get(cur)) {

                //         if (vis[child] == 0 && !set.contains(child)) {

                //             vis[child] = 1;

                //             level[child] = level[cur] + 1;

                //             q.add(child);

                //             flag = 1;

                //         }

                //     }

                // }

                // if (flag == 1) {

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

                //         if (level[i] > max) {

                //             max = level[i];

                //             maxNodeOutsideDiameter = i;

                //         }

                //     }

                // }

                Pair<Integer,Integer> p=maxDepthNode(node,0,0);

                if(p.y>=max) {

                    max = p.y;

                    maxNodeOutsideDiameter = p.x;

                }

                // w.write(p.y+" "+p.x+" "+node+"\n");

            }

            if(maxNodeOutsideDiameter==-1 || maxNodeOutsideDiameter==endPt1 || maxNodeOutsideDiameter==endPt2) {

                for(int i:set){

                    if(i!=endPt1 && i!=endPt2){

                        maxNodeOutsideDiameter=i;

                        break;

                    }

                }

            }

            w.write((set.size() - 1 + max) + "\n");

            w.write(endPt1 + " " + endPt2 + " " + maxNodeOutsideDiameter + "\n");

        }

        w.flush();

    }

    static Pair<Integer,Integer> maxDepthNode(int node,int parent,int depth){

        // if(g.get(node).size()==1){

        //     return new Pair<>(node,depth);

        // }

        Pair<Integer,Integer> max=new Pair<>(node,depth);

        for(int child:g.get(node)){

            if(child!=parent && !set.contains(child)){

                Pair<Integer,Integer> p=maxDepthNode(child,node,depth+1);

                if(p.y>max.y){

                    max=p;

                }

            }

        }

        return max;

    }

    static void dfs(int node, int parent, int level) {

        // System.out.println(node);

        if (level >= maxLevel) {

            maxLevel = level;

            farthestNode = node;

        }

        for (int i : g.get(node)) {

            if (i != parent) {

                dfs(i, node, level + 1);

            }

        }

    }

    static void printPath(Vector<Integer> stack) {

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

            set.add(stack.get(i));

        }

    }

    static void DFS(boolean vis[], int x, int y, Vector<Integer> stack) {

        stack.add(x);

        if (x == y) {

            printPath(stack);

            return;

        }

        vis[x] = true;

        if (g.get(x).size() > 0) {

            for (int j = 0; j < g.get(x).size(); j++) {

                if (vis[g.get(x).get(j)] == false) {

                    DFS(vis, g.get(x).get(j), y, stack);

                }

            }

        }

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

    }

    static void nodesInTheDia(int x, int y, int n, Vector<Integer> stack) {

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

        DFS(vis, x, y, stack);

    }

}

/*

 */


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

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 = 1;
         while(tt-->  0){
             long x =fastReader.nextLong();
             ArrayList<Long> left = new ArrayList<>();
             long ans1 = 1, ans2 = x;
             for(long i = 1; i *i <= x ; i++){
                 if(x%i == 0 && lcm(i,(x/i)) == x){
                     if(max(ans1,ans2) > max(i,(x/i))){
                         ans1= i;
                         ans2 = (x/i);
                     }

                 }
             }

             /*
             Collections.sort(left);
             for(int i = 0 ;i  < left.size() ; i++){
                 if(left.get(i) >= max(ans1,ans2)) break;
                 for(int j= i; j < left.size(); j++){
                    if(left.get(i) >= max(ans1,ans2)) break;
                     if(lcm(left.get(i),left.get(j)) == x && max(left.get(i),left.get(j)) < max(ans1,ans2)){
                         ans1 = left.get(i);
                         ans2 = left.get(j);
                     }
                 }
             }
             out.println(left.size());
             out.println(sqrt(x));

              */
             out.println(ans1 + " " + ans2);

         }

         out.close();
     }

    static class Pair{
        int x;
        int y;
        Pair(int x, int y){
            this.x  = x;
            this.y = y;
        }

    }

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


import java.util.*;

public class Main{

	public static void main(String []args){

		Scanner sc = new Scanner(System.in);

		long x = sc.nextLong();

		long ans = 1;

		for(long i=1; i<=Math.sqrt(x); i++){

			if(x%i==0&&gcd(i,x/i)==1){

				ans = i;

			}

		}

		System.out.println(ans+ " "+ (x/ans));

	}

	static long gcd(long a, long b){

		if(a%b==0) return b;

		return gcd(b, a%b);

	}

}


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

import java.util.*;

public class OneRemove {

	public static void main(String [] args) {

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		while(t-->0)

		{

			String s=sc.next();

			int one=0;

			int zero=0;

			int tone=0;

			int temp=0;

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

			{

				if(s.charAt(i)-'0'==1)

				{

					tone++;

				}

			}

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

			{

				if(s.charAt(i)-'0'==1)

				{

					one++;

					temp++;

				}

				if(temp==tone)

				{

					break;

				}

				if(one>0 && s.charAt(i)-'0'==0)

				{

					zero++;

				}

			}

			System.out.println(zero);

		}

	}

}


A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey:  c=[1,2,4]c=[1,2,4];  c=[3,5,6,8]c=[3,5,6,8];  c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6
10 7 1 9 10 15
OutputCopy26
InputCopy1
400000
OutputCopy400000
InputCopy7
8 9 26 11 12 29 14
OutputCopy55
NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].

// ceil using integer division: ceil(x/y) = (x+y-1)/y

import com.sun.source.tree.Tree;

import java.lang.reflect.Array;

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

        Reader.init(System.in);

        int t;

//        t = Reader.nextInt();

        t = 1;

        while (t-- > 0) {

            int n = Reader.nextInt();

            HashMap<Long,Long> map = new HashMap<>();

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

                long num = Reader.nextLong();

                map.put(num-i,map.getOrDefault(num-i,0L)+num);

            }

            long ans = 0;

            for(long key : map.keySet()){

                ans = Math.max(ans,map.get(key));

            }

            System.out.println(ans);

        }

    }

    public static long[] factorial(int n){

        long mod = 998244353;

        long[] factorials = new long[n];

        factorials[1] = 1;

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

            factorials[i] = (factorials[i-1]*i)%mod;

        }

        return factorials;

    }

    public static long ncr(long n, long r) {

        long p = 1, k = 1;

        if (n - r < r) {

            r = n - r;

        }

        if (r != 0) {

            while (r > 0) {

                p *= n;

                k *= r;

                long m = gcd(p, k);

                p /= m;

                k /= m;

                n--;

                r--;

            }

        } else {

            p = 1;

        }

        return p;

    }

    public 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; (long) i * i <= n; i = i + 6){

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

                return false;

            }

        }

        return true;

    }

    public static int powOf2JustSmallerThanN(int n) {

        n |= n >> 1;

        n |= n >> 2;

        n |= n >> 4;

        n |= n >> 8;

        n |= n >> 16;

        return n ^ (n >> 1);

    }

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

        int count = 0;

        if (l < r) {

            int m = (l + r) / 2;

            count += mergeSortAndCount(arr, l, m);

            count += mergeSortAndCount(arr, m + 1, r);

            count += mergeAndCount(arr, l, m, r);

        }

        return count;

    }

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

        int[] left = Arrays.copyOfRange(arr, l, m + 1);

        int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);

        int i = 0, j = 0, k = l, swaps = 0;

        while (i < left.length && j < right.length) {

            if (left[i] <= right[j])

                arr[k++] = left[i++];

            else {

                arr[k++] = right[j++];

                swaps += (m + 1) - (l + i);

            }

        }

        while (i < left.length)

            arr[k++] = left[i++];

        while (j < right.length)

            arr[k++] = right[j++];

        return swaps;

    }

    public static void reverseArray(int[] arr,int start, int end) {

        int temp;

        while (start < end) {

            temp = arr[start];

            arr[start] = arr[end];

            arr[end] = temp;

            start++;

            end--;

        }

    }

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

        if(a==0){

            return b;

        }

        return gcd(b%a,a);

    }

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

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

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

    }

    public static long largeExponentMod(long x,long y,long mod){

        // computing (x^y) % mod

        x%=mod;

        long ans = 1;

        while(y>0){

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

                ans = (ans*x)%mod;

            }

            x = (x*x)%mod;

            y = y >> 1;

        }

        return ans;

    }

    public static boolean[] numOfPrimesInRange(long L, long R){

        boolean[] isPrime = new boolean[(int) (R-L+1)];

        Arrays.fill(isPrime,true);

        long lim = (long) Math.sqrt(R);

        for (long i = 2; i <= lim; i++){

            for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){

                isPrime[(int) (j - L)] = false;

            }

        }

        if (L == 1) isPrime[0] = false;

        return isPrime;

    }

    public static ArrayList<Long> primeFactors(long n){

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

        if(n%2==0){

            factorization.add(2L);

        }

        while(n%2==0){

            n/=2;

        }

        if(n%3==0){

            factorization.add(3L);

        }

        while(n%3==0){

            n/=3;

        }

        if(n%5==0){

            factorization.add(5L);

        }

        while(n%5==0){

//            factorization.add(5L);

            n/=5;

        }

        int[] increments = {4, 2, 4, 2, 4, 6, 2, 6};

        int i = 0;

        for (long d = 7; d * d <= n; d += increments[i++]) {

            if(n%d==0){

                factorization.add(d);

            }

            while (n % d == 0) {

//                factorization.add(d);

                n /= d;

            }

            if (i == 8)

                i = 0;

        }

        if (n > 1)

            factorization.add(n);

        return factorization;

    }

}

class DSU {

    int[] size, parent;

    int n;

    public DSU(int n){

        this.n = n;

        size = new int[n];

        parent = new int[n];

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

            parent[i] = i;

            size[i] = 1;

        }

    }

    public int find(int u){

        if(parent[u]==u){

            return u;

        }

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

    }

    public void merge(int u, int v){

        u = find(u);

        v = find(v);

        if(u!=v){

            if(size[u]>size[v]){

                parent[v] = u;

                size[u] += size[v];

            }

            else{

                parent[u] = v;

                size[v] += size[u];

            }

        }

    }

}

class Reader {

    static BufferedReader reader;

    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */

    static void init(InputStream input) {

        reader = new BufferedReader(

                new InputStreamReader(input) );

        tokenizer = new StringTokenizer("");

    }

    /** get next word */

    static String next() throws IOException {

        while ( ! tokenizer.hasMoreTokens() ) {

            //TODO add check for eof if necessary

            tokenizer = new StringTokenizer(

                    reader.readLine() );

        }

        return tokenizer.nextToken();

    }

    static String nextLine() throws IOException {

        return reader.readLine();

    }

    static int nextInt() throws IOException {

        return Integer.parseInt( next() );

    }

    static long nextLong() throws IOException{

        return Long.parseLong(next() );

    }

    static double nextDouble() throws IOException {

        return Double.parseDouble( next() );

    }

}


import java.io.*;

import java.util.*;

import static java.lang.Math.*;

public class Main {

    public static void main(String[] args) {

        new Main().solve(new InputReader(System.in), new PrintWriter(System.out));

    }

    private void solve(InputReader in, PrintWriter pw) {

        int tt = 1;

//        int tt = in.nextInt();

        while (tt-- > 0) {

            int n = in.nextInt();

            int h = in.nextInt();

            int l = in.nextInt();

            int r = in.nextInt();

            int[] a = in.nextArray(n);

            // f[i][j]代表已经睡了i次且恰好早睡j次时好睡眠的次数

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

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

                Arrays.fill(f[i], Integer.MIN_VALUE);

            }

            f[0][0] = 0;

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

                sum += a[i];

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

                    f[i + 1][j] = max(f[i + 1][j], f[i][j] + check((sum - j) % h, l, r));

                    if (j < n) {

                        f[i + 1][j + 1] = max(f[i + 1][j + 1], f[i][j] + check((sum - (j + 1)) % h, l, r));

                    }

                }

            }

            int maxv = 0;

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

                maxv = max(maxv, f[n][i]);

            }

            pw.println(maxv);

        }

        pw.close();

    }

    private int check(int x, int l, int r) {

        if (x >= l && x <= r) {

            return 1;

        }

        return 0;

    }

    private int gcd(int a, int b) {

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

    }

    private int lcm(int a, int b) {

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

    }

}

class InputReader {

    private final BufferedReader reader;

    private StringTokenizer tokenizer;

    public InputReader(InputStream stream) {

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

        tokenizer = null;

    }

    public String next() {

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

            try {

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

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

        }

        return tokenizer.nextToken();

    }

    public String nextLine() {

        String str;

        try {

            str = reader.readLine();

        } catch (IOException e) {

            throw new RuntimeException(e);

        }

        return str;

    }

    public boolean hasNext() {

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

            String nextLine = null;

            try {

                nextLine = reader.readLine();

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

            if (nextLine == null)

                return false;

            tokenizer = new StringTokenizer(nextLine);

        }

        return true;

    }

    public int nextInt() {

        return Integer.parseInt(next());

    }

    public long nextLong() {

        return Long.parseLong(next());

    }

    public int[] nextArray(int n) {

        int[] a = new int[n];

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

            a[i] = nextInt();

        }

        return a;

    }

}


import java.util.*;

public class Main{

	public static void main(String args[]){

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while(t-- > 0){

			int n = sc.nextInt();

			int[] a = new int[n];

			int[] b = new int[n];

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

			for(int i=0; i<n; i++) b[i] = sc.nextInt();

			Arrays.sort(a);

			Arrays.sort(b);

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

				System.out.print(a[i] + " ");

			System.out.println("");

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

				System.out.print(b[i] + " ");

			System.out.println("");

		}

	}

}


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

import java.util.*;

import java.io.*;

import static java.lang.Math.*;

public class test {

    final static int MOD = 1000000007;

    final static int intMax = 1000000000;

    final static int intMin = -1000000000;

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

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

    static int add(int a, int b) {

        return (a + b) % MOD;

    }

    static int sub(int a, int b) {

        return (a - b + MOD) % MOD;

    }

    static int mult(int a, int b) {

        return (int)((((long)(a)) * b) % MOD);

    }

    static class Reader {

        final private int BUFFER_SIZE = 1 << 16;

        private DataInputStream din;

        private byte[] buffer;

        private int bufferPointer, bytesRead;

        public Reader() {

            din = new DataInputStream(System.in);

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public Reader(String file_name) throws IOException {

            din = new DataInputStream(new FileInputStream(file_name));

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public String readLine() throws IOException {

            byte[] buf = new byte[360]; // line length

            int cnt = 0, c;

            while ((c = read()) != -1) {

                if (c == '\n')

                    break;

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

            }

            return new String(buf, 0, cnt);

        }

        public int nextInt() throws IOException {

            int ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do {

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

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

            if (neg)

                return -ret;

            return ret;

        }

        public long nextLong() throws IOException {

            long ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do {

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

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

            if (neg)

                return -ret;

            return ret;

        }

        public double nextDouble() throws IOException {

            double ret = 0, div = 1;

            byte c = read();

            while (c <= ' ')

                c = read();

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

            if (neg)

                c = read();

            do {

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

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

            if (c == '.') {

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

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

                }

            }

            if (neg)

                return -ret;

            return ret;

        }

        private void fillBuffer() throws IOException {

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

            if (bytesRead == -1)

                buffer[0] = -1;

        }

        private byte read() throws IOException {

            if (bufferPointer == bytesRead)

                fillBuffer();

            return buffer[bufferPointer++];

        }

        public void close() throws IOException {

            if (din == null)

                return;

            din.close();

        }

    }

    static class Sb_Output implements Closeable, Flushable{

        StringBuilder sb;

        OutputStream os;

        int BUFFER_SIZE;

        public Sb_Output(String s) throws Exception {

            os = new BufferedOutputStream(new FileOutputStream(new File(s)));

            BUFFER_SIZE = 1 << 16;

            sb = new StringBuilder(BUFFER_SIZE);

        }

        public void print(String s) {

            sb.append(s);

            if(sb.length() >= (BUFFER_SIZE>>1)) {

                flush();

            }

        }

        public void println(String s) {

            print(s);

            print("\n");

        }

        public void println(int i) {

            println("" + i);

        }

        public void println(long i) {

            println("" + i);

        }

        public void flush() {

            try {

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

                sb = new StringBuilder(BUFFER_SIZE);

            }catch(IOException e) {

                e.printStackTrace();

            }

        }

        public void close() {

            flush();

            try {

                os.close();

            }catch(IOException e) {

                e.printStackTrace();

            }

        }

    }

    static ArrayList<Integer>[] adj;

    static int root, c[];

    static int[] tin, tout;

    static int timer = 0;

    static boolean poss = true;

    static ArrayList<Integer> dfs(int v, int p){

        int start = timer++;

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

        if(c[v] == 0) ret.add(v);

        for(int i : adj[v]) {

            if(i == p) continue;

            ArrayList<Integer> cur = dfs(i, v);

            for(int j : cur) {

                ret.add(j);

                if(ret.size() == c[v]) {

                    ret.add(v);

                }

            }

        }

        poss &= timer - 1 - start >= c[v];

        return ret;

    }

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

        Reader in = new Reader();

//		Reader in = new Reader("poetry.in");

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

//        BufferedReader br = new BufferedReader(new FileReader("poetry.in"));

        int n = in.nextInt();

        adj = new ArrayList[n];

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

            adj[i] = new ArrayList<Integer>();

        }

        c = new int[n];

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

            int p = in.nextInt();

            c[i] = in.nextInt();

            if(p == 0) root = i;

            else {

                --p;

                adj[p].add(i);

                adj[i].add(p);

            }

        }

        ArrayList<Integer> ans = dfs(root, -1);

        if(!poss) {

            System.out.println("NO");

        } else{

            System.out.println("YES");

            int[] res = new int[n];

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

                res[ans.get(i)] = i + 1;

            }

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

                System.out.print(res[i] + " ");

            }

            System.out.println();

        }

        in.close();

    }

    static class pair{

        int x, y;

        pair(int a, int b){

            x = a; y = b;

        }

    }

}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

import java.util.Scanner;

public class Second {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        double n = sc.nextInt();

        double ans = 0;

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

            ans += (1.0 / i);

        }

        System.out.println(ans);

    }

}


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    OutputWriter out = new OutputWriter(outputStream);
    AGarland solver = new AGarland();
    solver.solve(1, in, out);
    out.close();
  }

  static class AGarland {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      int n = in.nextInt();
      int[] a = new int[n];
      int[] cnt = new int[2];
      cnt[0] = n / 2;
      cnt[1] = n - cnt[0];
      for (int i = 0; i < n; i++) {
        a[i] = in.nextInt();

      }
      int[][][][] dp = new int[n + 1][n + 1][n + 1][2];
      int inf = (int) 1e9;
      for (int i = 0; i < n + 1; i++) {
        for (int j = 0; j < n + 1; j++) {
          for (int k = 0; k < n + 1; k++) {
            Arrays.fill(dp[i][j][k], inf);
          }
        }
      }
      dp[0][0][0][0] = dp[0][0][0][1] = 0;

      for (int i = 1; i <= n; i++) {
        if (a[i - 1] == 0 || a[i - 1] % 2 == 1) {
          for (int j = 0; j < i; j++) {
            int k = i - j;
            dp[i][j][k][1] = Math.min(dp[i - 1][j][k - 1][1], dp[i - 1][j][k - 1][0] + 1);
          }
        }

        if (a[i - 1] == 0 || a[i - 1] % 2 == 0) {
          for (int j = 1; j <= i; j++) {
            int k = i - j;
            dp[i][j][k][0] = Math.min(dp[i - 1][j - 1][k][0], dp[i - 1][j - 1][k][1] + 1);
          }
        }

      }
      out.println(Math.min(dp[n][cnt[0]][cnt[1]][0], dp[n][cnt[0]][cnt[1]][1]));
    }

  }

  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 UnknownError();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new UnknownError();
        }
        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 UnknownError();
        }
        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 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);
    }

  }
}


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

import java.util.*;

import static java.lang.Math.*;

import static java.util.Arrays.*;

public class cf1288e {

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

        int n = rni(), m = ni(), block = 550, a[] = riam1(m);

        List<List<Integer>> q = g(n);

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

            q.get(a[i]).add(i);

        }

        PriorityQueue<int[]> pq = new PriorityQueue<>((x, y) -> x[0] / block == y[0] / block ? x[1] - y[1] : x[0] / block - y[0] / block);

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

            for (int j = 1, end = q.get(i).size(); j < end; ++j) {

                pq.add(new int[] {q.get(i).get(j - 1) + 1, q.get(i).get(j) - 1});

            }

            if (q.get(i).size() > 0) {

                pq.add(new int[] {q.get(i).get(q.get(i).size() - 1) + 1, m - 1});

            }

        }

        int ans[] = new int[n], cnt[] = new int[n], distinct = 0, l = 0, r = -1;

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

            ans[i] = i;

        }

        while (!pq.isEmpty()) {

            int qry[] = pq.poll(), i = qry[0], j = qry[1];

            while (l < i) {

                if (--cnt[a[l++]] == 0) {

                    --distinct;

                }

            }

            while (l > i) {

                if (++cnt[a[--l]] == 1) {

                    ++distinct;

                }

            }

            while (r < j) {

                if (++cnt[a[++r]] == 1) {

                    ++distinct;

                }

            }

            while (r > j) {

                if (--cnt[a[r--]] == 0) {

                    --distinct;

                }

            }

            ans[a[i - 1]] = max(ans[a[i - 1]], distinct);

        }

        bit bit = new bit(n, Integer::sum);

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

            if (i == q.get(a[i]).get(0)) {

                // prln(0, n - a[i], bit.qry(n - a[i]));

                ans[a[i]] = max(ans[a[i]], a[i] + bit.qry(n - a[i]));

                // prln(1, n - a[i] - 1);

                bit.upd(n - a[i] - 1, 1);

            }

        }

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

            if (q.get(i).size() == 0) {

                ans[i] = i + bit.qry(n - i);

            }

        }

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

            prln(q.get(i).size() > 0 ? 1 : i + 1, ans[i] + 1);

        }

        close();

    }

    @FunctionalInterface

    interface IntOperator {

        int merge(int a, int b);

    }

    static class bit {

        IntOperator op;

        int n, bit[];

        bit(int size, IntOperator operator) {

            bit = new int[n = size + 1];

            op = operator;

        }

        bit(int[] arr, IntOperator operator) {

            bit = new int[(n = arr.length + 1)];

            op = operator;

            for (int i = 0; i < n - 1; ++i) upd(i, arr[i]);

            ++n;

        }

        void upd(int i, int x) {

            ++i;

            while (i < n) {

                bit[i] = op.merge(bit[i], x);

                i += i & (-i);

            }

        }

        int qry(int i) {

            int ans = 0;

            while (i > 0) {

                ans = op.merge(ans, bit[i]);

                i -= i & (-i);

            }

            return ans;

        }

    }

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

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

    static StringTokenizer input;

    static Random __rand = new Random();

    // references

    // IBIG = 1e9 + 7

    // IMAX ~= 2e9

    // LMAX ~= 9e18

    // constants

    static final int IBIG = 1000000007;

    static final int IMAX = 2147483647;

    static final int IMIN = -2147483648;

    static final long LMAX = 9223372036854775807L;

    static final long LMIN = -9223372036854775808L;

    // 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 gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}

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

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

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

    static int randInt(int min, int max) {return __rand.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);}

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

    // graph util

    static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}

    static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}

    static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}

    static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}

    static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}

    static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}

    // input

    static void r() throws IOException {input = new StringTokenizer(rline());}

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

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

    static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;}

    static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}

    static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;}

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

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

    static String n() {return input.nextToken();}

    static int rni() throws IOException {r(); return ni();}

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

    static long rnl() throws IOException {r(); return nl();}

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

    static double rnd() throws IOException {r(); return nd();}

    static double nd() {return Double.parseDouble(n());}

    static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}

    static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}

    static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}

    static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}

    static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}

    static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}

    static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}

    static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}

    // output

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}