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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.*;

import static java.lang.Double.parseDouble;

import static java.lang.Integer.parseInt;

import static java.lang.Long.parseLong;

import static java.lang.System.in;

import static java.lang.System.out;

public class SolutionE extends Thread {

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(new

                                            InputStreamReader(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 parseInt(next());

        }

        long nextLong() {

            return parseLong(next());

        }

        double nextDouble() {

            return parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    private static final FastReader scanner = new FastReader();

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

    public static void main(String[] args) {

        new Thread(null, new SolutionE(), "Main", 1 << 28).start();

    }

    public void run() {

        solve();

        out.close();

    }

    private static void solve() {

        int n = scanner.nextInt();

        int[] a = new int[n];

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

            a[i] = scanner.nextInt();

        }

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

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

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

                if (l + size > n) {

                    break;

                }

                int r = l + size;

                dp[l][r] = -1;

                if (size == 1) {

                    dp[l][r] = a[l];

                    continue;

                }

                for (int j = l+1; j < r; j++) {

                    if (dp[l][j] == dp[j][r] && dp[l][j] != -1) {

                        dp[l][r] = dp[l][j] + 1;

                    }

                }

            }

        }

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

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

            int minValue = 2000;

            if (dp[0][i] != -1) {

                minValue = 1;

            }

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

                if (dp[j][i] != -1) {

                    int value = 1 + dp2[j];

                    minValue = Math.min(minValue, value);

                }

            }

            dp2[i] = minValue;

        }

        out.println(dp2[n]);

    }

}


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

// package c1324;

//
// Codeforces Round #627 (Div. 3) 2020-03-12 05:05
// E. Sleeping Schedule
// https://codeforces.com/contest/1324/problem/E
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n
// times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can
// assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each
// time Vova sleeps (in other words, h hours).
//
// Vova thinks that the i-th sleeping time is if he starts to sleep between hours l and r inclusive.
//
// Vova can control himself and before the i-th time can choose between two options: go to sleep
// after a_i hours or after a_i - 1 hours.
//
// Your task is to say the maximum number of sleeping times Vova can obtain if he acts optimally.
//
// Input
//
// The first line of the input contains four integers n, h, l and r (1 <= n <= 2000, 3 <= h <= 2000,
// 0 <= l <= r < h) -- the number of times Vova goes to sleep, the number of hours in a day and the
// segment of the sleeping time.
//
// The second line of the input contains n integers a_1, a_2, ..., a_n (1 <= a_i < h), where a_i is
// the number of hours after which Vova goes to sleep the i-th time.
//
// Output
//
// Print one integer -- the maximum number of sleeping times Vova can obtain if he acts optimally.
//
// Example
/*
input:
7 24 21 23
16 17 14 20 20 11 22
output:
3
*/
// Note
//
// The maximum number of times in the example is 3.
//
// The story starts from t=0. Then Vova goes to sleep after a_1 - 1 hours, now the time is 15. This
// time is not good. Then Vova goes to sleep after a_2 - 1 hours, now the time is 15 + 16 = 7. This
// time is also not good. Then Vova goes to sleep after a_3 hours, now the time is 7 + 14 = 21. This
// time is . Then Vova goes to sleep after a_4 - 1 hours, now the time is 21 + 19 = 16. This time is
// not good. Then Vova goes to sleep after a_5 hours, now the time is 16 + 20 = 12. This time is not
// good. Then Vova goes to sleep after a_6 hours, now the time is 12 + 11 = 23. This time is . Then
// Vova goes to sleep after a_7 hours, now the time is 23 + 22 = 21. This time is also .
//

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;

public class C1324E {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  static int solve(int[] a, int h, int l, int r) {
    int n = a.length;

