D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

import java.io.BufferedOutputStream;

import java.io.Closeable;

import java.io.DataInputStream;

import java.io.Flushable;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintStream;

import java.util.Arrays;

import java.util.InputMismatchException;

import java.util.Objects;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

	static class TaskAdapter implements Runnable {

		@Override

		public void run() {

			InputStream inputStream = System.in;

			OutputStream outputStream = System.out;

			FastReader in = new FastReader(inputStream);

			Output out = new Output(outputStream);

			DNashMatrix solver = new DNashMatrix();

			solver.solve(1, in, out);

			out.close();

		}

	}

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

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

		thread.start();

		thread.join();

	}

	static class DNashMatrix {

		private final int[] ry = new int[] {0, 1, 0, -1};

		private final int[] rx = new int[] {-1, 0, 1, 0};

		private final char[] dir = new char[] {'U', 'R', 'D', 'L'};

		private final char[] rdir = new char[] {'D', 'L', 'U', 'R'};

		Pair<Integer, Integer>[][] arr;

		Pair<Integer, Integer> p;

		char[][] ans;

		int n;

		public DNashMatrix() {

		}

		public void dfs(int x, int y) {

			Utilities.Debug.dbg(x, y);

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

				int cx = x+rx[i], cy = y+ry[i];

				if(inBounds(cx, cy)&&arr[cx][cy].equals(p)&&ans[cx][cy]==0) {

					ans[cx][cy] = rdir[i];

					dfs(cx, cy);

				}

			}

		}

		public boolean inBounds(int x, int y) {

			return x>=0&&y>=0&&x<n&&y<n;

		}

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

			n = in.nextInt();

			arr = new Pair[n][n];

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

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

					arr[i][j] = new Pair<>(Math.max(in.nextInt()-1, -1), Math.max(in.nextInt()-1, -1));

				}

			}

			ans = new char[n][n];

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

				loop:

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

					if(ans[i][j]!=0) {

						continue;

					}

					var v = arr[i][j];

					if(v.a==-1) {

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

							int cx = i+rx[k], cy = j+ry[k];

							if(inBounds(cx, cy)&&arr[cx][cy].equals(v)) {

								ans[i][j] = dir[k];

								p = new Pair<>(v);

								dfs(i, j);

								continue loop;

							}

						}

						pw.println("INVALID");

						return;

					}else if(v.a==i&&v.b==j) {

						ans[i][j] = 'X';

						p = new Pair<>(i, j);

						dfs(i, j);

					}

				}

			}

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

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

					if(ans[i][j]==0) {

						pw.println("INVALID");

						return;

					}

				}

			}

			pw.println("VALID");

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

				pw.println(ans[i]);

			}

		}

	}

	static class Utilities {

		public static class Debug {

			public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;

			private static <T> String ts(T t) {

				if(t==null) {

					return "null";

				}

				try {

					return ts((Iterable) t);

				}catch(ClassCastException e) {

					if(t instanceof int[]) {

						String s = Arrays.toString((int[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof long[]) {

						String s = Arrays.toString((long[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof char[]) {

						String s = Arrays.toString((char[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof double[]) {

						String s = Arrays.toString((double[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof boolean[]) {

						String s = Arrays.toString((boolean[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}

					try {

						return ts((Object[]) t);

					}catch(ClassCastException e1) {

						return t.toString();

					}

				}

			}

			private static <T> String ts(T[] arr) {

				StringBuilder ret = new StringBuilder();

				ret.append("{");

				boolean first = true;

				for(T t: arr) {

					if(!first) {

						ret.append(", ");

					}

					first = false;

					ret.append(ts(t));

				}

				ret.append("}");

				return ret.toString();

			}

			private static <T> String ts(Iterable<T> iter) {

				StringBuilder ret = new StringBuilder();

				ret.append("{");

				boolean first = true;

				for(T t: iter) {

					if(!first) {

						ret.append(", ");

					}

					first = false;

					ret.append(ts(t));

				}

				ret.append("}");

				return ret.toString();

			}

			public static void dbg(Object... o) {

				if(LOCAL) {

					System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");

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

						if(i!=0) {

							System.err.print(", ");

						}

						System.err.print(ts(o[i]));

					}

					System.err.println("]");

				}

			}

		}

	}

	static interface InputReader {

		int nextInt();

	}

	static class FastReader implements InputReader {

		final private int BUFFER_SIZE = 1<<16;

		private DataInputStream din;

		private byte[] buffer;

		private int bufferPointer;

		private int bytesRead;

		public FastReader(InputStream is) {

			din = new DataInputStream(is);

			buffer = new byte[BUFFER_SIZE];

			bufferPointer = bytesRead = 0;

		}

		public int nextInt() {

			int ret = 0;

			byte c = skipToDigit();

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

			if(neg) {

				c = read();

			}

			do {

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

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

			if(neg) {

				return -ret;

			}

			return ret;

		}

		private boolean isDigit(byte b) {

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

		}

		private byte skipToDigit() {

			byte ret;

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

			return ret;

		}

		private void fillBuffer() {

			try {

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

			}catch(IOException e) {

				e.printStackTrace();

				throw new InputMismatchException();

			}

			if(bytesRead==-1) {

				buffer[0] = -1;

			}

		}

		private byte read() {

			if(bytesRead==-1) {

				throw new InputMismatchException();

			}else if(bufferPointer==bytesRead) {

				fillBuffer();

			}

			return buffer[bufferPointer++];

		}

	}

	static class Output implements Closeable, Flushable {

		public StringBuilder sb;

		public OutputStream os;

		public int BUFFER_SIZE;

		public String lineSeparator;

		public Output(OutputStream os) {

			this(os, 1<<16);

		}

		public Output(OutputStream os, int bs) {

			BUFFER_SIZE = bs;

			sb = new StringBuilder(BUFFER_SIZE);

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

			lineSeparator = System.lineSeparator();

		}

		public void println(char[] c) {

			println(String.valueOf(c));

		}

		public void println(String s) {

			sb.append(s);

			println();

		}

		public void println() {

			sb.append(lineSeparator);

		}

		private void flushToBuffer() {

			try {

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

			}catch(IOException e) {

				e.printStackTrace();

			}

			sb = new StringBuilder(BUFFER_SIZE);

		}

		public void flush() {

			try {

				flushToBuffer();

				os.flush();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

		public void close() {

			flush();

			try {

				os.close();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

	}

	static class Pair<T1, T2> implements Comparable<Pair<T1, T2>> {

		public T1 a;

		public T2 b;

		public Pair(Pair<T1, T2> p) {

			this(p.a, p.b);

		}

		public Pair(T1 a, T2 b) {

			this.a = a;

			this.b = b;

		}

		public String toString() {

			return a+" "+b;

		}

		public int hashCode() {

			return Objects.hash(a, b);

		}

		public boolean equals(Object o) {

			if(o instanceof Pair) {

				Pair p = (Pair) o;

				return a.equals(p.a)&&b.equals(p.b);

			}

			return false;

		}

		public int compareTo(Pair<T1, T2> p) {

			int cmp = ((Comparable<T1>) a).compareTo(p.a);

			if(cmp==0) {

				return ((Comparable<T2>) b).compareTo(p.b);

			}

			return cmp;

		}

	}

}


D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that:  each array contains nn elements;  each element is an integer from 11 to mm;  for each array, there is exactly one pair of equal elements;  for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are:  [1,2,1][1,2,1];  [1,3,1][1,3,1];  [1,4,1][1,4,1];  [2,3,2][2,3,2];  [2,4,2][2,4,2];  [3,4,3][3,4,3].

import java.io.IOException;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

    static final Reader input = new Reader();

    static final int MOD = 998244353;

    static int n, m;

    static long[] fac;

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

        n = input.nextInt();

        m = input.nextInt();

        if(n == 2) {

            System.out.println(0);

            return;

        }

        fac = new long[m+1];

        fac[0] = 1;

        fac[1] = 1;

        for(int i = 2; i < fac.length; ++i) fac[i] = (i*fac[i-1]) % MOD;

        long common = 0;

        for(int x = n-2; x < m; ++x) {

            common += (((fac[x-1] * inverse(fac[x-1 - (n-3)])) % MOD) * x ) % MOD;

            if(common >= MOD) common -= MOD;

        }

        long answer = 0;

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

            answer += (common * inverse((fac[i-1]*fac[(n-1)-i-1]) % MOD)) % MOD;

            if(answer >= MOD) answer -= MOD;

        }

        System.out.println(answer);

    }

    static long inverse(long a) {

        return power(a, MOD-2);

    }

    static long power(long a, long b) {

        long result = 1;

        while(b > 0) {

            if(b % 2 == 1) result = (result*a)%MOD;

            a = (a*a) % MOD;

            b /= 2;

        }

        return result;

    }

    static class Reader {

        BufferedReader reader;

        StringTokenizer string;

        public Reader() {

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

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

    }

}


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

import java.util.Scanner;

import java.util.*;

public class Solution {

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

    static Kattio io = new Kattio();

    static int h = (int) 1e5 * 2 + 2;

    public static void main(String[] args) {

        int n = io.nextInt();

        int[] arr = new int[n];

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

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

            arr[i] = io.nextInt();

            vis[arr[i]] = true;

        }

        new Solution().solve(n, vis, arr);

        io.close();

    }

    public void solve(int n, boolean[] vis, int[] arr) {

        int odd = 0;

        int even = 0;

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

            if (!vis[i]) {

                if (i % 2 == 0) even++;

                else odd++;

            }

        }

        int cur = 0;

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

            if (arr[i] == 0 || arr[i - 1] == 0) continue;

            if((arr[i] + arr[i - 1]) % 2 == 1) cur++;

        }

        List<int[]> blocks = new ArrayList();

        int cnt = 0;

        int l = -1;

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

            if (arr[i] == 0) {

                if (i > 0 && arr[i - 1] != 0) {

                    l = arr[i - 1] % 2;

                }

                cnt++;

            } else {

                if (cnt == 0) continue;

                blocks.add(new int[]{cnt, l, arr[i] % 2});

                cnt = 0;

            }

        }

        if (cnt > 0) {

            blocks.add(new int[]{cnt, l, -1});

        }

        List<int[]> same = new ArrayList();

        List<int[]> edge = new ArrayList();

        for (int[] block : blocks) {

            if (block[1] == -1 || block[2] == -1) {

                int x = -1;

                if (block[1] != -1) x = block[1];

                else x = block[2];

                edge.add(new int[]{block[0], x});

            } else if ((block[1] + block[2]) % 2 == 0) {

                same.add(new int[]{block[0], block[1]});

            }

        }

        int ans = blocks.size() - edge.size() - same.size();

        same.sort((a, b) -> a[0] - b[0]);

        for (int[] f : same) {

            if (f[1] == 1) {

                if (odd >= f[0]) odd -= f[0];

                else ans += 2;

            } else {

                if (even >= f[0]) even -= f[0];

                else ans += 2;

            }

        }

        for (int[] f : edge) {

            if (f[1] == -1) {

                if (n != 1) ans++;

            } else if (f[1] == 1) {

                if (odd >= f[0]) {

                    odd -= f[0];

                } else ans++;

            } else {

                if (even >= f[0]) {

                    even -= f[0];

                } else ans++;

            }

        }

        io.println(ans + cur);

    }

    public int gcd(int a, int b) {

        if (b == 0) return a;

        return gcd(b, a % b);

    }

    public int countbit(long n) {

        int count = 0;

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

            if (((1L << i) & n) != 0) count++;

        }

        return count;

    }

    public int firstbit(int n) {

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

            if (((1 << i) & n) != 0) return i;

        }

        return -1;

    }

}

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

}


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import java.util.Scanner;

/**

 *

 * @author eslam

 */

public class NewYearAndNaming {

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();

        int m = input.nextInt();

        String sn[] =new String[n];

        String sm[] =new String[m];

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

            sn[i] = input.next();

        }

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

            sm[i] = input.next();

        }

        int q = input.nextInt();

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

            int x = input.nextInt();

            String w = "";

            if(x%n==0){

                w = w+sn[n-1];

            }else{

                w = w +sn[(x%n)-1];

            }

            if(x%m==0){

                w = w+sm[m-1];

            }else{

                w = w +sm[(x%m)-1];

            }

            System.out.println(w);

        }

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayDeque;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Deque;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.PriorityQueue;

import java.util.Queue;

import java.util.Set;

import java.util.Stack;

import java.util.StringTokenizer;

import java.util.function.BiFunction;

import java.util.function.Function;

public class Main {

  int a[];

  int n;

  int ddp[][];

  int getValue(int l, int r) {

    if(ddp[l][r] != 0) {

      return ddp[l][r];

    }

    if(l==r) {

      return a[l];

    }

    for(int i = l; i < r; i++) {

      int x1 = getValue(l, i);

      int x2 = getValue(i+1, r);

      if(x1 == x2 && x1 != -1) {

        ddp[l][r] = x1 +1;

        return x1 + 1;

      }

    }

    ddp[l][r] = -1;

    return -1;

  }

  void solve() {

    n = in.nextInt();

    ddp = new int[n][n];

    a = new int[n];

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

      a[i] = in.nextInt();

    }

    int dp[] = new int[n];

    dp[0] = 1;

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

      dp[i] = Integer.MAX_VALUE;

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

        int x = getValue(l, i);

        if(x == -1) {

          continue;

        }

        x = 1;

        if (l > 0) {

          x += dp[l-1];

        }

        dp[i] = Integer.min(dp[i], x);

      }

    }

    out(dp[n-1]);

  }

    public static void main(String[] args)

    {

      new Main().solve();//.multiple();

    }

    final static  FastReader in = new FastReader();

    private void multiple() {

      int t = in.nextInt();

      for(; t >0; t--) {

        solve();

      }

    }

    private <T> void out(T s) {

      System.out.println(s);

    }

    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;

        }

    }

}


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

import java.io.*;

import java.util.*;

public class ProblemD {

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

		Scanner s= new Scanner();

		int n = s.readInt();

		int a = s.readInt();

		int b = s.readInt();

		int k = s.readInt();

		int arr[] = new int[n];

		int p = a+b,ans = 0;

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

			arr[i] = s.readInt();

			if(arr[i]%p == 0){

				arr[i] = b;

				arr[i]+=a;

			}else arr[i]%=p;

		}

		sort(arr);

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

			if(arr[i]>0){

				arr[i]-=a;

				if(arr[i]>0 && k>=(arr[i]+a-1)/a){

					k-=((arr[i]+a-1)/a);

					arr[i] = 0;

				}

			}

			if(arr[i]<=0)ans++;

		}

		System.out.println(ans);

	}

	public static void sort(int arr[]){

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

		for(int it:arr)list.add(it);

		Collections.sort(list);

		for(int i = 0;i<arr.length;i++)arr[i] = list.get(i)  ;

	}

	static class Pair{

		int x,y;

		public Pair(int x,int y){

			this.x = x;

			this.y = y;

		}

	}

	static class Scanner{

		BufferedReader br;

		StringTokenizer st;

		public Scanner(){

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

		}

	    public String read()

	    {

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

	            try {	st = new StringTokenizer(br.readLine()); }

	            catch (Exception e) {	e.printStackTrace(); }

	         }

	         return st.nextToken();

	     }

	     public int  readInt() { return Integer.parseInt(read()); }

	     public long readLong() { return Long.parseLong(read()); }

	     public double readDouble(){return Double.parseDouble(read());}

	     public  String readLine() throws Exception { return br.readLine(); }

	}

}


