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

import java.util.*;

import java.io.*;

public class File {

	public static class FastScanner {

		BufferedReader br;

		StringTokenizer st;

		public FastScanner() {

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

		}

	}

	public static void main(String[] args) {

		FastScanner sc = new FastScanner();

		PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

		int test=sc.nextInt();

		while(test>0)

		{

		    int n=sc.nextInt();

		    String s=sc.next();

		    String ans="";

		    int a=0;

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

		    {

		        StringBuilder temp=new StringBuilder();

		        temp.append(s.substring(i-1));

		        StringBuilder add=new StringBuilder();

		        add.append(s.substring(0,i-1));

		        if(temp.length()%2!=0)add.reverse();

		        temp.append(add);

		        if(ans=="" || ans.compareTo(temp.toString())>0)

		        {

		           ans=temp.toString();

		           a=i;

		        }

		    }

		    out.println(ans);

		    out.println(a);

		    test--;

		}

		out.close();

	}

}


C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb
OutputCopy6
InputCopyusaco
OutputCopy1
InputCopylol
OutputCopy2
NoteIn the first example; these are all the hidden strings and their indice sets:   a occurs at (1)(1), (2)(2), (3)(3)  b occurs at (4)(4), (5)(5)  ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5)  aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3)  bb occurs at (4,5)(4,5)  aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4)  aaa occurs at (1,2,3)(1,2,3)  abb occurs at (3,4,5)(3,4,5)  aaab occurs at (1,2,3,4)(1,2,3,4)  aabb occurs at (2,3,4,5)(2,3,4,5)  aaabb occurs at (1,2,3,4,5)(1,2,3,4,5)  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

import java.util.*;

public class C1307 {

    public static void main(String[] args) {

        Scanner scn = new Scanner(System.in);

        String s = scn.next();

        long[] dp1 = new long[26]; // for 1 length

        long[][] dp2 = new long[26][26]; // for 2 length

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

            int asc = s.charAt(i)-'a';

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

                dp2[j][asc]+=dp1[j]; // no of times j+asc will occur

            }

            dp1[asc]++;

        }

        long max = 0;

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

            max = Math.max(max,dp1[i]);

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

                max = Math.max(max,dp2[i][j]);

            }

        }

        System.out.println(max);

    }

}


F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3
13 35 77
OutputCopy1001InputCopy6
1 2 4 8 16 32
OutputCopy32

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Stack;

public class Solution {

    static ArrayList<Integer>[] pfactors, factors;

    static int sieve[];

    static int count[];

    static long ans;

    static long gcd(long a, long b) {

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

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

        long z = gcd(a, b);

        ans = Math.max(ans, ((a * b) / z) * g);

        if (z == 1)

            return 1;

        return 0;

    }

    static int get(int x) {

        int val = 0;

        int l = pfactors[x].size();

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

            int p = 1, c = 0;

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

                if ((i & (1 << j)) > 0) {

                    p = p * pfactors[x].get(j);

                    c++;

                }

            }

            if (c % 2 == 0)

                val = val + count[p];

            else

                val = val - count[p];

        }

        return val;

    }

    static void add(int x, int v) {

        for (int z : factors[x]) {

            count[z] += v;

        }

    }

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

        FastReader in = new FastReader(System.in);

        int i, j, MN = 100000;

        sieve = new int[MN + 1];

        pfactors = new ArrayList[MN + 1];

        factors = new ArrayList[MN + 1];

        for (i = 1; i <= MN; i++) {

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

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

        }

        sieve[1] = 1;

        for (i = 1; i <= MN; i++) {

            if (sieve[i] == 0) {

                for (j = i; j <= MN; j += i) {

                    sieve[j] = i;

                    factors[j].add(i);

                }

            } else {

                for (j = i; j <= MN; j += i) {

                    factors[j].add(i);

                }

            }

        }

        for (i = 2; i <= MN; i++) {

            int temp = i;

            while (temp != 1) {

                int x = sieve[temp];

                pfactors[i].add(x);

                while (temp % x == 0)

                    temp = temp / x;

            }

        }

        boolean pre[] = new boolean[MN + 1];

        ans = 0;

        int n = in.nextInt();

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

            int x = in.nextInt();

            ans = Math.max(ans, x);

            pre[x] = true;

        }

        count = new int[MN + 1];

        for (int gcd = 1; gcd <= MN; gcd++) {

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

            for (j = gcd; j <= MN; j += gcd) {

                if (pre[j]) {

                    list.add(j / gcd);

                }

            }

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

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

            for (int x : list) {

                int z = get(x);

                if (z == 0) {

                    st.add(x);

                    add(x, 1);

                } else {

                    while (z != 0) {

                        int y = st.pop();

                        z -= lcm(x, y, gcd);

                        add(y, -1);

                    }

                }

            }

            while (!st.isEmpty()) {

                add(st.pop(), -1);

            }

        }

        System.out.println(ans);

    }

}