    // dp[i][j] is the maximal number of good sleeping in suffix days i
    // when woke up at hour j
    int[][] dp = new int[n][h];
    for (int i = n-1; i >= 0; i--) {
      int v = a[i];
      for (int j = 0; j < h; j++) {
        // if sleep v hours
        {
          int hour = (j + v) % h;
          int w = (hour >= l && hour <= r ? 1 : 0) + (i == n - 1 ? 0 : dp[i+1][hour]);
          dp[i][j] = w;
        }
        // if sleep v - 1 hours
        {
          int hour = (j + v + h - 1) % h;
          int w = (hour >= l && hour <= r ? 1 : 0) + (i == n - 1 ? 0 : dp[i+1][hour]);
          dp[i][j] = Math.max(dp[i][j], w);
        }
      }
    }
    int ans = 0;
    for (int j = 0; j < h; j++) {
      ans = Math.max(ans, dp[0][j]);
    }
    return dp[0][0];
  }

  static String trace(int[][] a) {
    return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
  }

  static String trace(int[] a) {
    return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
  }

  static boolean test = false;
  static void doTest() {
    if (!test) {
      return;
    }
    long t0 = System.currentTimeMillis();
    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    doTest();
    MyScanner in = new MyScanner();
    int n = in.nextInt();
    int h = in.nextInt();
    int l = in.nextInt();
    int r = in.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = in.nextInt();
    }
    int ans = solve(a, h, l, r);
    System.out.println(ans);
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
      sb.append(v);
      sb.append(' ');
      if (sb.length() > 4000) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }

  static class MyScanner {
    BufferedReader br;
    StringTokenizer st;

    public MyScanner() {
      try {
        final String USERDIR = System.getProperty("user.dir");
        String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
        cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
        final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
        br = new BufferedReader(new InputStreamReader(fin.exists()
            ? new FileInputStream(fin) : System.in));
      } catch (Exception e) {
        br = new BufferedReader(new InputStreamReader(System.in));
      }
    }

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

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

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


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

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String s = input.nextLine();

        int[][] count = new int[s.length() + 1][26];

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

            count[i + 1] = count[i].clone();

            count[i + 1][s.charAt(i) - 'a'] += 1;

        }

        int q = input.nextInt();

        while (q-- != 0) {

            int l = input.nextInt() - 1, r = input.nextInt() - 1;

            int distinct = 0;

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

                distinct += (count[r + 1][i] != count[l][i] ? 1 : 0);

            }

            if (l != r && s.charAt(l) == s.charAt(r) && distinct < 3) {

                System.out.println("No");

            } else {

                System.out.println("Yes");

            }

        }

    }

}