import java.util.*;

public class Main {

    public static void main(String[] args) {

Scanner s=new Scanner(System.in);

int n=s.nextInt();

int m=s.nextInt();

s.nextLine();

String s1=s.nextLine();

String[] str=s1.split(" ");

String s2=s.nextLine();

String[] str1=s2.split(" ");

int q=s.nextInt();

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

{

    int x=s.nextInt();

    x--;

    System.out.println(str[x%n]+str1[x%m]);

}

    }

}


E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.BufferedOutputStream;

import java.io.UncheckedIOException;

import java.util.Objects;

import java.nio.charset.Charset;

import java.util.StringTokenizer;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.BufferedReader;

import java.util.Comparator;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author mikit

 */

public class Main {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        LightScanner in = new LightScanner(inputStream);

        LightWriter out = new LightWriter(outputStream);

        ENewYearAndCastleConstruction solver = new ENewYearAndCastleConstruction();

        solver.solve(1, in, out);

        out.close();

    }

    static class ENewYearAndCastleConstruction {

        public void solve(int testNumber, LightScanner in, LightWriter out) {

            int n = in.ints();

            Vec2l[] points = new Vec2l[n];

            for (int i = 0; i < n; i++) points[i] = new Vec2l(in.longs(), in.longs());

            long ans = n * (n - 1L) * (n - 2L) * (n - 3L) * (n - 4L) / 24;

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

                int m = 0;

                Vec2l[] angles = new Vec2l[n - 1];

                {

                    Vec2l now = points[t];

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

                        if (i != t) {

                            angles[m] = new Vec2l(points[i].x - now.x, points[i].y - now.y);

                            m++;

                        }

                    }

                    IntroSort.sort(angles, Vec2l::compareToByAngle);

                }

                //System.out.println(Arrays.stream(angles).map(angle -> Double.toString(Math.atan2(angle.y, angle.x))).collect(Collectors.joining(", ")));

                int hi = 0;

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

                    while (hi < j + m && (hi <= j || angles[j].det(angles[hi % m]) > 0)) {

                        hi++;

                    }

                    int cnt = hi - j;

                    ans -= (cnt - 1L) * (cnt - 2L) * (cnt - 3L) / 6;

                }

            }

            out.ans(ans).ln();

        }

    }

    static class InsertionSort {

        private InsertionSort() {

        }

        static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) {

            for (int i = low; i < high; i++) {

                for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) {

                    ArrayUtil.swap(a, j - 1, j);

                }

            }

        }

    }

    static class QuickSort {

        private QuickSort() {

        }

        private static <T> void med(T[] a, int low, int x, int y, int z, Comparator<? super T> comparator) {

            if (comparator.compare(a[z], a[x]) < 0) {

                ArrayUtil.swap(a, low, x);

            } else if (comparator.compare(a[y], a[z]) < 0) {

                ArrayUtil.swap(a, low, y);

            } else {

                ArrayUtil.swap(a, low, z);

            }

        }

        static <T> int step(T[] a, int low, int high, Comparator<? super T> comparator) {

            int x = low + 1, y = low + (high - low) / 2, z = high - 1;

            if (comparator.compare(a[x], a[y]) < 0) {

                med(a, low, x, y, z, comparator);

            } else {

                med(a, low, y, x, z, comparator);

            }

            int lb = low + 1, ub = high;

            while (true) {

                while (comparator.compare(a[lb], a[low]) < 0) {

                    lb++;

                }

                ub--;

                while (comparator.compare(a[low], a[ub]) < 0) {

                    ub--;

                }

                if (lb >= ub) {

                    return lb;

                }

                ArrayUtil.swap(a, lb, ub);

                lb++;

            }

        }

    }

    static interface Verified {

    }

    static final class ArrayUtil {

        private ArrayUtil() {

        }

        public static <T> void swap(T[] a, int x, int y) {

            T t = a[x];

            a[x] = a[y];

            a[y] = t;

        }

    }

    static final class BitMath {

        private BitMath() {

        }

        public static int count(int v) {

            v = (v & 0x55555555) + ((v >> 1) & 0x55555555);

            v = (v & 0x33333333) + ((v >> 2) & 0x33333333);

            v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);

            v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);

            v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);

            return v;

        }

        public static int msb(int v) {

            if (v == 0) {

                throw new IllegalArgumentException("Bit not found");

            }

            v |= (v >> 1);

            v |= (v >> 2);

            v |= (v >> 4);

            v |= (v >> 8);

            v |= (v >> 16);

            return count(v) - 1;

        }

    }

    static class HeapSort {

        private HeapSort() {

        }

        private static <T> void heapfy(T[] a, int low, int high, int i, T val, Comparator<? super T> comparator) {

            int child = 2 * i - low + 1;

            while (child < high) {

                if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) {

                    child++;

                }

                if (comparator.compare(val, a[child]) >= 0) {

                    break;

                }

                a[i] = a[child];

                i = child;

                child = 2 * i - low + 1;

            }

            a[i] = val;

        }

        static <T> void sort(T[] a, int low, int high, Comparator<T> comparator) {

            for (int p = (high + low) / 2 - 1; p >= low; p--) {

                heapfy(a, low, high, p, a[p], comparator);

            }

            while (high > low) {

                high--;

                T pval = a[high];

                a[high] = a[low];

                heapfy(a, low, high, low, pval, comparator);

            }

        }

    }

    static class LightWriter implements AutoCloseable {

        private final Writer out;

        private boolean autoflush = false;

        private boolean breaked = true;

        public LightWriter(Writer out) {

            this.out = out;

        }

        public LightWriter(OutputStream out) {

            this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));

        }

        public LightWriter print(char c) {

            try {

                out.write(c);

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter print(String s) {

            try {

                out.write(s, 0, s.length());

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter ans(String s) {

            if (!breaked) {

                print(' ');

            }

            return print(s);

        }

        public LightWriter ans(long l) {

            return ans(Long.toString(l));

        }

        public LightWriter ln() {

            print(System.lineSeparator());

            breaked = true;

            if (autoflush) {

                try {

                    out.flush();

                } catch (IOException ex) {

                    throw new UncheckedIOException(ex);

                }

            }

            return this;

        }

        public void close() {

            try {

                out.close();

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

        }

    }

    static class LightScanner {

        private BufferedReader reader = null;

        private StringTokenizer tokenizer = null;

        public LightScanner(InputStream in) {

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

        }

        public String string() {

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

                try {

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

                } catch (IOException e) {

                    throw new UncheckedIOException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public int ints() {

            return Integer.parseInt(string());

        }

        public long longs() {

            return Long.parseLong(string());

        }

    }

    static class Vec2l implements Comparable<Vec2l> {

        public long x;

        public long y;

        public Vec2l(long x, long y) {

            this.x = x;

            this.y = y;

        }

        public long det(Vec2l other) {

            return x * other.y - other.x * y;

        }

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Vec2l vec2i = (Vec2l) o;

            return x == vec2i.x &&

                    y == vec2i.y;

        }

        public int hashCode() {

            return Objects.hash(x, y);

        }

        public String toString() {

            return "(" + x + ", " + y + ")";

        }

        public int compareTo(Vec2l o) {

            if (x == o.x) {

                return Long.compare(y, o.y);

            }

            return Long.compare(x, o.x);

        }

        public int compareToByAngle(Vec2l o) {

            if ((y >= 0) != (o.y >= 0)) {

                return y >= 0 ? 1 : -1;

            } else if ((x >= 0) != (o.x >= 0)) {

                if (y >= 0) return x >= 0 ? -1 : 1;

                else return x >= 0 ? 1 : -1;

            } else {

                return Long.compare(0, x * o.y - o.x * y);

            }

        }

    }

    static class IntroSort {

        private static int INSERTIONSORT_THRESHOLD = 16;

        private IntroSort() {

        }

        static <T> void sort(T[] a, int low, int high, int maxDepth, Comparator<T> comparator) {

            while (high - low > INSERTIONSORT_THRESHOLD) {

                if (maxDepth-- == 0) {

                    HeapSort.sort(a, low, high, comparator);

                    return;

                }

                int cut = QuickSort.step(a, low, high, comparator);

                sort(a, cut, high, maxDepth, comparator);

                high = cut;

            }

            InsertionSort.sort(a, low, high, comparator);

        }

        public static <T> void sort(T[] a, Comparator<T> comparator) {

            if (a.length <= INSERTIONSORT_THRESHOLD) {

                InsertionSort.sort(a, 0, a.length, comparator);

            } else {

                sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator);

            }

        }

    }

}


C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1

import java.io.*;

import java.math.BigDecimal;

import java.math.BigInteger;

import java.math.RoundingMode;

import java.util.*;

/**

 * @author Tran Anh Tai

 * @template for CP codes

 * What a trick prob!

 */

public class ProbC {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        InputReader in = new InputReader(inputStream);

        PrintWriter out = new PrintWriter(outputStream);

        Task solver = new Task();

        solver.solve(in, out);

        out.close();

    }

    // main solver

    static class Task{

        static int MOD = 1000000007;

        public void solve(InputReader in, PrintWriter out) {

            int n = in.nextInt();

            long a[] = new long[n];

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

                a[i] = in.nextInt();

            }

            long b[] = a.clone();

            Arrays.sort(b);

            long[][] dp = new long[2][n];

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

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

                    dp[(i & 1)][j] = dp[(i + 1) & 1][j] + Math.abs(a[i - 1]- b[j]);

                    if (j > 0){

                        dp[(i & 1)][j] = Math.min(dp[(i & 1)][j], dp[(i & 1)][j - 1]);

                    }

                }

            }

            out.println(dp[n & 1][n - 1]);

        }

    }

    // fast input reader class;

    static class InputReader {

        BufferedReader br;

        StringTokenizer st;

        public InputReader(InputStream stream) {

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

        }

        public String nextToken() {

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

                String line = null;

                try {

                    line = br.readLine();

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

                if (line == null) {

                    return null;

                }

                st = new StringTokenizer(line);

            }

            return st.nextToken();

        }

        public int nextInt() {

            return Integer.parseInt(nextToken());

        }

        public long nextLong(){

            return Long.parseLong(nextToken());

        }

    }

}


