B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1
0
1337
NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).

import java.io.*;

import java.util.StringTokenizer;

public class Problem1288B {

    static Scanner scanner = new Scanner(System.in);

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

        int tc = scanner.nextInt();

        while (tc-->0){

            int a = scanner.nextInt();

            int b = scanner.nextInt();

            int cnt = 0;

            if (a<9 && b<9) {

                System.out.println(0);

                continue;

            }

            boolean flag = allNine(b);

            while (b>0){

                cnt++;

                b/=10;

            }

            if (flag){

                long val = (long) cnt*a;

                System.out.println(val);

                continue;

            }

            long val = (long) a*(cnt-1);

            System.out.println(val);

        }

    }

    static boolean allNine(int b){

        boolean yes = true;

        String str = Integer.toString(b);

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

            if (str.charAt(i)!='9'){

                yes = false;

                break;

            }

        }

        return yes;

    }

    static class Scanner {

        StringTokenizer st;

        BufferedReader br;

        public Scanner(InputStream s) {

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

        }

        public Scanner(FileReader s) throws FileNotFoundException {

            br = new BufferedReader(s);

        }

        public String next() throws IOException {

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

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

            return st.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public String nextLine() throws IOException {

            return br.readLine();

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public boolean ready() throws IOException {

            return br.ready();

        }

    }

}


F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks:  a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders);  an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders);  a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2

import java.io.*;

import java.util.Arrays;

import java.util.BitSet;

import java.util.HashMap;

import java.util.InputMismatchException;

import java.util.function.LongBinaryOperator;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

	static class TaskAdapter implements Runnable {

		@Override

		public void run() {

			long startTime = System.currentTimeMillis();

			InputStream inputStream = System.in;

			OutputStream outputStream = System.out;

			FastReader in = new FastReader(inputStream);

			Output out = new Output(outputStream);

			FAttackOnRedKingdom solver = new FAttackOnRedKingdom();

			int testCount = in.nextInt();

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

				solver.solve(i, in, out);

			out.close();

			System.err.println(System.currentTimeMillis()-startTime+"ms");

		}

	}

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

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

		thread.start();

		thread.join();

	}

	static class FAttackOnRedKingdom {

		LongBinaryOperator[][][] grundy;

		public FAttackOnRedKingdom() {

			int n = 5;

			grundy = new LongBinaryOperator[n+1][n+1][n+1];

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

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

					for(int k = 1; k<=5; k++) {

						var p = new FAttackOnRedKingdom.Provider(i, j, k);

						HashMap<FAttackOnRedKingdom.State, Integer> hm = new HashMap<>();

						int[][] prev = new int[5][3];

						for(int b = 1; b<5; b++) {

							prev[b] = p.get(b-1);

						}

						int start, len;

						for(int b = 4; ; b++) {

							Utilities.leftShift(prev, 1);

							prev[4] = p.get(b);

							FAttackOnRedKingdom.State cur = new FAttackOnRedKingdom.State(prev);

							if(hm.containsKey(cur)) {

								int val = hm.get(cur);

								start = val;

								len = b-4-val;

								break;

							}else {

								hm.put(cur, b-4);

							}

						}

//						Utilities.Debug.dbg(start, len);

						grundy[i][j][k] = (a, b) -> {

							if(a<start) {

								return p.dp((int) a, (int) b);

							}

							return p.dp((int) ((a-start)%len+start), (int) b);

						};

					}

				}

			}

		}

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

			int n = in.nextInt(), x = in.nextInt(), y = in.nextInt(), z = in.nextInt();

			long[] arr = in.nextLong(n);

			long xor = 0;

			long[] sub = new long[] {x, y, z};

			long[] val = new long[n];

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

				xor ^= val[i] = grundy[x][y][z].applyAsLong(arr[i], 0);

			}

			int ans = 0;

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

				xor ^= val[i];

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

					if((xor^grundy[x][y][z].applyAsLong(Math.max(0, arr[i]-sub[j]), j))==0) {

						ans++;

					}

				}

				xor ^= val[i];

			}

			pw.println(ans);

		}

		static class Provider {

			int n;

			int[] v;

			int[][] dp;

			public static boolean valid(int cur, int prev) {

				return prev==0||cur!=prev;

			}

			public Provider(int... v) {

				this.v = v;

				n = 16;

				dp = new int[16][3];

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

					dp[i][0] = dp[i][1] = dp[i][2] = -1;

				}

			}

			public int[] get(int left) {

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

					dp(left, i);

				}

				return dp[left];

			}

			private int dp(int left, int prev) {

				if(left>=n) {

					int[][] ndp = new int[n*2][3];

					System.arraycopy(dp, 0, ndp, 0, n);

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

						ndp[j][0] = ndp[j][1] = ndp[j][2] = -1;

					}

					dp = ndp;

					n *= 2;

				}

				if(dp[left][prev]!=-1) {

					return dp[left][prev];

				}

				BitSet ans = new BitSet();

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

					if(valid(i, prev)) {

						ans.set(dp(Math.max(0, left-v[i]), i));

					}

				}

				return dp[left][prev] = ans.nextClearBit(0);

			}

		}

		static class State {

			int[][] a;

			public State(int[][] a) {

				this.a = Utilities.deepClone(a);

			}

			public boolean equals(Object o) {

				if(this==o) return true;

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

				FAttackOnRedKingdom.State state = (FAttackOnRedKingdom.State) o;

				return Arrays.deepEquals(a, state.a);

			}

			public int hashCode() {

				return Arrays.deepHashCode(a);

			}

		}

	}

	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(int i) {

			println(String.valueOf(i));

		}

		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 FastReader implements InputReader {

		final private int BUFFER_SIZE = 1<<16;

		private final DataInputStream din;

		private final 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;

		}

		public long nextLong() {

			long 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 Utilities {

		public static <T> void leftShift(T[] arr, int offSet) {

			T[] tmp = (T[]) new Object[offSet];

			System.arraycopy(arr, 0, tmp, 0, offSet);

			System.arraycopy(arr, offSet, arr, 0, arr.length-offSet);

			System.arraycopy(tmp, 0, arr, arr.length-offSet, offSet);

		}

		public static int[][] deepClone(int[][] arr) {

			int[][] ret = new int[arr.length][];

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

				ret[i] = arr[i].clone();

			}

			return ret;

		}

		public static class Debug {

			public static 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("]");

				}

			}

		}

	}

	interface InputReader {

		int nextInt();

		long nextLong();

		default long[] nextLong(int n) {

			long[] ret = new long[n];

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

				ret[i] = nextLong();

			}

			return ret;

		}

	}

}