D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
OutputCopy2
-1
0

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

    static long n;

    static int m;

    static int[] a, map, v, needs;

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

        Reader input = new Reader();

        StringBuilder output = new StringBuilder();

        int t = input.nextInt();

        while(t > 0) {

            n = input.nextLong();

            m = input.nextInt();

            a = new int[m];

            for(int i = 0; i < m; ++i) a[i] = input.nextInt();

            long sum = 0;

            for(int i = 0; i < m; ++i) sum += (long)a[i];

            if(sum < n) {

                output.append(-1);

            } else {

                output.append(solve());

            }

            --t;

            output.append("\n");

        }

        System.out.print(output);

    }

    static long solve() {

        map = new int[30];

        v = new int[30];

        v[0] = 1;

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

            v[i] = v[i-1]*2;

        }

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

            int left = 0, right = 30, middle;

            while(left < right) {

                middle = left+right>>1;

                if(v[middle] == a[i]) {

                    ++map[middle];

                    break;

                } else if(v[middle] > a[i]) {

                    right = middle;

                } else {

                    left = middle+1;

                }

            }

        }

        needs = new int[30];

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

            needs[i] = (int)(n/v[i]);

            n -= (n/v[i])*(long)v[i];

        }

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

            if(map[i] >= needs[i]) {

                map[i] -= needs[i];

                needs[i] = 0;

            } else {

                needs[i] -= map[i];

                map[i] = 0;

            }

        }

        long count = 0;

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

            if(map[i] >= needs[i]) {

                map[i] -= needs[i];

                needs[i] = 0;

                if(i+1 < 30) {

                    int temp = map[i]/2;

                    map[i+1] += temp;

                    map[i] -= temp*2;

                }

            } else {

                needs[i] -= map[i];

                map[i] = 0;

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

                    if(map[j] > needs[j]) {

                        for(int k = j-1; k >= i; --k) {

                            ++map[k];

                            ++count;

                        }

                        ++map[i];

                        --map[j];

                        break;

                    }

                }

                --i;

            }

        }

        return count;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

    static int n;

    static int[] a;

    static Integer[][][][] memo;

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

        Reader input = new Reader();

        n = input.nextInt();

        a = new int[n];

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

            a[i] = input.nextInt();

        }

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

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

            used[a[i]] = true;

        }

        int evens = 0, odds = 0;

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

            if(!used[i]) {

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

                else ++odds;

            }

        }

        memo = new Integer[n][evens+1][odds+1][2];

        System.out.println(solve(0, evens, odds, 0));

    }

    static int solve(int p, int evens, int odds, int prevParty) {

        if(p >= n) {

            return 0;

        }

        if(memo[p][evens][odds][prevParty] != null) {

            return memo[p][evens][odds][prevParty];

        }

        int answer = n+1;

        if(a[p] != 0) {

            answer = p == 0 ? 0 : (a[p]%2 == prevParty ? 0 : 1);

            answer += solve(p+1, evens, odds, a[p]%2);

        } else {

            if(evens > 0) {

                int test = p == 0 ? 0 : (prevParty == 0 ? 0 : 1);

                test += solve(p+1, evens-1, odds, 0);

                answer = Math.min(test, answer);

            }

            if(odds > 0) {

                int test = p == 0 ? 0 : (prevParty == 0 ? 1 : 0);

                test += solve(p+1, evens, odds-1, 1);

                answer = Math.min(test, answer);

            }

        }

        memo[p][evens][odds][prevParty] = answer;

        return answer;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int t=1;

//		t=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

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

			int n=f.nextInt();

			char[] s=f.next().toCharArray();

			int[] dp=new int[26];

			int[] ans=new int[n];

			int a1=0;

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

				int cd=1;

				for(int j=0; j<s[i]-'a'; ++j)

					cd=Math.max(cd, dp[j]+1);

				a1=Math.max(cd, a1);

				ans[i]=cd;

				dp[s[i]-'a']=cd;

			}

			System.out.println(a1);;

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

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

			System.out.println();

		}

		out.close();

	}

	static void sort(int[] p) {

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

        for (int i: p) q.add( i);

        Collections.sort(q);

        for (int i = 0; i < p.length; i++) p[i] = q.get(i);

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}

//Some things to notice

//Check for the overflow

//Binary Search

//Bitmask

//runtime error most of the time is due to array index out of range


B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3
SET
ETS
TSE
OutputCopy1InputCopy3 4
SETE
ETSE
TSES
OutputCopy0InputCopy5 4
SETT
TEST
EEET
ESTE
STES
OutputCopy2NoteIn the third example test; these two triples of cards are sets:  "SETT"; "TEST"; "EEET"  "TEST"; "ESTE", "STES"

import java.io.*;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashSet;

import java.util.StringTokenizer;

public class Hyperset {

    static int mod = 1000000007;

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

        FastReader reader = new FastReader();

        FastWriter writer = new FastWriter();

        int[] nk = reader.readIntArray(2);

        int n = nk[0], k = nk[1];

        String[] cards = new String[n];

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