D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3

3

4

4

OutputCopy

? 5 6

? 3 1

? 1 2

! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:

import java.util.*;

import java.io.*;

public class Main {

  static StringBuilder sb;

  static dsu dsu;

  static long fact[];

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

  static ArrayList<HashSet<Integer>> graph; // set for o(1) removal

  static HashSet<Integer> leaves;

  static void solve() {

     int n =i();

     graph = new ArrayList();

     leaves = new HashSet();

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

         graph.add(new HashSet());

     }

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

         int u = i()-1;

         int v = i()-1;

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

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

     }

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

         int s = graph.get(i).size();

         if(s==1) leaves.add(i);

     }

     while(leaves.size()>1){

         int u = leaves.iterator().next();

         leaves.remove(u);

         int v = leaves.iterator().next();

         leaves.remove(v);

         int w = query(u,v);

         if(w==v||w==u){

             System.out.println("! "+(w+1));

             System.out.flush();

             return;

         }

         delete(u,-1,w);

         delete(v,-1,w);

         if(graph.get(w).size()<=1) leaves.add(w);

     }

     int ans = leaves.iterator().next();

     System.out.println("! "+(ans+1));

     System.out.flush();

  }

  static int query(int u,int v){

      u++;

      v++;

      System.out.println("? "+u+" "+v);

      System.out.flush();

      int lca = i()-1;

      return lca;

  }

  static void delete(int u,int p,int lca){

      leaves.remove(u);

      for(int e : graph.get(u)){

          if(e==p) continue;

          if(e==lca){

              graph.get(lca).remove(u);

          }else delete(e,u,lca);

      }

    //   graph.get(u).clear();

  }

  public static void main(String[] args) {

    sb = new StringBuilder();

    int test = 1;

    while (test-- > 0) {

      solve();

    }

    System.out.println(sb);

  }

  /*

   * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)

   * { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }

   */