C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
OutputCopy1

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;

public class C1320C {

    public static void main(String[] args) {
        var scanner = new BufferedScanner();
        var writer = new PrintWriter(new BufferedOutputStream(System.out));

        var n = scanner.nextInt();
        var m = scanner.nextInt();
        var p = scanner.nextInt();
        var a = new int[n];
        var ca = new int[n];
        var orderA = new Integer[n];
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
            ca[i] = scanner.nextInt();
            orderA[i] = i;
        }
        Arrays.sort(orderA, Comparator.comparingInt(i -> a[i]));
        var b = new int[m];
        var cb = new int[m];
        var orderB = new Integer[m];
        for (int i = 0; i < m; i++) {
            b[i] = scanner.nextInt();
            cb[i] = scanner.nextInt();
            orderB[i] = i;
        }
        Arrays.sort(orderB, Comparator.comparingInt(i -> b[i]));
        var x = new int[p];
        var y = new int[p];
        var z = new int[p];
        var orderX = new Integer[p];
        for (int i = 0; i < p; i++) {
            x[i] = scanner.nextInt();
            y[i] = scanner.nextInt();
            z[i] = scanner.nextInt();
            orderX[i] = i;
        }
        Arrays.sort(orderX, Comparator.comparingInt(i -> x[i]));

        var acc = new long[4 * m]; // acc[i,j]表示范围i到j的累计
        var max = new long[4 * m]; // max[i,j]表示范围i到j区间内acc的最大值
        Arrays.fill(max, UNTOUCHED);
        for (int ib : orderB) {
            var j = orderB[ib];
            update(acc, max, 0, 0, m - 1, ib, ib, -cb[j]);
        }
        var ix = 0;
        var ans = UNTOUCHED;
        for (var i : orderA) {
            var k = 0;
            while (ix < p && x[(k = orderX[ix])] < a[i]) {
                var startJ = searchFirstGreater(b, orderB, y[k]);
                update(acc, max, 0, 0, m - 1, startJ, m - 1, z[k]);
                ix++;
            }
            ans = Math.max(ans, max[0] - ca[i]);
        }
        writer.println(ans);