            cards[i] = reader.readString();

        }

        int triple = 0;

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

            HashSet<String> seen = new HashSet<>();

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

                StringBuilder b = new StringBuilder("");

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

                    if(cards[i].charAt(m) == cards[j].charAt(m)) {

                        b.append(cards[i].charAt(m));

                    } else {

                        if(cards[i].charAt(m) != 'S' && cards[j].charAt(m) != 'S'){

                            b.append('S');

                        } else if(cards[i].charAt(m) != 'E' && cards[j].charAt(m) != 'E'){

                            b.append('E');

                        } else {

                            b.append('T');

                        }

                    }

                }

                if(seen.contains(b.toString())) triple++;

                seen.add(cards[j]);

            }

        }

        writer.writeSingleInteger(triple);

    }

    public static void mergeSort(int[] a, int n) {

        if (n < 2) {

            return;

        }

        int mid = n / 2;

        int[] l = new int[mid];

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

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

            l[i] = a[i];

        }

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

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

        }

        mergeSort(l, mid);

        mergeSort(r, n - mid);

        merge(a, l, r, mid, n - mid);

    }

    public static void merge(int[] a, int[] l, int[] r, int left, int right) {

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

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

            if (l[i] <= r[j]) {

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

            }

            else {

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

            }

        }

        while (i < left) {

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

        }

        while (j < right) {

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

        }

    }

    public static class FastReader {

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

        StringTokenizer tokenizer;

        public int readSingleInt() throws IOException {

            return Integer.parseInt(reader.readLine());

        }

        public int[] readIntArray(int numInts) throws IOException {

            int[] nums = new int[numInts];

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

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

                nums[i] = Integer.parseInt(tokenizer.nextToken());

            }

            return nums;

        }

        public String readString() throws IOException {

            return reader.readLine();

        }

    }

    public static class FastWriter {

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

        public void writeSingleInteger(int i) throws IOException {

            writer.write(Integer.toString(i));

            writer.newLine();

            writer.flush();

        }

        public void writeSingleLong(long i) throws IOException {

            writer.write(Long.toString(i));

            writer.newLine();

            writer.flush();

        }

        public void writeIntArrayWithSpaces(int[] nums) throws IOException {

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

                writer.write(nums[i] + " ");

            }

            writer.newLine();

            writer.flush();

        }

        public void writeIntArrayListWithSpaces(ArrayList<Integer> nums) throws IOException {

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

                writer.write(nums.get(i) + " ");

            }

            writer.newLine();

            writer.flush();

        }

        public void writeIntArrayWithoutSpaces(int[] nums) throws IOException {

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

                writer.write(Integer.toString(nums[i]));

            }

            writer.newLine();

            writer.flush();

        }

        public void writeString(String s) throws IOException {

            writer.write(s);

            writer.newLine();

            writer.flush();

        }

    }

}


F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

	import java.io.*;

	import java.util.*;

	public class ProblemD {

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

			Scanner in = new Scanner();

			int n = in.readInt();

			int a[] = new int[n];

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

			int mx = 0;

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

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

				long sum = 0;

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

					sum+=a[j];

					HashMap<Long,Integer>mp = new HashMap<>();

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

					long cur = 0;

					int pos  = 0;

					mp.put(0l, -1);

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

						cur+=a[z];

						if(mp.containsKey(cur-sum)){

							l.add(new Pair(mp.get(cur-sum)+2,z+1));

							mp.clear();

						}

						mp.put(cur, z);

					}

					/*if(sum == 2){

						for(Pair it:l)System.out.println(it.x+" "+it.y+" "+sum);

					}*/

					if(l.size()>mx){

						mx = l.size();

						res = new ArrayList<>(l);

					}

				}

			}

			System.out.println(res.size());

			for(Pair it:res)System.out.println(it.x+" "+it.y);

		}

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

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

		}

		public static long nearest(TreeSet<Long> list,long target){

			long nearest = -1,sofar = Integer.MAX_VALUE;

			for(long it:list){

				if(Math.abs(it - target)<sofar){

					sofar = Math.abs(it - target);

					nearest = it;

				}

			}

			return nearest;

		}

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

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

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

				if(n%i == 0){

					l.add(i);

					if(n/i != i)l.add(n/i);

				}

			}

			Collections.sort(l);

			return l;

		}

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

			int t = a[i];

			a[i] = a[j];

			a[j] = t;

		}

		public static boolean isSorted(long a[]){

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

				if(i+1<a.length && a[i]>a[i+1])return false;

			}

			return true;

		}

		public static int first(ArrayList<Long>list,long target){

			int index = -1;

			int l = 0,r = list.size()-1;

			while(l<=r){

				int mid = (l+r)/2;

				if(list.get(mid) == target){

					index = mid;

					r = mid-1;

				}else if(list.get(mid)>target){

					r  = mid-1;

				}else l  = mid+1;

			}

			return index;

		}

		public static int last(ArrayList<Long>list,long target){

			int index = -1;

			int l = 0,r = list.size()-1;

			while(l<=r){

				int mid = (l+r)/2;

				if(list.get(mid) == target){

					index=  mid;

					l = mid+1;

				}else if(list.get(mid)<target){

					l  = mid+1;

				}else r  = mid-1;

			}

			return index;

		}

		public static void sort(int arr[]){

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

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

			Collections.sort(list);

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

		}

		static class Pair{

			int x,y;

			public Pair(int x,int y){

				this.x = x;

				this.y = y;

			}

		}

		static class Scanner{

			BufferedReader br;

			StringTokenizer st;

			public Scanner(){

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

			}

		    public String read()

		    {

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

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

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

		         }

		         return st.nextToken();

		     }

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

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

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

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

		}

}


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