//**************NCR%P******************

  static long ncr(int n, int r) {

    if (r > n)

      return (long) 0;

    long res = fact[n] % mod;

    // System.out.println(res);

    res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;

    res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;

    // System.out.println(res);

    return res;

  }

  static long p(long x, long y)// POWER FXN //

  {

    if (y == 0)

      return 1;

    long res = 1;

    while (y > 0) {

      if (y % 2 == 1) {

        res = (res * x) % mod;

        y--;

      }

      x = (x * x) % mod;

      y = y / 2;

    }

    return res;

  }

//**************END******************

  // *************Disjoint set

  // union*********//

  static class dsu {

    int parent[];

    dsu(int n) {

      parent = new int[n];

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

        parent[i] = -1;

    }

    int find(int a) {

      if (parent[a] < 0)

        return a;

      else {

        int x = find(parent[a]);

        parent[a] = x;

        return x;

      }

    }

    void merge(int a, int b) {

      a = find(a);

      b = find(b);

      if (a == b)

        return;

      parent[b] = a;

    }

  }

//**************PRIME FACTORIZE **********************************//

  static TreeMap<Integer, Integer> prime(long n) {

    TreeMap<Integer, Integer> h = new TreeMap<>();

    long num = n;

    for (int i = 2; i <= Math.sqrt(num); i++) {

      if (n % i == 0) {

        int nt = 0;

        while (n % i == 0) {

          n = n / i;

          nt++;

        }

        h.put(i, nt);

      }

    }

    if (n != 1)

      h.put((int) n, 1);

    return h;

  }