        scanner.close();
        writer.flush();
        writer.close();
    }

    static final long UNTOUCHED = Long.MIN_VALUE;

    private static int searchFirstGreater(int[] a, Integer[] order, int key) {
        var low = 0;
        var high = a.length - 1;
        var ans = Integer.MAX_VALUE;
        while (low <= high) {
            var mid = (low + high) >>> 1;
            if (a[order[mid]] <= key) {
                low = mid + 1;
            } else {
                high = mid - 1;
                ans = Math.min(ans, mid);
            }
        }
        return ans;
    }

    private static void update(long[] acc, long[] max, int index, int low, int high, int targetLow, int targetHigh,
            int inc) {
        if (targetHigh < low || high < targetLow || targetLow > targetHigh) {
            return;
        }
        if (targetLow <= low && high <= targetHigh) {
            acc[index] += inc;
            if (max[index] == UNTOUCHED) {
                max[index] = 0;
            }
            max[index] += inc;
            return;
        }
        if (low < high) {
            var leftIndex = (index << 1) + 1;
            var rightIndex = leftIndex + 1;
            var mid = (low + high) >>> 1;
            update(acc, max, leftIndex, low, mid, targetLow, targetHigh, inc);
            update(acc, max, rightIndex, mid + 1, high, targetLow, targetHigh, inc);
            max[index] = Math.max(max[index], Math.max(max[leftIndex], max[rightIndex]) + acc[index]);
        }
    }

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

        public BufferedScanner(Reader reader) {
            br = new BufferedReader(reader);
        }

        public BufferedScanner() {
            this(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;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    static long gcd(long a, long b) {
        if (a < b) {
            return gcd(b, a);
        }
        while (b > 0) {
            long tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }

    static long inverse(long a, long m) {
        long[] ans = extgcd(a, m);
        return ans[0] == 1 ? (ans[1] + m) % m : -1;
    }

    private static long[] extgcd(long a, long m) {
        if (m == 0) {
            return new long[]{a, 1, 0};
        } else {
            long[] ans = extgcd(m, a % m);
            long tmp = ans[1];
            ans[1] = ans[2];
            ans[2] = tmp;
            ans[2] -= ans[1] * (a / m);
            return ans;
        }
    }

    private static List<Integer> primes(double upperBound) {
        var limit = (int) Math.sqrt(upperBound);
        var isComposite = new boolean[limit + 1];
        var primes = new ArrayList<Integer>();
        for (int i = 2; i <= limit; i++) {
            if (isComposite[i]) {
                continue;
            }
            primes.add(i);
            int j = i + i;
            while (j <= limit) {
                isComposite[j] = true;
                j += i;
            }
        }
        return primes;
    }

}


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.io.Closeable;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Flushable;

/**
 * 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;
			Input in = new Input(inputStream);
			Output out = new Output(outputStream);
			BIrreducibleAnagrams solver = new BIrreducibleAnagrams();
			solver.solve(1, in, out);
			out.close();
		}
	}

	public static void main(String[] args) throws Exception {
		Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29);
		thread.start();
		thread.join();
	}
	static class BIrreducibleAnagrams {
		public BIrreducibleAnagrams() {
		}

		public void solve(int kase, Input in, Output pw) {
			char[] input = in.next().toCharArray();
			int n = input.length;
			int[][] psum = new int[n+1][26];
			for(int i = 1; i<=n; i++) {
				System.arraycopy(psum[i-1], 0, psum[i], 0, 26);
				psum[i][input[i-1]-'a']++;
			}
			int q = in.nextInt();
			while(q-->0) {
				int l = in.nextInt()-1, r = in.nextInt()-1;
				if(r-l+1<=1||input[l]!=input[r]) {
					pw.println("Yes");
					continue;
				}
				int cnt = 0;
				for(int i = 0; i<26; i++) {
					if(psum[r+1][i]-psum[l][i]>0) {
						cnt++;
					}
				}
				if(cnt>=3) {
					pw.println("Yes");
				}else {
					pw.println("No");
				}
			}
		}

	}

	static class Input {
		BufferedReader br;
		StringTokenizer st;

		public Input(InputStream is) {
			this(is, 1<<20);
		}

		public Input(InputStream is, int bs) {
			br = new BufferedReader(new InputStreamReader(is), bs);
			st = null;
		}

		public boolean hasNext() {
			try {
				while(st==null||!st.hasMoreTokens()) {
					String s = br.readLine();
					if(s==null) {
						return false;
					}
					st = new StringTokenizer(s);
				}
				return true;
			}catch(Exception e) {
				return false;
			}
		}

		public String next() {
			if(!hasNext()) {
				throw new InputMismatchException();
			}
			return st.nextToken();
		}

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

	}

	static class Output implements Closeable, Flushable {
		public StringBuilder sb;
		public OutputStream os;
		public int BUFFER_SIZE;
		public boolean autoFlush;
		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);
			autoFlush = false;
			LineSeparator = System.lineSeparator();
		}

		public void println(String s) {
			sb.append(s);
			println();
			if(autoFlush) {
				flush();
			}else if(sb.length()>BUFFER_SIZE >> 1) {
				flushToBuffer();
			}
		}

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

	}
}


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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Manav
 */
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);
        CRemoveAdjacent solver = new CRemoveAdjacent();
        solver.solve(1, in, out);
        out.close();
    }

    static class CRemoveAdjacent {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            StringBuffer buffer = new StringBuffer(in.next());
            int initialSize = buffer.length();
            boolean isUpdated = true;
            for (int it = 0; it < 110 && isUpdated; it++) {
                int currentSize = buffer.length();
                boolean isBreaked = false;
                for (int i = 25; i >= 1; i += -1) {
                    for (int j = 0; j < buffer.length(); j++) {
                        int current = buffer.charAt(j) - 'a';
                        if (current == i) {
                            if (j - 1 >= 0 && buffer.charAt(j - 1) - 'a' == current - 1) {
                                buffer.deleteCharAt(j);
                                isBreaked = true;
                                break;
                            }
                            if (j + 1 < buffer.length() && buffer.charAt(j + 1) - 'a' == current - 1) {
                                buffer.deleteCharAt(j);
                                isBreaked = true;
                                break;
                            }

                        }
                    }
                    if (isBreaked) break;
                }

                int updatedSize = buffer.length();
                if (currentSize == updatedSize) {
                    isUpdated = false;
                }
            }
            out.println(initialSize - buffer.length());
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                if (Character.isValidCodePoint(c)) {
                    res.appendCodePoint(c);
                }
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        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 String next() {
            return nextString();
        }

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

    }
}