import java.io.*;

import java.math.*;

import java.util.*;

// @author : Dinosparton

public class test {

	   static class Pair{

		   long x;

		   long y;

		   Pair(long x,long y){

			   this.x = x;

			   this.y = y;

		   }

	   }

	   static class Compare {

		     void compare(Pair arr[], int n)

		    {

		        // Comparator to sort the pair according to second element

		        Arrays.sort(arr, new Comparator<Pair>() {

		            @Override public int compare(Pair p1, Pair p2)

		            {

		            	if(p1.x!=p2.x) {

		                return (int)(p1.x - p2.x);

		            	}

		            	else {

		            		return (int)(p1.y - p2.y);

		            	}

		            }

		        });

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

//		            System.out.print(arr[i].x + " " + arr[i].y + " ");

//		        }

//		        System.out.println();

		    }

		}

	   static class Scanner {

	        BufferedReader br;

	        StringTokenizer st;

	        public Scanner()

	        {

	            br = new BufferedReader(

	                new InputStreamReader(System.in));

	        }

	        String next()

	        {

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

	                try {

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

	                }

	                catch (IOException e) {

	                    e.printStackTrace();

	                }

	            }

	            return st.nextToken();

	        }

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

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

	        double nextDouble()

	        {

	            return Double.parseDouble(next());

	        }

	        String nextLine()

	        {

	            String str = "";

	            try {

	                str = br.readLine();

	            }

	            catch (IOException e) {

	                e.printStackTrace();

	            }

	            return str;

	        }

	    }

	 static int max[] = new int[200005];

	 static int ans[] = new int[200005];

	   static void dfs(int src,int par,ArrayList<Integer> adj[],int a[]) {

		   max[src] = a[src];

		   for(int i : adj[src]) {

			   if(i == par) {

				   continue;

			   }

				   dfs(i,src,adj,a);

				   max[src] += Math.max(0, max[i]);

		   }

	   }

	   static void dfs(int src,int par,ArrayList<Integer> adj[]) {

		   ans[src] = max[src];

		   for(int i : adj[src]) {

			   if(i == par) {

				   continue;

			   }

			   max[src] -= Math.max(0, max[i]);

			   max[i] += Math.max(0, max[src]);

			   dfs(i,src,adj);

			   max[i] -= Math.max(0, max[src]);

			   max[src] += Math.max(0, max[i]);

		   }

	   }

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

		   Scanner sc = new Scanner();

		   StringBuilder res = new StringBuilder();

		   int tc = 1;

		   while(tc-->0) {

			   int n = sc.nextInt();

			   int a[] = new int[n];

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

				   a[i] = sc.nextInt();

				   if(a[i] == 0) {

					   a[i] = -1;

				   }

			   }

			   ArrayList<Integer> adj[] = new ArrayList[n];

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

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

			   }

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

				   int src = sc.nextInt()-1;

				   int dest = sc.nextInt()-1;

				   adj[src].add(dest);

				   adj[dest].add(src);

			   }

			   dfs(0,-1,adj,a);

			   dfs(0,-1,adj);

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

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

			   }

		   }

		   System.out.println(res);

	   }

}


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