class FastReader {

    byte[] buf = new byte[2048];

    int index, total;

    InputStream in;

    FastReader(InputStream is) {

        in = is;

    }

    int scan() throws IOException {

        if (index >= total) {

            index = 0;

            total = in.read(buf);

            if (total <= 0) {

                return -1;

            }

        }

        return buf[index++];

    }

    String next() throws IOException {

        int c;

        for (c = scan(); c <= 32; c = scan()) ;

        StringBuilder sb = new StringBuilder();

        for (; c > 32; c = scan()) {

            sb.append((char) c);

        }

        return sb.toString();

    }

    int nextInt() throws IOException {

        int c, val = 0;

        for (c = scan(); c <= 32; c = scan()) ;

        boolean neg = c == '-';

        if (c == '-' || c == '+') {

            c = scan();

        }

        for (; c >= '0' && c <= '9'; c = scan()) {

            val = (val << 3) + (val << 1) + (c & 15);

        }

        return neg ? -val : val;

    }

    long nextLong() throws IOException {

        int c;

        long val = 0;

        for (c = scan(); c <= 32; c = scan()) ;

        boolean neg = c == '-';

        if (c == '-' || c == '+') {

            c = scan();

        }

        for (; c >= '0' && c <= '9'; c = scan()) {

            val = (val << 3) + (val << 1) + (c & 15);

        }

        return neg ? -val : val;

    }

}


B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2
3
3 2 1
6
3 1 4 1 5 9
OutputCopy3
5
NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].

import java.util.Arrays;

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        while (t-- > 0) {

            int n = sc.nextInt();

            int[] a = new int[n];

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

                a[i] = sc.nextInt();

            }

            Arrays.sort(a);

            int count = 0;

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

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

                    count++;

                }

            }

            System.out.println(n - count);

        }

    }

}


A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
OutputCopy8
4
1
1
NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element.  the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8];  the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8];  if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element);  if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.

import java.util.*;
import java.lang.*;
import java.io.*;

// Created by @thesupremeone on 16/07/21
public class MindControl {
    int getMin(int[] arr, int m){
        int min = Integer.MAX_VALUE;
        for (int x = 0; x <= m-1; x++) {
            int y = arr.length-(m-1-x)-1;
            min = Math.min(min, Math.max(arr[x], arr[y]));
        }
        return min;
    }
    void solve() throws IOException {
        int ts = getInt();
        for (int t = 1; t <= ts; t++){
            int n = getInt();
            int m = getInt();
            int k = getInt();
            int[] a = new int[n];
            for (int i = 0; i < n; i++){
                a[i] = getInt();
            }
            int max = Integer.MIN_VALUE;
            if(k<m-1){
                for (int x = 0; x <= k; x++) {
                    int y = k-x;
                    int[] arr = new int[n-k];
                    for (int i = x; i < n-y; i++)
                        arr[i-x] = a[i];
                    int min = getMin(arr, m-k);
                    max = Math.max(max, min);
                }
            }else {
                for (int i = 0; i < m; i++) {
                    max = Math.max(max, a[i]);
                    max = Math.max(max, a[n-1-i]);
                }
            }
            println(max);
        }
    }