A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here:  After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5).  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3).  After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

import java.util.ArrayList;

import java.util.Collections;

import java.util.Scanner;

import java.io.OutputStreamWriter;

import java.io.BufferedWriter;

import java.io.IOException;

public class neko {

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

		Scanner in = new Scanner(System.in);

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

		int n = in.nextInt();

		int q = in.nextInt();

		int[][] mat = new int[2][n];

		int cnt = 0;

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

			int a = in.nextInt();

			int b = in.nextInt();

			a--;

			b--;

			if(mat[a][b]==0) {

				mat[a][b] = 1;

			}

			else if(mat[a][b]==1) {

				mat[a][b] = 0;

				if(a==1) {

					if(mat[a-1][b]==1) {

						cnt--;

					}

					if(b!=n-1 && mat[a-1][b+1]==1) {

						cnt--;

					}

					if(b!=0 && mat[a-1][b-1]==1) {

						cnt--;

					}

				}

				else {

					if(mat[a+1][b]==1) {

						cnt--;

					}

					if(b!=n-1 && mat[a+1][b+1]==1) {

						cnt--;

					}

					if(b!=0 && mat[a+1][b-1]==1) {

						cnt--;

					}

				}

			}

			if(a==1 && mat[a-1][b]==1 && mat[a][b]==1) {

				cnt++;

			}

			if(a==0 && mat[a+1][b]==1 && mat[a][b]==1) {

				cnt++;

			}

			if(a==1 && ((b!=n-1 && mat[a-1][b+1]==1 && mat[a][b]==1))) {

				cnt++;

			}

			if(a==1 && (b!=0 && mat[a-1][b-1]==1 && mat[a][b]==1)) {

				cnt++;

			}

			if(a==0 && (b!=0 && mat[a+1][b-1]==1 && mat[a][b]==1)) {

				cnt++;

			}