//****CLASS PAIR ************************************************

  static class Pair implements Comparable<Pair> {

    int x;

    long y;

    Pair(int x, long y) {

      this.x = x;

      this.y = y;

    }

    public int compareTo(Pair o) {

      return (int) (this.y - o.y);

    }

  }

//****CLASS PAIR **************************************************

  static class InputReader {

    private InputStream stream;

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

    private int curChar;

    private int numChars;

    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public int read() {

      if (numChars == -1)

        throw new InputMismatchException();

      if (curChar >= numChars) {

        curChar = 0;

        try {

          numChars = stream.read(buf);

        } catch (IOException e) {

          throw new InputMismatchException();

        }

        if (numChars <= 0)

          return -1;

      }

      return buf[curChar++];

    }

    public int Int() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      int sgn = 1;

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

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

          throw new InputMismatchException();

        res *= 10;

        res += c - '0';

        c = read();

      } while (!isSpaceChar(c));

      return res * sgn;

    }

    public String String() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      StringBuilder res = new StringBuilder();

      do {

        res.appendCodePoint(c);

        c = read();

      } while (!isSpaceChar(c));

      return res.toString();

    }

    public boolean isSpaceChar(int c) {

      if (filter != null)

        return filter.isSpaceChar(c);

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

    }

    public String next() {

      return String();

    }

    public interface SpaceCharFilter {

      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

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

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

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

        if (i != 0)

          writer.print(' ');

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

    public void flush() {

      writer.flush();

    }

  }

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

  static OutputWriter out = new OutputWriter(System.out);

  public static long[] sort(long[] a2) {

    int n = a2.length;

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

    for (long i : a2)

      l.add(i);

    Collections.sort(l);

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

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

    return a2;

  }

  public static char[] sort(char[] a2) {

    int n = a2.length;

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

    for (char i : a2)

      l.add(i);

    Collections.sort(l);

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

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

    return a2;

  }

  public static long pow(long x, long y) {

    long res = 1;

    while (y > 0) {

      if (y % 2 != 0) {

        res = (res * x);// % modulus;

        y--;

      }

      x = (x * x);// % modulus;

      y = y / 2;

    }

    return res;

  }