    public static void main(String[] args) throws Exception {
        if (isOnlineJudge()) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new BufferedWriter(new OutputStreamWriter(System.out));
            new MindControl().solve();
            out.flush();
        } else {
            localJudge = new Thread();
            in = new BufferedReader(new FileReader("input.txt"));
            out = new BufferedWriter(new FileWriter("output.txt"));
            localJudge.start();
            new MindControl().solve();
            out.flush();
            localJudge.suspend();
        }
    }
    static boolean isOnlineJudge(){
        try {
            return System.getProperty("ONLINE_JUDGE")!=null
                    || System.getProperty("LOCAL")==null;
        }catch (Exception e){
            return true;
        }
    }
    // Fast Input & Output
    static Thread localJudge = null;
    static BufferedReader in;
    static StringTokenizer st;
    static BufferedWriter out;
    static String getLine() throws IOException{
        return in.readLine();
    }
    static String getToken() throws IOException{
        if(st==null || !st.hasMoreTokens())
            st = new StringTokenizer(getLine());
        return st.nextToken();
    }
    static int getInt() throws IOException {
        return Integer.parseInt(getToken());
    }
    static long getLong() throws IOException {
        return Long.parseLong(getToken());
    }
    static void print(Object s) throws IOException{
        out.write(String.valueOf(s));
    }
    static void println(Object s) throws IOException{
        out.write(String.valueOf(s));
        out.newLine();
    }
}


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

import java.util.*;

import java.io.*;

public class A_Game_23

{

static long mod = 1000000007;

public static void main(String[] args) {

var sc = new Kattio(System.in, System.out);

int t=1;

// t = sc.nextInt();

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

sc.close();

}

public static void solve(Kattio sc) {

        int n = sc.nextInt();

        int m = sc.nextInt();

        if(m%n!=0) {sc.println(-1);return;}

        int d = m/n;

        int count=0;

        while(d!=1){

            if(d%2!=0 && d%3!=0){

                sc.println(-1);

                return;

            }

            if(d%2==0) {d/=2;count++;}

            if(d%3==0){

                d/=3;

                count++;

            }

        }

        sc.println(count);

    }

}

class Kattio extends PrintWriter {

    public Kattio(InputStream i) {

        super(new BufferedOutputStream(System.out));

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

    }

    public Kattio(InputStream i, OutputStream o) {

        super(new BufferedOutputStream(o));

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

    }

    public boolean hasMoreTokens() {

        return peekToken() != null;

    }

    public int nextInt() {

        return Integer.parseInt(nextToken());

    }

    public double nextDouble() {

        return Double.parseDouble(nextToken());

    }

    public long nextLong() {

        return Long.parseLong(nextToken());

    }

    public String next() {

        return nextToken();

    }

    private BufferedReader r;

    private String line;

    private StringTokenizer st;

    private String token;

    private String peekToken() {

        if (token == null)

            try {

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

                    line = r.readLine();

                    if (line == null) return null;

                    st = new StringTokenizer(line);

                }

                token = st.nextToken();

            } catch (IOException e) { }

        return token;

    }

    private String nextToken() {

        String ans = peekToken();

        token = null;

        return ans;

    }

}


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

import java.util.*;

/*

Прокрастинирую

*/

public class Main {

    static FastReader in;

    static PrintWriter out;

    static Random rand = new Random();

    static final int INF = (int) (1e9 + 10);

    static final int MOD = (int) (1e9 + 7);

    static final int N = (int) (1e6 + 6);

    static final int LOGN = 62;

    static int n, m, p;

    static int[][] a, b;

    static class Monster {

        int x, y, z;

        Monster(int x, int y, int z) {

            this.x = x;

            this.y = y;

            this.z = z;

        }

    }

    static class SegTree {

        int size;

        long[] t_max, t_add;

        SegTree(long[] arr) {

            size = arr.length;

            t_max = new long[size * 4];

            t_add = new long[size * 4];

            build(arr);

        }

        void push(int v) {

            if (t_add[v] != 0) {

                t_max[v * 2 + 1] += t_add[v];

                t_add[v * 2 + 1] += t_add[v];

                t_max[v * 2 + 2] += t_add[v];

                t_add[v * 2 + 2] += t_add[v];

                t_add[v] = 0;

            }

        }