			if(a==0 && (b!=n-1 && mat[a+1][b+1]==1 && mat[a][b]==1)) {

				cnt++;

			}

			if(cnt==0) {

				log.write("Yes"+"\n");

			}

			else {

				log.write("No"+"\n");

			}

		}

		log.flush();

	}

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
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);
        CRemoveAdjacent solver = new CRemoveAdjacent();
        solver.solve(1, in, out);
        out.close();
    }

    static class CRemoveAdjacent {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            String s = in.nextString();
            StringBuilder sb = new StringBuilder(s);
            sb.insert(0, '#');
            sb.append('#');
            while (true) {
                boolean ok = false;
                f:
                for (char i = 'z'; i >= 'a'; i--) {
                    for (int j = 1; j < sb.length() - 1; j++) {
                        if (sb.charAt(j) == i) {
                            if (sb.charAt(j - 1) == i - 1 || sb.charAt(j + 1) == i - 1) {
                                sb.deleteCharAt(j);
                                ok = true;
                                break f;
                            }
                        }
                    }
                }
                if (!ok) {
                    break;
                }
            }
            out.println(n - (sb.length() - 2));

        }

    }

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

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                if (Character.isValidCodePoint(c)) {
                    res.appendCodePoint(c);
                }
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

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

        }

    }
}


A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).  Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2
6 3
7 3
OutputCopyYES
NO
Note  The first test case of the example It can be shown that the answer for the second test case of the example is "NO".

import java.util.Scanner;

public class CF3107{

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int testCases = scan.nextInt();

		while(testCases-->0){

			int m = scan.nextInt();

			int n = scan.nextInt();

			if(m%n==0){

				System.out.println("YES");

			}else{

				System.out.println("NO");

			}

		}

	}

}


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111

import java.io.*;

import java.util.StringTokenizer;

public class JavaApplication {

    static BufferedReader in;

    static BufferedWriter out;

    static StringTokenizer st;

    static String token;

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

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

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

        new JavaApplication().Solve();

        out.flush();

    }

    public String getLine() throws IOException {

        return in.readLine();

    }

    private String getToken() throws IOException {

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

            st = new StringTokenizer(getLine(), "\n ");

        return st.nextToken();

    }

    public int getInt() throws IOException {

        return Integer.parseInt(getToken());

    }

    public long getLong() throws IOException {

        return Long.parseLong(getToken());

    }

    //    public char getChar() throws IOException {

////        if (token == null || token.length() == 0)

////            token = getToken();

////        char r = token.charAt(0);

////        token = token.substring(1);

////        return r;

//    }

    public void println() throws IOException {

        out.newLine();

    }

    public void println(Object obj) throws IOException {

        if (obj == null)

            return;

        out.write(String.valueOf(obj));

        out.newLine();

    }

    public void print(Object obj) throws IOException {

        if (obj == null)

            return;

        out.write(String.valueOf(obj));

    }

    class Pair{

        int a;

        int b;

        boolean flag;

        public Pair(int a,int b){

            this.a=a;

            this.b=b;

            flag=false;

        }

        @Override

        public String toString() {

            String s="";

            s=a+" "+b+", ";

            return s;

        }

    }

    private void Solve() throws IOException {

        int t = getInt();

        while (t-- > 0) {

            int n=getInt();

            long spend=0;

            while(n>=10){

                spend+=10*(n/10);

                n=(n%10)+(n/10);

            }

            spend+=n;

            println(spend);

        }

    }

    private int lcm(int n,int m){

        return n*m/gcd(Math.max(n,m),Math.min(n,m));

    }

    private int gcd(int n,int m){

        if(m==0)

            return n;

        return gcd(m,n%m);

    }

}


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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class test{
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);

        int t = Integer.parseInt(br.readLine());
        while(t-- > 0){
            int n = Integer.parseInt(br.readLine());
            Integer[] a = new Integer[n*2];
            StringTokenizer tokenizer = new StringTokenizer(br.readLine());

            for(int i = 0; i < 2*n; i++){
                a[i] = Integer.parseInt(tokenizer.nextToken());
            }

            Arrays.sort(a);

            if(n % 2 == 0){
                // int min = Integer.MAX_VALUE;
                // for(int i = 2; i < (2*n) - 1; i++){
                //     min = Math.min(min, (int)(a[i] - a[i-1]));
                // }
                // pw.println(min);
                pw.println(a[n] - a[n-1]);
            }
            else{
                pw.println(a[n] - a[n-1]);
            }
        }

        pw.flush();
        pw.close();
        br.close();
    }
}