//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  public static long gcd(long x, long y) {

    if (x == 0)

      return y;

    else

      return gcd(y % x, x);

  }

  // ******LOWEST COMMON MULTIPLE

  // *********************************************

  public static long lcm(long x, long y) {

    return (x * (y / gcd(x, y)));

  }

//INPUT PATTERN********************************************************

  public static int i() {

    return in.Int();

  }

  public static long l() {

    String s = in.String();

    return Long.parseLong(s);

  }

  public static String s() {

    return in.String();

  }

  public static int[] readArrayi(int n) {

    int A[] = new int[n];

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

      A[i] = i();

    }

    return A;

  }

  public static long[] readArray(long n) {

    long A[] = new long[(int) n];

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

      A[i] = l();

    }

    return A;

  }

}


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Collections;

import java.util.StringTokenizer;

public class CollectingPackages {

    static PrintWriter pw;

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

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

        pw = new PrintWriter(System.out);

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

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

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

            ArrayList<Point> points = new ArrayList<>();

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

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

                int x = Integer.parseInt(st.nextToken());

                int y = Integer.parseInt(st.nextToken());

                points.add(new Point(x, y));

            }

            Collections.sort(points);

            if (!test(points)) pw.println("NO");

        }

        pw.close();

    }

    static boolean test(ArrayList<Point> points) {

        Point pos = new Point(0, 0);

        StringBuilder sb = new StringBuilder();

        for (Point p : points) {

            if (p.x >= pos.x && p.y >= pos.y) {

                sb.append(diff(pos, p));

                pos = p;

            } else return false;

        }

        pw.println("YES");

        pw.println(sb);

        return true;

    }

    static StringBuilder diff(Point p1, Point p2) {

        StringBuilder res = new StringBuilder();

        res.append("R".repeat(Math.max(0, p2.x - p1.x)));

        res.append("U".repeat(Math.max(0, p2.y - p1.y)));

        return res;

    }

    static class Point implements Comparable<Point> {

        public int x, y;

        public Point(int x, int y) {

            this.x = x;

            this.y = y;

        }

        @Override

        public int compareTo(Point o) {

            int xComp = Integer.compare(x, o.x);

            if (xComp != 0) return xComp;

            else return Integer.compare(y, o.y);

        }

    }

}


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