import java.util.Scanner;

public class CF1009{

	public static void main(String[] args){

		Scanner scan = new Scanner(System.in);

		int testCases = scan.nextInt();

		while(testCases>0){

			String firstString = scan.next();

			String secondString = scan.next();

			String thirdString = scan.next();

			boolean flag = false;

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

				char a = firstString.charAt(i);

				char b = secondString.charAt(i);

				char c = thirdString.charAt(i);

				if(a != b && b != c && a != c || a == b && c!=b){

					flag = true;

				}

			}

			if(flag){

				System.out.println("NO");

			}else{

				System.out.println("YES");

			}

			testCases--;

		}

	}

}


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

import java.util.Arrays;

import java.util.Scanner;

public class B1311 {

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

	static int t = sc.nextInt();

	static int []a = new int[110];

	static boolean []c = new boolean[110];

	static int []p = new int[110];

	public static void main(String[] args) {

		while((t--) > 0) {

			Arrays.fill(c,false);

			boolean flag = true;

			int n = sc.nextInt();

			int m = sc.nextInt();

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

				a[i] = sc.nextInt();

			}

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

				p[j] = sc.nextInt();

				c[p[j]] = true;

			}

			int k = 0;

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

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

					if(a[j] > a[j + 1]) {

						if(c[j]) {

							k = a[j];

							a[j] = a[j + 1];

							a[j + 1] = k;

						}

						else {

							flag = false;

						}

					}

				}

			}

			if(!flag) {

				System.out.println("NO");

			}else {

				System.out.println("YES");

			}

		}

	}

 }