C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2
1 1 2
2 1
OutputCopy1
InputCopy2 2 999999937
2 1
3 1
OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.

import java.io.*;

import java.util.*;

public class Main {

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

        Scanner scn = new Scanner(System.in);

        OutputWriter out = new OutputWriter(System.out);

        // Always print a trailing "\n" and close the OutputWriter as shown at the end of your output

        // example:

        int n=scn.nextInt();int m=scn.nextInt();int p=scn.nextInt();

        int[] a=new int[n];int[] b=new int[m];

        int i1=-1;int i2=-1;

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

            a[i]=scn.nextInt()%p;

            if(i1==-1&&a[i]!=0){

                i1=i;

            }

        }

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

            b[i]=scn.nextInt()%p;

            if(i2==-1&b[i]!=0){

                i2=i;

            }

        }

        out.print((i1+i2)+"\n");

        out.close();

    }

    // fast input

    static class Scanner {

        public BufferedReader reader;

        public StringTokenizer tokenizer;

        public Scanner(InputStream stream) {

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

            tokenizer = null;

        }

        public String next() {

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

                try {

                    String line = reader.readLine();

                    if (line == null)

                        return null;

                    tokenizer = new StringTokenizer(line);

                } catch (Exception e) {

                    throw(new RuntimeException());

                }

            }

            return tokenizer.nextToken();

        }

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

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

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

    }

    // fast output

    static class OutputWriter {

        BufferedWriter writer;

        public OutputWriter(OutputStream stream) {

            writer = new BufferedWriter(new OutputStreamWriter(stream));

        }

        public void print(int i) throws IOException { writer.write(i); }

        public void print(String s) throws IOException { writer.write(s); }

        public void print(char[] c) throws IOException { writer.write(c); }

        public void close() throws IOException { writer.close(); }

    }

}


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

import java.util.Arrays;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        int t=sc.nextInt();

        while((t--)>0)

        {

            int arr[]=new int[3];

             arr[0]=sc.nextInt();

             arr[1]=sc.nextInt();

             arr[2]=sc.nextInt();

            int x=sc.nextInt();

            Arrays.sort(arr);

            int z=0;

            z=(arr[2]-arr[0]) + (arr[2]-arr[1]);

            if(z>x)

            {

                System.out.println("No");

                continue;

            }

            else

            {

                if((x-z)%3==0)

                {

                    System.out.println("Yes");

                }

                else System.out.println("No");

            }

        }

    }

}


A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

import java.io.*;

import java.util.*;

import static java.lang.Math.*;

import static java.util.Arrays.*;

public class cf1310a_2 {

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

        int n = ri(), at[][] = new int[n][2];

        r();

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

            at[i][0] = ni();

        }

        r();

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

            at[i][1] = ni();

        }

        sort(at, (p, q) -> p[0] - q[0]);

        PriorityQueue<Integer> pq = new PriorityQueue<>((p, q) -> q - p);

        int ind = 0, cur = -1;

        long sum = 0, ans = 0;

        while(ind < n || !pq.isEmpty()) {

            if(pq.isEmpty()) {

                cur = at[ind][0];

            }

            while(ind < n && at[ind][0] == cur) {

                sum += at[ind][1];

                pq.offer(at[ind][1]);

                ++ind;

            }

            sum -= pq.poll();

            ans += sum;

            ++cur;

        }

        prln(ans);

        close();

    }

    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 ~= 2e10

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

    static long hash(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(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 rsort(int[] a) {shuffle(a); sort(a);}

    static void rsort(long[] 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 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 int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;}

    static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;}

    static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;}

    static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;}

    // graph util

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

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

    static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);}

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

    static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);}

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

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

    static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);}

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

    static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);}

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

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

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

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

    // input

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

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

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

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

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

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

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

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

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

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

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

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

    // output

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}


F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3
6 2 4
OutputCopy0
InputCopy5
9 8 7 3 1
OutputCopy4
NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations:  Add 11 to the second element, making it equal to 99.  Subtract 11 from the third element, making it equal to 66.  Add 11 to the fifth element, making it equal to 22.  Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;