// package TreeQueries;

import java.util.*;

import java.io.*;

public class addEdge {

    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;

        }

    }

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

        FastReader sc = new FastReader();

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

        int t = 1;

        // t = sc.nextInt();

        while (t-- != 0) {

            int n = sc.nextInt();

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

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

                adj.add(new ArrayList<Integer>());

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

                int u = sc.nextInt();

                int v = sc.nextInt();

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

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

            }

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

            int limit = (int) (Math.log(n) / Math.log(2));

            int parent[][] = new int[n + 1][limit + 1];

            dfs(1, 0, 0, adj, level, parent);

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

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

                    int x = parent[j][i - 1];

                    parent[j][i] = parent[x][i - 1];

                }

            }

            int q = sc.nextInt();

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

                int k = 5;

                int qur[] = new int[k];

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

                    qur[j] = sc.nextInt();

                }

                int withoutedge = getDist(qur[2], qur[3], parent, level);

                int d2 = getDist(qur[2], qur[0], parent, level) + 1 + getDist(qur[1], qur[3], parent, level);

                int d3 = getDist(qur[3], qur[0], parent, level) + 1 + getDist(qur[1], qur[2], parent, level);

                int withedge = Math.min(d2, d3);

                int ans = Integer.MAX_VALUE;

                if (withedge % 2 == qur[4] % 2) {

                    ans = withedge;

                }

                if (withoutedge % 2 == qur[4] % 2) {

                    ans = Math.min(ans, withoutedge);

                }

                if (ans <= qur[4]) {

                    w.write("YES\n");

                } else {

                    w.write("NO\n");

                }

            }

            w.flush();

        }

        w.close();

    }

    private static int getDist(int a, int b, int[][] parent, int[] level) {

        if (level[a] > level[b]) {

            int temp = a;

            a = b;

            b = temp;

        }

        int diff = level[b] - level[a];

        int ans = 0;

        while (diff > 0) {

            int log = (int) (Math.log(diff) / Math.log(2));

            b = parent[b][log];

            diff -= (1 << log);

            ans += (1 << log);

        }

        if(a==b)return ans;

        for(int i=parent[0].length-1;i>=0;i--){

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

                a = parent[a][i];

                b = parent[b][i];

                ans += 2*(1 << (i));

            }

        }

        return ans+2;

    }

    private static void dfs(int i, int p, int l, ArrayList<ArrayList<Integer>> adj, int[] level, int[][] parent) {

        parent[i][0] = p;

        level[i] = l;

        for (int nbr : adj.get(i)) {

            if (nbr == p)

                continue;

            dfs(nbr, i, l + 1, adj, level, parent);

        }

    }

}


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

import java.util.*;

import java.io.*;

public class Main {

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

    //Code here

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

    PrintWriter wr = new PrintWriter(System.out);

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

    String s = br.readLine();

    int count = 0;

    for(char ch = 'z';ch>='a';ch--){

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

            if(s.length()==1) break;

            if(s.charAt(i)!=ch) continue;

            if(i==0){

                if(s.charAt(i+1)==ch-1){

                    count++;

                    s = s.substring(0,i) + s.substring(i+1);

                }

            }else if(i==s.length()-1){

                if(s.charAt(i-1)==ch-1){

                    count++;

                    s = s.substring(0,i) + s.substring(i+1);

                }

            }else{

                if(s.charAt(i+1)==ch-1||s.charAt(i-1)==ch-1){

                    count++;

                    s = s.substring(0,i) + s.substring(i+1);

                    i-=2;

                }

            }

        }

    }

    wr.println(count);

    wr.close();

  }

}


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

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

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

    static final FastReader sc = new FastReader();

    //I invented a new word!Plagiarism!

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

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

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

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

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

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

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

    public static boolean sorted(int a[])

    {

        int n=a.length,i;

        int b[]=new int[n];

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

        b[i]=a[i];

        Arrays.sort(b);

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

        {

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

            return false;

        }

        return true;

    }

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

	{

	        int n=sc.nextInt();

	        int a[]=new int[n];

	        int b[]=new int[n];

	        int i; long pos=0;

	        long ans=0;

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

	        a[i]=sc.nextInt();

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

	        b[i]=sc.nextInt();

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

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

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

	        {

	            arr.add((long)b[i]-(long)a[i]);

	            if(a[i]-b[i]<=0)

	            neg.add((long)a[i]-(long)b[i]);

	            else

	            pos++;

	        }

	        ans=(pos*(pos-1))/2;

	        Collections.sort(arr);

	        for(long it:neg)

	        {

	           ans+=lower_bound(arr,0,arr.size()-1,it);

	        }

	        System.out.println(ans);

	}

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

    {

        if (high >= low) {

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

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

                return mid;

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

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

            else

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

        }

        return -1;

    }

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

    {

        if (high >= low) {

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

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

                return mid;

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

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

            else

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

        }

        return -1;

    }

	public static int lis(int[] arr) {

	int n = arr.length;

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

	al.add(arr[0]);

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

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

		if(arr[i]>=x) {

			al.add(arr[i]);

		}else {

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

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

		}

	}

	return al.size();

}

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