        void pull(int v) {

            t_max[v] = Math.max(t_max[v * 2 + 1], t_max[v * 2 + 2]);

        }

        void build(int v, int tl, int tr, long[] arr) {

            if (tl == tr) {

                t_max[v] = arr[tl];

                return;

            }

            int tm = (tl + tr) / 2;

            build(v * 2 + 1, tl, tm, arr);

            build(v * 2 + 2, tm + 1, tr, arr);

            pull(v);

        }

        void build(long[] arr) {

            build(0, 0, size - 1, arr);

        }

        long maxOn(int v, int tl, int tr, int l, int r) {

            if (l > tr || r < tl) return -INF;

            if (l <= tl && tr <= r) {

                return t_max[v];

            }

            push(v);

            int tm = (tl + tr) / 2;

            return Math.max(maxOn(v * 2 + 1, tl, tm, l, r),

                    maxOn(v * 2 + 2, tm + 1, tr, l, r));

        }

        long maxOn(int l, int r) {

            return maxOn(0, 0, size - 1, l, r);

        }

        void addOn(int v, int tl, int tr, int l, int r, int val) {

            if (l > tr || r < tl)return;

            if (l <= tl && tr <= r) {

                t_max[v] += val;

                t_add[v] += val;

                return;

            }

            push(v);

            int tm = (tl + tr) / 2;

            addOn(v * 2 + 1, tl, tm, l, r, val);

            addOn(v * 2 + 2, tm + 1, tr, l, r, val);

            pull(v);

        }

        void addOn(int l, int r, int val) {

            addOn(0, 0, size - 1, l, r, val);

        }

    }

    static int upperBound(int[][] arr, int x) {

        int lb = 0, rb = arr.length;

        while (lb < rb) {

            int mb = (lb + rb) / 2;

            if (arr[mb][0] <= x) {

                lb = mb + 1;

            } else {

                rb = mb;

            }

        }

        return lb;

    }

    static void solve() {

        n = in.nextInt();

        m = in.nextInt();

        p = in.nextInt();

        a = new int[n][2];

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

            a[i][0] = in.nextInt();

            a[i][1] = in.nextInt();

        }

        Arrays.sort(a, (a1, a2) -> Integer.compare(a1[0], a2[0]));

        b = new int[m][2];

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

            b[i][0] = in.nextInt();

            b[i][1] = in.nextInt();

        }

        Arrays.sort(b, (b1, b2) -> Integer.compare(b1[0], b2[0]));

        long[] arr = new long[m];

        for (int i = 0; i < m; i++) arr[i] = -b[i][1];

        SegTree st = new SegTree(arr);

        Monster[] monsters = new Monster[p];

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

            monsters[i] = new Monster(in.nextInt(), in.nextInt(), in.nextInt());

        }

        Arrays.sort(monsters, (m1, m2) -> Integer.compare(m1.x, m2.x));

        long ans = 10L * -INF;

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

            while (j < p && monsters[j].x < a[i][0]) {

                st.addOn(upperBound(b, monsters[j].y), m - 1, monsters[j].z);

                j++;

            }

            ans = Math.max(ans, st.maxOn(0, m - 1) - a[i][1]);

        }

        out.println(ans);

    }

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

        in = new FastReader(System.in);

//        in = new FastReader(new FileInputStream("connect.in"));

        out = new PrintWriter(System.out);

//        out = new PrintWriter(new FileOutputStream("connect.out"));

        int q = 1;

//        q = in.nextInt();

        while (q-- > 0) {

            solve();

        }

        out.close();

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        FastReader(InputStream is) {

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

        }

        Integer nextInt() {

            return Integer.parseInt(next());

        }

        Long nextLong() {

            return Long.parseLong(next());

        }

        Double nextDouble() {

            return Double.parseDouble(next());

        }

        String next() {

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

                st = new StringTokenizer(nextLine());

            }

            return st.nextToken();

        }

        String nextLine() {

            String s = "";

            try {

                s = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return s;

        }

    }

}


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;

		}

	}

}


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

            }

        }

    }

}