public class C1305F {
    public static void main(String[] args) {
        var scanner = new BufferedScanner();
        var writer = new PrintWriter(new BufferedOutputStream(System.out));

        var n = scanner.nextInt();
        var a = new long[n];
        for (int i = 0; i < a.length; i++) {
            a[i] = scanner.nextLong();
        }
        var distinct = Arrays.stream(a).boxed().collect(Collectors.toList());
        Collections.shuffle(distinct);
        var ans = countOps(2, a, n);
        for (int guess = 0; guess < 20 && guess < distinct.size(); guess++) {
            for (int j = -1; j <= 1; j++) {
                var factors = factor(distinct.get(guess) + j);
                for (var factor : factors) {
                    var ops = countOps(factor, a, ans);
                    ans = Math.min(ans, ops);
                }
            }
        }
        writer.println(ans);

        scanner.close();
        writer.flush();
        writer.close();
    }

    private static long countOps(long factor, long[] a, long already) {
        var ans = 0L;
        for (var x : a) {
            if (x < factor) {
                ans += factor - x;
            } else {
                var remain = x % factor;
                ans += Math.min(remain, factor - remain);
//                if (remain < factor / 2) {
//                    ans += remain;
//                } else {
//                    ans += factor - remain;
//                }
            }
            if (ans >= already) {
                break;
            }
        }
        return ans;
    }

    private static List<Long> factor(long a) {
        if (a <= 1) {
            return List.of();
        }
        var limit = (long) Math.sqrt(a);
        var ans = new ArrayList<Long>();
        for (long i = 2; i <= limit; i++) {
            var count = 0;
            while (a % i == 0) {
                a /= i;
                count++;
            }
            if (count > 0) {
                ans.add(i);
            }
        }
        if (a > 1) {
            ans.add(a);
        }
        return ans;
    }

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

        public BufferedScanner(Reader reader) {
            br = new BufferedReader(reader);
        }

        public BufferedScanner() {
            this(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;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    static long gcd(long a, long b) {
        if (a < b) {
            return gcd(b, a);
        }
        while (b > 0) {
            long tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }

    static long inverse(long a, long m) {
        long[] ans = extgcd(a, m);
        return ans[0] == 1 ? (ans[1] + m) % m : -1;
    }

    private static long[] extgcd(long a, long m) {
        if (m == 0) {
            return new long[]{a, 1, 0};
        } else {
            long[] ans = extgcd(m, a % m);
            long tmp = ans[1];
            ans[1] = ans[2];
            ans[2] = tmp;
            ans[2] -= ans[1] * (a / m);
            return ans;
        }
    }

    private static List<Integer> primes(double upperBound) {
        var limit = (int) Math.sqrt(upperBound);
        var isComposite = new boolean[limit + 1];
        var primes = new ArrayList<Integer>();
        for (int i = 2; i <= limit; i++) {
            if (isComposite[i]) {
                continue;
            }
            primes.add(i);
            int j = i + i;
            while (j <= limit) {
                isComposite[j] = true;
                j += i;
            }
        }
        return primes;
    }

}


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

import java.util.StringTokenizer;

/**

 * * @author zhengnaishan

 * * @date 2022/10/13 9:44

 */

public class CF1286 {

    public static void main(String[] args) {

        Kattio io = new Kattio();

        int n = io.nextInt();

        int[] a = new int[n];

        int j = (n + 1) / 2, o = n / 2;//表示奇数个数，偶数个数

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

            a[i] = io.nextInt();

            if (a[i] != 0) {

                if (a[i] % 2 == 0) {

                    o--;

                } else {

                    j--;

                }

            }

        }

        int[][][] f = new int[2][j + 1][o + 1];//当前面的数是奇数/偶数时， 使用j个奇数/k个偶数最少不同对

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

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

                for (int m = 0; m <= o; m++) f[i][l][m] = Integer.MAX_VALUE;

            }

        }

        f[0][0][0] = f[1][0][0] = 0;

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

            int ai = a[i];

            int[][][] nf = new int[2][j + 1][o + 1];

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

                for (int m = o; m >= 0; m--) {//前面用了 l个奇数  m个偶数

                    nf[0][l][m] = nf[1][l][m] = Integer.MAX_VALUE;

                    if (f[0][l][m] != Integer.MAX_VALUE) {//前面一个数是奇数

                        if (a[i] != 0 && a[i] % 2 == 0) {//当前是偶数

                            nf[1][l][m] = Math.min(nf[1][l][m], f[0][l][m] + 1);

                        } else if (a[i] != 0 && a[i] % 2 == 1) {//当前数是奇数

                            nf[0][l][m] = Math.min(nf[0][l][m], f[0][l][m]);

                        }

                        if (ai == 0 && l < j) {//当前数置为奇数

                            nf[0][l + 1][m] = Math.min(nf[0][l + 1][m], f[0][l][m]);

                        }

                        if (ai == 0 && m < o) {//当前数置为偶数

                            nf[1][l][m + 1] = Math.min(nf[1][l][m + 1], f[0][l][m] + 1);

                        }

                    }

                    if (f[1][l][m] != Integer.MAX_VALUE) {//前面一个数是偶数

                        if (a[i] != 0 && ai % 2 == 0) {//当前是偶数

                            nf[1][l][m] = Math.min(nf[1][l][m], f[1][l][m]);

                        } else if (ai != 0 && ai % 2 == 1) {//当前是奇数

                            nf[0][l][m] = Math.min(nf[0][l][m], f[1][l][m] + 1);

                        }

                        if (ai == 0 && l < j) {//将当前数置为奇数

                            nf[0][l + 1][m] = Math.min(nf[0][l + 1][m], f[1][l][m] + 1);

                        }

                        if (ai == 0 && m < o) {//将当前数置为偶数

                            nf[1][l][m + 1] = Math.min(nf[1][l][m + 1], f[1][l][m]);

                        }

                    }

                }

            }