{

    //Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

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

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

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

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

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

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

static boolean isPrime(long N)

    {

        if (N<=1)  return false;

        if (N<=3)  return true;

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

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

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

                return false;

        return true;

    }

    static int countBits(long a)

    {

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

    }

    static long fact(long N)

    {

        long mod=1000000007;

        long n=2;

        if(N<=1)return 1;

        else

        {

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

        }

        return n;

    }

    private static boolean isInteger(String s) {

        try {

            Integer.parseInt(s);

        } catch (NumberFormatException e) {

            return false;

        } catch (NullPointerException e) {

            return false;

        }

        return true;

    }

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

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

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

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

    }

    private static boolean isPalindrome(String str) {

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

        while (i < j)

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

                return false;

        return true;

    }

    private static String reverseString(String str) {

        StringBuilder sb = new StringBuilder(str);

        return sb.reverse().toString();

    }

	static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(

                new InputStreamReader(System.in));

        }

        String next()

        {

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

                try {

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

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

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

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

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


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

import java.util.*;

import java.io.*;

public class Practice {
	static boolean multipleTC = true;
	FastReader in;
	PrintWriter out;

	final static int mod = 1000000007;
	final static int mod2 = 998244353;
	final double E = 2.7182818284590452354;
	final double PI = 3.14159265358979323846;
	int MAX = 100005;

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

	void run() throws Exception {
		in = new FastReader();
		out = new PrintWriter(System.out);
		int T = (multipleTC) ? ni() : 1;
		pre();
		for (int t = 1; t <= T; t++)
			solve(t);
		out.flush();
		out.close();
	}

	void pre() throws Exception {
	}

	// All the best
	void solve(int TC) throws Exception {
		int n = ni(), arr[] = readArr(n);
		int max = 2 * n;
		boolean used[] = new boolean[max + 1];
		int res[] = new int[max];
		boolean possible = true;
		for (int i = 0, j = 0; i < n; i++, j += 2) {
			if (arr[i] >= max || used[arr[i]]) {
				possible = false;
				break;
			} else {
				res[j] = arr[i];
				used[arr[i]] = true;
			}
		}
		if (possible) {
			for (int i = 0, j = 1; i < n; i++, j += 2) {
				boolean found = false;
				for (int k = arr[i] + 1; k <= max; k++) {
					if (!used[k]) {
						res[j] = k;
						found = true;
						used[k] = true;
						break;
					}
				}
				if (!found) {
					possible = false;
					break;
				}
			}
			if (possible) {
				StringBuilder ans = new StringBuilder();
				for (int i : res) {
					ans.append(i + " ");
				}
				pn(ans);
			}else {
				pn("-1");
			}

		} else {
			pn("-1");
		}
	}

	int[] readArr(int n) throws Exception {
		int arr[] = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = ni();
		}
		return arr;
	}

	void sort(int arr[]) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < arr.length; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = 0; i < arr.length; i++)
			arr[i] = list.get(i);
	}

	public long max(long... arr) {
		long max = arr[0];
		for (long itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public int max(int... arr) {
		int max = arr[0];
		for (int itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public long min(long... arr) {
		long min = arr[0];
		for (long itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public int min(int... arr) {
		int min = arr[0];
		for (int itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public long sum(long... arr) {
		long sum = 0;
		for (long itr : arr)
			sum += itr;
		return sum;
	}

	public long sum(int... arr) {
		long sum = 0;
		for (int itr : arr)
			sum += itr;
		return sum;
	}

	String bin(long n) {
		return Long.toBinaryString(n);
	}

	String bin(int n) {
		return Integer.toBinaryString(n);
	}

	static int bitCount(int x) {
		return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
	}

	static void dbg(Object... o) {
		System.err.println(Arrays.deepToString(o));
	}

	int bit(long n) {
		return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
	}

	int abs(int a) {
		return (a < 0) ? -a : a;
	}

	long abs(long a) {
		return (a < 0) ? -a : a;
	}

	void p(Object o) {
		out.print(o);
	}

	void pn(Object o) {
		out.println(o);
	}

	void pni(Object o) {
		out.println(o);
		out.flush();
	}

	String n() throws Exception {
		return in.next();
	}

	String nln() throws Exception {
		return in.nextLine();
	}

	int ni() throws Exception {
		return Integer.parseInt(in.next());
	}

	long nl() throws Exception {
		return Long.parseLong(in.next());
	}

	double nd() throws Exception {
		return Double.parseDouble(in.next());
	}

	class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		public FastReader(String s) throws Exception {
			br = new BufferedReader(new FileReader(s));
		}

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

		String nextLine() throws Exception {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				throw new Exception(e.toString());
			}
			return str;
		}
	}
}