C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    static int globalVariable = 123456789;
    static String author = "pl728 on codeforces";

    public static void main(String[] args) {
        FastReader sc = new FastReader();
        PrintWriter pw = new PrintWriter(System.out);
        MathUtils mathUtils = new MathUtils();
        ArrayUtils arrayUtils = new ArrayUtils();

        int tc = sc.ni();
        while (tc-- != 0) {
            String s = sc.ns();

            // separate the string into two parts
            // if one part is a palindrome, and the other part has no repeating letters
            // then it's possible
            char[] keyboard = new char[26];
            List<Character> alphabet = new ArrayList<>();
            Set<Character> alphabetSet = new HashSet<>();
            int n = s.length();
            for (int i = 0; i < 26; i++) {
                alphabet.add((char) (i + 97));
                alphabetSet.add((char) (i + 97));
            }
            if (n == 1) {
                pw.println("YES");
                keyboard[0] = s.charAt(0);
                alphabet.remove(s.charAt(0) - 97);
                for (int i = 0; i < alphabet.size(); i++) {
                    keyboard[i + 1] = alphabet.get(i);
                }
                pw.println(keyboard);
                continue;
            }
            boolean ans = true;
            StringBuilder sb = new StringBuilder(s.charAt(0) + "" + s.charAt(1));
            int x = 1;
            alphabetSet.remove(s.charAt(0));
            alphabetSet.remove(s.charAt(1));

            for(int i = 2; i < n && ans; i++) {
                int m = sb.length();
                if(!alphabetSet.contains(s.charAt(i))) {
                    if(x == m - 1) {
                        if(sb.charAt(x - 1) == s.charAt(i)) x--;
                        else ans = false;
                    } else if (x == 0) {
                        if(sb.charAt(x + 1) == s.charAt(i)) x++;
                        else ans = false;
                    } else {
                        if(sb.charAt(x + 1) == s.charAt(i)) x++;
                        else if(sb.charAt(x - 1) == s.charAt(i)) x--;
                        else ans = false;
                    }
                } else {
                    if(x != m-1 && x != 0) {
                        ans = false;
                    } else {
                        if(x == 0) {
                            sb.insert(0, s.charAt(i));
                        } else {
                            sb.append(s.charAt(i));
                            x++;
                        }
                        alphabetSet.remove(s.charAt(i));
                    }
                }
            }

            if(ans) {
                pw.println("YES");
                pw.print(sb);
                for(char k : alphabetSet) {
                    pw.print(k);
                }
                pw.println();
            } else {
                pw.println("NO");
            }

        }
        pw.flush();
    }

    static class FastReader {
        /**
         * Uses BufferedReader and StringTokenizer for quick java I/O
         * get next int, long, double, string
         * get int, long, double, string arrays, both primitive and wrapped object when array contains all elements
         * on one line, and we know the array size (n)
         * next: gets next space separated item
         * nextLine: returns entire line as space
         */
        BufferedReader br;
        StringTokenizer st;

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

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

        // to parse something else:
        // T x = T.parseT(fastReader.next());
        public int ni() {
            return Integer.parseInt(next());
        }

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

        public String[] readStringArrayLine(int n) {
            String line = "";
            try {
                line = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return line.split(" ");
        }

        public String[] readStringArrayLines(int n) {
            String[] result = new String[n];
            for (int i = 0; i < n; i++) {
                result[i] = this.next();
            }
            return result;
        }

        public int[] readIntArray(int n) {
            int[] result = new int[n];
            for (int i = 0; i < n; i++) {
                result[i] = this.ni();
            }
            return result;
        }

        public long[] readLongArray(int n) {
            long[] result = new long[n];
            for (int i = 0; i < n; i++) {
                result[i] = this.nl();
            }
            return result;
        }

        public Integer[] readIntArrayObject(int n) {
            Integer[] result = new Integer[n];
            for (int i = 0; i < n; i++) {
                result[i] = this.ni();
            }
            return result;
        }

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

        public char[] readCharArray(int n) {
            return this.ns().toCharArray();
        }

    }

    static class MathUtils {
        public MathUtils() {
        }

        public long gcdLong(long a, long b) {
            if (a % b == 0)
                return b;
            else
                return gcdLong(b, a % b);
        }

        public long lcmLong(long a, long b) {
            return a * b / gcdLong(a, b);
        }
    }

    static class ArrayUtils {
        public ArrayUtils() {
        }

        public static int[] reverse(int[] a) {
            int n = a.length;
            int[] b = new int[n];
            int j = n;
            for (int i = 0; i < n; i++) {
                b[j - 1] = a[i];
                j = j - 1;
            }

            return b;
        }

        public int sumIntArrayInt(int[] a) {
            int ans = 0;
            for (int i = 0; i < a.length; i++) {
                ans += a[i];
            }

            return ans;
        }

        public long sumLongArrayLong(int[] a) {
            long ans = 0;
            for (int i = 0; i < a.length; i++) {
                ans += a[i];
            }

            return ans;
        }
    }

    public static int lowercaseToIndex(char c) {
        return (int) c - 97;
    }
}


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

import java.util.*;

public class infiniteprefixes {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while (t-- > 0) {

			int n = sc.nextInt();

			int x = sc.nextInt();

			String s = sc.next();

			int[] cnt = new int[n];

			int c = 0, c0 = 0, c1 = 0, d = 0;

			int ans = 0;

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

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

					c++;

					c0++;

				} else {

					c--;

					c1++;

				}

				cnt[i] = c;

			}

			d = c0 - c1;

			if (d == 0) {

				c = 0;

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

					if (cnt[i] == x)

						c++;

				}

				if (c != 0)

					ans = -1;

				else

					ans = 0;

			} else {

				if (x == 0)

					ans++;

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

					if ((cnt[i] - x) % d == 0) {

						if (d > 0 && cnt[i] <= x)

							ans++;

						if (d < 0 && cnt[i] >= x)

							ans++;

					}

				}

			}

			System.out.println(ans);

		}

	}

}


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;

        }

    }

}