            f = nf;

        }

        int ans = Integer.MAX_VALUE;

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

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

                ans = Math.min(ans, f[0][i][l]);

                ans = Math.min(ans, f[1][i][l]);

            }

        }

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

        }

    }

}


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

import java.io.*;

import java.util.*;

/*

                                                                                (36210193, 61984219)

*/

public class B {

	static FastReader sc=null;

	public static void main(String[] args) {

		sc=new FastReader();

		int t=sc.nextInt();

		while(t-->0) {

			long a=sc.nextLong(),m=sc.nextLong();

			m/=gcd(a,m);

			System.out.println(phi(m));

		}

	}

	static long phi(long n) {

	    long result = n;

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

	        if (n % i == 0) {

	            while (n % i == 0)

	                n /= i;

	            result -= result / i;

	        }

	    }

	    if (n > 1)

	        result -= result / n;

	    return result;

	}

	static int[] reverseSort(int a[]) {

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

		for(int i:a)al.add(i);

		Collections.sort(al,Collections.reverseOrder());

		for(int i=0;i<a.length;i++)a[i]=al.get(i);

		return a;

	}

	static int[] reverse(int a[]) {

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

		for(int i:a)al.add(i);

		Collections.reverse(al);

		for(int i=0;i<a.length;i++)a[i]=al.get(i);

		return a;

	}

	static char[] reverse(char a[]) {

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

		for(char i:a)al.add(i);

		Collections.reverse(al);

		for(int i=0;i<a.length;i++)a[i]=al.get(i);

		return a;

	}

	static int gcd(int a,int b) {

		if(b==0)return a;

		else return gcd(b,a%b);

	}

	static long gcd(long a,long b) {

		if(b==0)return a;

		else return gcd(b,a%b);

	}

	static int[] ruffleSort(int a[]) {

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

		for(int i:a)al.add(i);

		Collections.sort(al);

		for(int i=0;i<a.length;i++)a[i]=al.get(i);

		return a;

	}

	static void print(int a[]) {

		for(int e:a) {

			System.out.print(e+" ");

		}

		System.out.println();

	}

	static void print(boolean a[]) {

		for(boolean e:a) {

			System.out.print(e+" ");

		}

		System.out.println();

	}

	static void print(long a[]) {

		for(long e:a) {

			System.out.print(e+" ");

		}

		System.out.println();

	}

	static void print(char a[]) {

		for(char e:a) {

			System.out.print(e);

		}

		System.out.println();

	}

	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[] readArray(int n) {

    		int a[]=new int [n];

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

    			a[i]=sc.nextInt();

    		}

    		return a;

    	}

    }

}