D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

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

public class CodeForces {

    /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
    public static void solve(int tCase) throws IOException {
        long u = sc.nextLong();
        long v = sc.nextLong();
        if(u>v || (v-u) % 2==1){
            out.println(-1);
            return;
        }
        if(u==0){
            if(v==0)out.println(0);
            else {
                out.println(2);
                out.println(v / 2 + " " + v / 2);
            }
            return;
        }
        List<Long> ans = new ArrayList<>();
        ans.add(u);
        v-=u;
        int bit = _digitCount(v,2)-1;
        long vv = v;
        while (v>0 && bit >=0){
            long curr = (1L<<bit);
            long cnt = v/curr;
            if(cnt%2==1)cnt--;
            for(int i=0;i<cnt;i++){
                if(i<ans.size() && (((ans.get(i)>>bit) & 1) ==0))ans.set(i,ans.get(i)+(1L<<bit));
                else ans.add((1L<<bit));
            }
            v-=cnt*(1L<<bit);
            bit--;
        }

        if(ans.size() > 3){
            out.println(3);
            out.println(u+" "+vv/2+" "+vv/2);
            return;
        }
        if(v!=0)throw new IOException("V is not zero");
        long xor = 0;
        for(long x : ans) xor ^=x;
        if(xor!=u)throw new IOException("Xor is not valid");
        out.println(ans.size());
        for(long x : ans)out.println(x);
    }

    public static void main(String[] args) throws IOException {
        openIO();
        int testCase = 1;
//        testCase = sc. nextInt();
        for (int i = 1; i <= testCase; i++) solve(i);
        closeIO();
    }

    /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
    /*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/

    public static int mod = (int) 1e9 + 7;
    //    public static int mod =  998244353;
    public static int inf_int = (int) 2e9;
    public static long inf_long = (long) 2e18;

    public static void _sort(int[] arr, boolean isAscending) {
        int n = arr.length;
        List<Integer> list = new ArrayList<>();
        for (int ele : arr) list.add(ele);
        Collections.sort(list);
        if (!isAscending) Collections.reverse(list);
        for (int i = 0; i < n; i++) arr[i] = list.get(i);
    }

    public static void _sort(long[] arr, boolean isAscending) {
        int n = arr.length;
        List<Long> list = new ArrayList<>();
        for (long ele : arr) list.add(ele);
        Collections.sort(list);
        if (!isAscending) Collections.reverse(list);
        for (int i = 0; i < n; i++) arr[i] = list.get(i);
    }

    // time : O(1), space : O(1)
    public static int _digitCount(long num,int base){
        // this will give the # of digits needed for a number num in format : base
        return (int)(1 + Math.log(num)/Math.log(base));
    }

    // time : O(n), space: O(n)
    public static long _fact(int n){
        // simple factorial calculator
        long ans = 1;
        for(int i=2;i<=n;i++)
            ans = ans * i % mod;
        return ans;
    }

    // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
    public static long[] factorial , inverseFact;
    public static void _ncr_precompute(int n){
        factorial = new long[n+1];
        inverseFact = new long[n+1];
        factorial[0] = inverseFact[0] = 1;
        for (int i = 1; i <=n; i++) {
            factorial[i] = (factorial[i - 1] * i) % mod;
            inverseFact[i] = _modExpo(factorial[i], mod - 2);
        }
    }
    // time of factorial calculation after pre-computation is O(1)
    public static int _ncr(int n,int r){
        if(r > n)return 0;
        return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
    }
    public static int _npr(int n,int r){
        if(r > n)return 0;
        return (int)(factorial[n] * inverseFact[n - r] % mod);
    }

    // euclidean algorithm time O(max (loga ,logb))
    public static long _gcd(long a, long b) {
        while (a>0){
            long x = a;
            a = b % a;
            b = x;
        }
        return b;
//        if (a == 0)
//            return b;
//        return _gcd(b % a, a);
    }

    // lcm(a,b) * gcd(a,b) = a * b
    public static long _lcm(long a, long b) {
        return (a / _gcd(a, b)) * b;
    }

    // binary exponentiation time O(logn)
    public static long _modExpo(long x, long n) {
        long ans = 1;
        while (n > 0) {
            if ((n & 1) == 1) {
                ans *= x;
                ans %= mod;
                n--;
            } else {
                x *= x;
                x %= mod;
                n >>= 1;
            }
        }
        return ans;
    }
    // function to find a/b under modulo mod. time : O(logn)
    public static long _modInv(long a,long b){
        return (a * _modExpo(b,mod-2)) % mod;
    }

    //sieve or first divisor time : O(mx * log ( log (mx) ) )
    public static int[]  _seive(int mx){
        int[] firstDivisor = new int[mx+1];
        for(int i=0;i<=mx;i++)firstDivisor[i] = i;
        for(int i=2;i*i<=mx;i++)
            if(firstDivisor[i] == i)
                for(int j = i*i;j<=mx;j+=i)
                    firstDivisor[j] = i;
        return firstDivisor;
    }

    // check if x is a prime # of not. time : O( n ^ 1/2 )
    private static boolean _isPrime(long x){
        for(long i=2;i*i<=x;i++)
            if(x%i==0)return false;
        return true;
    }

    static class Pair<K, V>{
        K ff;
        V ss;

        public Pair(K ff, V ss) {
            this.ff = ff;
            this.ss = ss;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || this.getClass() != o.getClass()) return false;
            Pair<?, ?> pair = (Pair<?, ?>) o;
            return ff.equals(pair.ff) && ss.equals(pair.ss);
        }

        @Override
        public int hashCode() {
            return Objects.hash(ff, ss);
        }
        @Override
        public String toString(){
            return ff.toString()+" "+ss.toString();
        }
    }

    /*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/
    /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
    static FastestReader sc;
    static PrintWriter out;

    private static void openIO() throws IOException {
        sc = new FastestReader();
        out = new PrintWriter(System.out);
    }

    public static void closeIO() throws IOException {
        out.flush();
        out.close();
        sc.close();
    }

    private static final class FastestReader {
        private static final int BUFFER_SIZE = 1 << 16;
        private final DataInputStream din;
        private final byte[] buffer;
        private int bufferPointer, bytesRead;

        public FastestReader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public FastestReader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        private static boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }

        private int skip() throws IOException {
            int b;
            //noinspection StatementWithEmptyBody
            while ((b = read()) != -1 && isSpaceChar(b)) {
            }
            return b;
        }

        public String next() throws IOException {
            int b = skip();
            final StringBuilder sb = new StringBuilder();
            while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
                sb.appendCodePoint(b);
                b = read();
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            final boolean neg = c == '-';
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (neg) {
                return -ret;
            }
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            final boolean neg = c == '-';
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) {
                return -ret;
            }
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            final boolean neg = c == '-';
            if (neg) {
                c = read();
            }

            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (c == '.') {
                while ((c = read()) >= '0' && c <= '9') {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg) {
                return -ret;
            }
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) {
                buffer[0] = -1;
            }
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead) {
                fillBuffer();
            }
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            din.close();
        }
    }
    /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}


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

import java.io.*;

public class Main {

    static class Scan {

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

        private int index;

        private InputStream in;

        private int total;

        public Scan()

        {

            in=System.in;

        }

        public int scan()throws IOException

        {

            if(total<0)

            throw new InputMismatchException();

            if(index>=total)

            {

                index=0;

                total=in.read(buf);

                if(total<=0)

                return -1;

            }

            return buf[index++];

        }

        public int scanInt()throws IOException

        {

            int integer=0;

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            int neg=1;

            if(n=='-')

            {

                neg=-1;

                n=scan();

            }

            while(!isWhiteSpace(n))

            {

                if(n>='0'&&n<='9')

                {

                    integer*=10;

                    integer+=n-'0';

                    n=scan();

                }

                else throw new InputMismatchException();

            }

            return neg*integer;

        }

        public double scanDouble()throws IOException

        {

            double doub=0;

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            int neg=1;

            if(n=='-')

            {

                neg=-1;

                n=scan();

            }

            while(!isWhiteSpace(n)&&n!='.')

            {

                if(n>='0'&&n<='9')

                {

                    doub*=10;

                    doub+=n-'0';

                    n=scan();

                }

                else throw new InputMismatchException();

            }

            if(n=='.')

            {

                n=scan();

                double temp=1;

                while(!isWhiteSpace(n))

                {

                    if(n>='0'&&n<='9')

                    {

                        temp/=10;

                        doub+=(n-'0')*temp;

                        n=scan();

                    }

                    else throw new InputMismatchException();

                }

            }

            return doub*neg;

        }

        public String scanString()throws IOException

        {

            StringBuilder sb=new StringBuilder();

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            while(!isWhiteSpace(n))

            {

                sb.append((char)n);

                n=scan();

            }

            return sb.toString();

        }

        private boolean isWhiteSpace(int n)

        {

            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)

            return true;

            return false;

        }

    }

    static long n,pow[];

    static int m,arr[];

    static HashMap<Long,Integer> map;

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

        Scanner input=new Scanner(System.in);

        int test=input.nextInt();

        pow=new long[32];

        pow[0]=1;

        map=new HashMap<>();

        map.put(1L, 0);

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

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

            map.put(pow[i], i);

        }

        StringBuilder ans=new StringBuilder("");

        for(int t=1;t<=test;t++) {

            n=input.nextLong();

            m=input.nextInt();

            arr=new int[pow.length];

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

                arr[map.get(input.nextLong())]++;

            }

            ans.append(solve()+"\n");

        }

        System.out.println(ans);

    }

    public static int solve() {

        int ans=0;

        if(n%2==1) {

            if(arr[0]>0) {

                arr[0]--;

                n--;

            }

            else {

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

                    if(arr[i]>0) {

                        arr[i]--;

                        long tmp=pow[i];

                        while(tmp!=1) {

//                            System.out.println(tmp);

                            tmp/=2;

                            arr[map.get(tmp)]++;

                            ans++;

                        }

                        arr[0]--;

                        n--;

                        break;

                    }

                }

            }

        }

//        System.out.println("III");

        arr[1]+=arr[0]/2;

        arr[0]=0;

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

//            System.out.println("i "+i);

            if((n&(long)Math.pow(2, i))!=0) {

                int tmp=check((long)Math.pow(2, i));

                if(tmp==-1) {

                    return -1;

                }

                ans+=tmp;

            }

        }

        return ans;

    }

    public static int check(long tmp) {

        long tmp1=tmp;

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

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

            tmp_arr[i]=arr[i];

        }

        for(int i=pow.length-1;i>0;i--) {

            while(tmp_arr[i]>0 && pow[i]<=tmp1) {

                tmp1-=pow[i];

                tmp_arr[i]--;

            }

        }

        if(tmp1==0) {

            arr=tmp_arr;

            return 0;

        }

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

            if(arr[i]>0 && pow[i]>=tmp) {

                arr[i]--;

                tmp1=pow[i];

                int cnt=0;

                while(tmp1!=tmp) {

                    tmp1/=2;

                    arr[map.get(tmp1)]++;

                    cnt++;

                }

                return cnt;

            }

        }

        return -1;

    }

}


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy 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 one of the two 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 say if it is possible to color the given string 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≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

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

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

  static class E1StringColoringEasyVersion {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      int n = in.nextInt();
      String s = in.nextString();
      char[] chars = s.toCharArray();
      int[] a = new int[n];
      char last1 = 'a' - 1;
      char last2 = 'a' - 1;
      for (int i = 0; i < n; i++) {
        if (chars[i] >= last1) {
          last1 = chars[i];
        } else {
          if (chars[i] >= last2) {
            last2 = chars[i];
            a[i] = 1;
          } else {
            out.println("NO");
            return;
          }
        }
      }
      out.println("YES");
      for (int i = 0; i < n; i++) {
        out.print(a[i]);
      }
      out.println();

    }

  }

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

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

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

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

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

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
      this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
      for (int i = 0; i < objects.length; i++) {
        if (i != 0) {
          writer.print(' ');
        }
        writer.print(objects[i]);
      }
    }

    public void println() {
      writer.println();
    }

    public void println(Object... objects) {
      print(objects);
      writer.println();
    }

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

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

  }
}


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

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

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

        var n = scanner.nextInt();
        var a = new long[n];
        for (int i = 0; i < a.length; i++) {
            a[i] = scanner.nextLong();
        }
        // TODO 2020/3/20: 为什么distinct了反而过不了？
        var distinct = Arrays.stream(a)/*.distinct()*/.boxed().collect(Collectors.toList());
        Collections.shuffle(distinct);
//        var distinct = Arrays.stream(a).distinct().toArray();
        var factors = new HashSet<Long>();
        for (int guess = 0; guess < 40 && guess < distinct.size(); guess++) {
            for (int j = -1; j <= 1; j++) {
                factors.addAll(factor(distinct.get(guess) + j));
            }
        }
//        for (int guess = 0; guess < 20; guess++) {
//            var i = (int) (Math.random() * distinct.length);
//            for (int j = -1; j <= 1; j++) {
//                factors.addAll(factor(distinct[i] + j));
//            }
//        }
        var ans = countOps(2, a, n);
        factors.remove(2L);
        for (var factor : factors) {
            var ops = countOps(factor, a, ans);
            ans = Math.min(ans, ops);
        }
        writer.println(ans);

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

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

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

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

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

        public BufferedScanner() {
            this(new InputStreamReader(System.in));
        }

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

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

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

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

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

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

    }

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

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

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

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

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.Scanner;

import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) {

        InputReader s = new InputReader();

        PrintWriter w = new PrintWriter(System.out);

        int T = s.nextInt();

        while(T-->0){

            int n = s.nextInt();

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

            int[] ans = new int[n];

            int num = n, last = 0;

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

            {

                if (i == n - 1 || c[i] == '>')

                {

                    for (int j = i; j >= last; j--)

                        ans[j] = num--;

                    last = i + 1;

                }

            }

            for (int i = 0; i < n; i++) w.write(ans[i]+" ");

            w.println();

            num = 1;

            last = 0;

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

            {

                if (i == n - 1 || c[i] == '<')

                {

                    for (int j = i; j >= last; j--)

                        ans[j] = num++;

                    last = i + 1;

                }

            }

            for (int i = 0; i < n; i++) w.write(ans[i]+" ");

            w.println();

        }

        w.flush();

    }

}

class InputReader {

    public BufferedReader reader;

    public StringTokenizer tokenizer;

    public InputReader() {

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

        tokenizer = null;

    }

    public String next() {

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

            try {

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

            } catch (IOException e) {

                throw new RuntimeException(e);

            }

        }

        return tokenizer.nextToken();

    }

    public int nextInt() {

        return Integer.parseInt(next());

    }

    public double nextDouble() {

        return Double.parseDouble(next());

    }

    public long nextLong() {

        return Long.parseLong(next());

    }

}


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

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.StringTokenizer;

public class YetAnotherMemeProblem {

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

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

        PrintWriter pw = new PrintWriter(System.out);

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

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

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

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

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

            String bS = Integer.toString(b);

            long nines = bS.length() - 1;

            int count = 0;

            for (int j = 0; j < bS.length(); j++) {

                if (bS.charAt(j) == '9') count++;

            }

            if (count == bS.length()) nines++;

            pw.println(a * nines);

        }

        pw.close();

    }

}


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

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Arrays;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.BufferedOutputStream;

import java.io.UncheckedIOException;

import java.util.Objects;

import java.nio.charset.Charset;

import java.util.StringTokenizer;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.BufferedReader;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author mikit

 */

public class Main {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        LightScanner in = new LightScanner(inputStream);

        LightWriter out = new LightWriter(outputStream);

        ENewYearAndCastleConstruction solver = new ENewYearAndCastleConstruction();

        solver.solve(1, in, out);

        out.close();

    }

    static class ENewYearAndCastleConstruction {

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

            int n = in.ints();

            Vec2l[] points = new Vec2l[n];

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

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

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

                int m = 0;

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

                {

                    Vec2l now = points[t];

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

                        if (i != t) {

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

                            m++;

                        }

                    }

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

                }

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

                int hi = 0;

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

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

                        hi++;

                    }

                    int cnt = hi - j;

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

                }

            }

            out.ans(ans).ln();

        }

    }

    static class Vec2l implements Comparable<Vec2l> {

        public long x;

        public long y;

        public Vec2l(long x, long y) {

            this.x = x;

            this.y = y;

        }

        public long det(Vec2l other) {

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

        }

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Vec2l vec2i = (Vec2l) o;

            return x == vec2i.x &&

                    y == vec2i.y;

        }

        public int hashCode() {

            return Objects.hash(x, y);

        }

        public String toString() {

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

        }

        public int compareTo(Vec2l o) {

            if (x == o.x) {

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

            }

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

        }

        public int compareToByAngle(Vec2l o) {

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

                return y >= 0 ? 1 : -1;

            } else {

                return Long.signum(o.x * y - x * o.y);

            }

        }

    }

    static class LightWriter implements AutoCloseable {

        private final Writer out;

        private boolean autoflush = false;

        private boolean breaked = true;

        public LightWriter(Writer out) {

            this.out = out;

        }

        public LightWriter(OutputStream out) {

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

        }

        public LightWriter print(char c) {

            try {

                out.write(c);

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter print(String s) {

            try {

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

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter ans(String s) {

            if (!breaked) {

                print(' ');

            }

            return print(s);

        }

        public LightWriter ans(long l) {

            return ans(Long.toString(l));

        }

        public LightWriter ln() {

            print(System.lineSeparator());

            breaked = true;

            if (autoflush) {

                try {

                    out.flush();

                } catch (IOException ex) {

                    throw new UncheckedIOException(ex);

                }

            }

            return this;

        }

        public void close() {

            try {

                out.close();

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

        }

    }

    static class LightScanner {

        private BufferedReader reader = null;

        private StringTokenizer tokenizer = null;

        public LightScanner(InputStream in) {

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

        }

        public String string() {

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

                try {

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

                } catch (IOException e) {

                    throw new UncheckedIOException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public int ints() {

            return Integer.parseInt(string());

        }

        public long longs() {

            return Long.parseLong(string());

        }

    }

}


import java.util.*;

public class D_Ehab_the_Xorcist{

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        long u = sc.nextLong();

        long v = sc.nextLong();

        if(u>v){

            System.out.println(-1);

        }else if(u==v){

            if(u==0){

                System.out.println(0);

            }else{

                System.out.println(1);

                System.out.println(u);

            }

        }else{

            long diff = v-u;

            if(diff%2==0){

                long d2 = diff/2;

                if((d2^u)==(d2+u)){

                    System.out.println(2);

                    System.out.println((d2+u)+" "+d2);

                }else{

                    System.out.println(3);

                    System.out.println(u + " "+d2+" "+d2);

                }

            }else{

                System.out.println(-1);

            }

        }

    }

}


/*

    Author : Akshat Jindal

    from NIT Jalandhar , Punjab , India

    JAI MATA DI

 */

import java.util.*;

import javax.swing.text.Segment;

import java.io.*;

import java.math.*;

import java.sql.Array;

public class Main {

	  static class FR{

			BufferedReader br;

			StringTokenizer st;

			public FR() {

				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 long mod = (long)(1e9 + 7);

	static void sort(long[] arr ) {

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

		 for(long e:arr) al.add(e);

		 Collections.sort(al);

		 for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);

	 }

	static void sort(int[] arr ) {

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

		 for(int e:arr) al.add(e);

		 Collections.sort(al);

		 for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);

	 }

	static void sort(char[] arr) {

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

		for(char cc:arr) al.add(cc);

		Collections.sort(al);

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

	}

	static void rvrs(int[] arr) {

		int i =0 , j = arr.length-1;

		while(i>=j) {

			int temp = arr[i];

			arr[i] = arr[j];

			arr[j] = temp;

			i++;

			j--;

		}

	}

	static void rvrs(long[] arr) {

		int i =0 , j = arr.length-1;

		while(i>=j) {

			long temp = arr[i];

			arr[i] = arr[j];

			arr[j] = temp;

			i++;

			j--;

		}

	}

	static long mod_mul(long a , long b ,long mod) {

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

	}

	 static long gcd(long a, long b)

	  {

	     if (b == 0)

	        return a;

	     return gcd(b, a % b);

	  }

	 static boolean[] prime(int num) {

			boolean[] bool = new boolean[num];

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

		         bool[i] = true;

		      }

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

		         if(bool[i] == true) {

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

		               bool[j] = false;

		            }

		         }

		      }

		      if(num >= 0) {

		    	  bool[0] = false;

		    	  bool[1] = false;

		      }

		      return bool;

		}

	 static long modInverse(long a, long m)

	    {

	        long g = gcd(a, m);

	          return   power(a, m - 2, m);

	    }

	 static long power(long x, long y, long m){

	        if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);

	        if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }

     static class Combinations{

	    	 private long[] z;

	    	 private long[] z1;

	    	 private long[] z2;

	    	  public Combinations(long N , long mod) {

				z = new long[(int)N+1];

				z1 = new long[(int)N+1];

				z[0] = 1;

				for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;

			     z2 = new long[(int)N+1];

				z2[0] = z2[1] = 1;

			    for (int i = 2; i <= N; i++)

			        z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;

			    z1[0] = z1[1] = 1;

			    for (int i = 2; i <= N; i++)

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

			}

	    	  long fac(long n) {

	    		  return z[(int)n];

	    	  }

	    	  long invrsNum(long n) {

	    		  return z2[(int)n];

	    	  }

	    	  long invrsFac(long n) {

	    		  return invrsFac((int)n);

	    	  }

	    	  long ncr(long N, long R, long mod)

	    	  {		if(R<0 || R>N ) return 0;

	    		    long ans = ((z[(int)N] * z1[(int)R])

	    		              % mod * z1[(int)(N - R)])

	    		             % mod;

	    		    return ans;

	    		}

	      }

	      static class DisjointUnionSets {

			    int[] rank, parent;

			    int n;

			    public DisjointUnionSets(int n)

			    {

			        rank = new int[n];

			        parent = new int[n];

			        this.n = n;

			        makeSet();

			    }

			    void makeSet()

			    {

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

			            parent[i] = i;

			        }

			    }

			    int find(int x)

			    {

			        if (parent[x] != x) {

			            parent[x] = find(parent[x]);

			        }

			        return parent[x];

			    }

			    void union(int x, int y)

			    {

			        int xRoot = find(x), yRoot = find(y);

			        if (xRoot == yRoot)

			            return;

			        if (rank[xRoot] < rank[yRoot])

			            parent[xRoot] = yRoot;

			        else if (rank[yRoot] < rank[xRoot])

			            parent[yRoot] = xRoot;

			        else

			        {

			            parent[yRoot] = xRoot;

			            rank[xRoot] = rank[xRoot] + 1;

			        }

			    }

			}

	      static int[] KMP(String str) {

	    	  int n = str.length();

	    	  int[] kmp = new int[n];

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

	    		  int j = kmp[i-1];

	    		  while(j>0 && str.charAt(i) != str.charAt(j)) {

	    			  j = kmp[j-1];

	    		  }

	    		  if(str.charAt(i) == str.charAt(j)) j++;

	    		  kmp[i] = j;

	    	  }

	    	  return kmp;

	      }

/************************************************ Query **************************************************************************************/

/***************************************** 		Sparse Table	********************************************************/

	      static class SparseTable{

	    		private long[][] st;

	    		SparseTable(long[] arr){

	    			int n = arr.length;

	    			st = new long[n][25];

	    			log = new int[n+2];

	    			build_log(n+1);

	    			build(arr);

	    		}

	    		private void build(long[] arr) {

	    			int n = arr.length;

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

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

	    					int r = i + (1<<j)-1;

	    					if(r>=n) break;

	    					if(j == 0 ) st[i][j] = arr[i];

	    					else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );

	    				}

	    			}

	    		}

	    		public long gcd(long a  ,long b) {

	    			if(a == 0) return b;

	    			return gcd(b%a , a);

	    		}

	    		public long query(int l ,int r) {

	    			int w = r-l+1;

	    			int power = log[w];

	    			return Math.min(st[l][power],st[r - (1<<power) + 1][power]);

	    		}

	    		private int[] log;

	    		void build_log(int n) {

	    			log[1] = 0;

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

	    				log[i] = 1 + log[i/2];

	    			}

	    		}

	    	}

/********************************************************	Segement Tree	*****************************************************/

/**

	 	 static class SegmentTree{

			 long[] tree;

			 long[] arr;

			 int n;

			 SegmentTree(long[] arr){

				 this.n = arr.length;

				 tree = new long[4*n+1];

				 this.arr = arr;

				 buildTree(0, n-1, 1);

			 }

			  void buildTree(int s ,int e  ,int index ) {

					if(s == e) {

						tree[index] = arr[s];

						return;

					}

					int mid = (s+e)/2;

					buildTree( s,  mid, 2*index);

					buildTree( mid+1, e, 2*index+1);

					tree[index] = Math.min(tree[2*index] , tree[2*index+1]);

				}

			 long query(int si ,int ei) {

				 return query(0 ,n-1 , si ,ei , 1   );

			 }

			 private long query( int ss ,int se ,int qs , int qe,int index) {

					if(ss>=qs && se<=qe) return tree[index];

					if(qe<ss || se<qs) return (long)(1e17);

					int mid = (ss + se)/2;

					long left = query( ss , mid , qs ,qe , 2*index);

					long right= query(mid + 1 , se , qs ,qe , 2*index+1);

					return Math.min(left, right);

				}

			 public void update(int index , int val) {

				 arr[index] = val;

				 for(long e:arr) System.out.print(e+" ");

				 update(index , 0 , n-1 , 1);

			 }

			 private void update(int id ,int si , int ei , int index) {

				 if(id < si || id>ei) return;

				 if(si == ei ) {

					 tree[index] = arr[id];

					 return;

				 }

				 if(si > ei) return;

				 int mid = (ei + si)/2;

					update( id,  si, mid , 2*index);

					update( id , mid+1, ei , 2*index+1);

					tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);

			 }

		 }

		 */

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

	      static FR sc = new FR();

	 static StringBuilder sb = new StringBuilder();

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

		 int tc = 1;

//		  tc = sc.nextInt();

		 while(tc-->0) {

			 TEST_CASE();

		 }

		 System.out.println(sb);

	 }

	 static void TEST_CASE() {

		 int n = sc.nextInt();

		 char[] str = sc.next().toCharArray();

		 int[] ans = new int[n];

		 boolean bool = fnc(str, ans);

		 if(bool) {

			 System.out.println("YES");

			 for(int e:ans) sb.append(e);

		 }else {

			 System.out.println("NO");

		 }

	 }

	 static boolean fnc(char[] str ,int[] ans) {

		 int n = str.length;

		 Arrays.fill(ans, -1);

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

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

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

				 if(str[i] - 'a' == k) ind.add(i);

			 }

			 if(ind.size()==0) continue;

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

			 for(int i =0 ; i<ind.get(0) ; i++) {

				 if(str[i] - 'a' > k)

				 non.add(i);

			 }

			 boolean one = false , zero = false;

			 for(int e:non) {

				 if(ans[e] == 0) zero = true;

				 if(ans[e] == 1) one  = true;

			 }

			 if(one && zero) return false;

			 if( (one && ans[ind.get(0)] == 1) || (zero && ans[ind.get(0)] == 0)   )

				 return false;

			 if(one || ans[ind.get(0)] == 0) {

				 ans[ind.get(0)] = 0;

				 for(int e:non) ans[e] = 1;

			 }else {

				 ans[ind.get(0)] = 1;

				 for(int e:non) ans[e] = 0;

			 }

			 for(int i = 1 ; i<ind.size() ; i++) {

				 one = false; zero = false;

				 non = new ArrayList<>();

				 for(int j = ind.get(i-1)+1 ; j<=ind.get(i)-1 ; j++) {

					 if(str[j] - 'a' > k) non.add(j);

				 }

				 for(int e:non) {

					 if(ans[e] == 0) zero = true;

					 if(ans[e] == 1) one  = true;

				 }

				 if(one && zero) return false;

				 if( (one && ans[ind.get(i)] == 1) || (zero && ans[ind.get(i)] == 0)  )

					 return false;

				 if(one || ans[ind.get(i)] == 0) {

					 ans[ind.get(i)] = 0;

					 for(int e:non) ans[e] = 1;

				 }else {

					 ans[ind.get(i)] = 1;

					 for(int e:non) ans[e] = 0;

				 }

			 }

//			 System.out.println(k);

//			 for(int e:ans) System.out.print(e+" ");

//			 System.out.println();

//			 System.out.println("------------");

		 }

		 return true;

	 }

}

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

/**

 */


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.


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

import java.util.*;

public class Hello {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();

        while (T-- > 0) {

            long X = sc.nextLong();

            long Y = sc.nextLong();

            long result = Y / getGCD(X, Y);

            long val = result;

            for (long ctr = 2; ctr * ctr <= val; ctr++) {

                if (val % ctr == 0) {

                    result -= result / ctr;

                }

                while (val % ctr == 0) {

                    val /= ctr;

                }

            }

            if (val != 1) {

                result -= result / val;

            }

            System.out.println(result);

        }

    }

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

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

    }

}


C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.Arrays;

import java.io.BufferedWriter;

import java.util.InputMismatchException;

import java.io.IOException;

import java.util.ArrayList;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.InputStream;

/**

 * Built using CHelper plug-in Actual solution is at the top

 *

 * @author ilyakor

 */

public class Main {

  public static void main(String[] args) {

    InputStream inputStream = System.in;

    OutputStream outputStream = System.out;

    InputReader in = new InputReader(inputStream);

    OutputWriter out = new OutputWriter(outputStream);

    TaskC1 solver = new TaskC1();

    solver.solve(1, in, out);

    out.close();

  }

  static class TaskC1 {

    InputReader in;

    OutputWriter out;

    public void solve(int testNumber, InputReader in, OutputWriter out) {

      // Random random = new Random(0xdead);

      // for (int it = 0; it < 10000; ++it) {

      //     int n = 8;

      //     StringBuilder sb = new StringBuilder();

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

      //         sb.append((char)('a' + random.nextInt(26)));

      //     S = sb.toString();

      //     sum = 0;

      //     String res = new String(doSolve(S.length()));

      //     if (sum > (n + 1) * (n + 1))

      //         throw new RuntimeException();

      //     if (!res.equals(S))

      //         throw new RuntimeException();

      // }

      this.in = in;

      this.out = out;

      int n = in.nextInt();

      if (n == 1) {

        char c1 = doQuery(1, 1).get(0)[0];

        out.printLine("! " + c1);

        out.flush();

        return;

      }

      if (n == 2) {

        char c1 = doQuery(1, 1).get(0)[0];

        out.printLine("? 2 2");

        out.flush();

        char c2 = in.nextToken().toCharArray()[0];

        out.printLine("! " + c1 + "" + c2);

        out.flush();

        return;

      }

      if (n == 3) {

        char c1 = doQuery(1, 1).get(0)[0];

        out.printLine("? 2 2");

        out.flush();

        char c2 = in.nextToken().toCharArray()[0];

        out.printLine("? 3 3");

        out.flush();

        char c3 = in.nextToken().toCharArray()[0];

        out.printLine("! " + c1 + "" + c2 + "" + c3);

        out.flush();

        return;

      }

      char[] res = doSolve(n);

      out.printLine("! " + new String(res));

      out.flush();

    }

    public char[] doSolve(int n) {

      char c1 = doQuery(1, 1).get(0)[0];

      char[][] qn = query(1, n);

      int m = 1;

      // int m = n / 2 - 1;

      // if ((n - m) % 2 == 1) ++m;

      char[][] qm = query(m + 1, n);

      char[] res = new char[n];

      char c = c1;

      int pos = 0;

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

        res[pos] = c;

        if (it == n - 1) {

          break;

        }

        if (res[n - 1 - pos] == 0) {

          c = other(qn[Math.min(pos, n - 1 - pos)], c);

          pos = n - 1 - pos;

        } else {

          if (res[m + n - 1 - pos] != 0) {

            throw new RuntimeException();

          }

          c = other(qm[Math.min(pos, m + n - 1 - pos) - m], c);

          pos = m + n - 1 - pos;

        }

      }

      return res;

    }

    private char other(char[] a, char c) {

      if (a[0] != c) {

        return a[0];

      }

      return a[1];

    }

    private char[][] query(int l, int r) {

      int n = r - l + 1;

      ArrayList<char[]> output = doQuery(l, r);

      ArrayList<char[]>[] ans = new ArrayList[n + 1];

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

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

      }

      for (char[] s : output) {

        Arrays.sort(s);

        ans[s.length].add(s);

      }

      char[][] res = new char[(n + 1) / 2][2];

      int[] cnts = new int[26];

      char[] st = new char[20];

      int ss = 0;

      for (char[] s : ans[n - 1]) {

        char[] os = ans[n].get(0);

        Arrays.fill(cnts, 0);

        for (char c : os) {

          ++cnts[c - 'a'];

        }

        for (char c : s) {

          --cnts[c - 'a'];

        }

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

          if (cnts[i] > 0) {

            st[ss++] = (char) ('a' + i);

          }

        }

      }

      if (ss != 2) {

        throw new RuntimeException();

      }

      res[0][0] = st[0];

      res[0][1] = st[1];

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

        int len = n - i - 1;

        Arrays.fill(cnts, 0);

        for (char[] s : ans[len]) {

          for (char c : s) {

            ++cnts[c - 'a'];

          }

        }

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

          for (char c : res[j]) {

            cnts[c - 'a'] -= j + 1;

          }

        }

        ss = 0;

        for (int j = 0; j < cnts.length; ++j) {

          if (cnts[j] % (i + 2) != 0) {

            st[ss++] = (char) ('a' + j);

          }

        }

        if (ss != 1 && ss != 2) {

          throw new RuntimeException();

        }

        if (ss == 1) {

          st[1] = st[0];

        }

        res[i][0] = st[0];

        res[i][1] = st[1];

      }

      return res;

    }

    ArrayList<char[]> doQuery(int l, int r) {

      // ArrayList<char[]> res = new ArrayList<>();

      // for (int i = l - 1; i <= r - 1; ++i)

      //     for (int j = i; j <= r - 1; ++j)

      //         res.add(S.substring(i, j + 1).toCharArray());

      // sum += res.size();

      // return res;

      out.printLine("? " + l + " " + r);

      out.flush();

      int n = r - l + 1;

      ArrayList<char[]> res = new ArrayList<>();

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

        res.add(in.nextToken().toCharArray());

      }

      return res;

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

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

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

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

        if (i != 0) {

          writer.print(' ');

        }

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

    public void flush() {

      writer.flush();

    }

  }

  static class InputReader {

    private InputStream stream;

    private byte[] buffer = new byte[10000];

    private int cur;

    private int count;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public static boolean isSpace(int c) {

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

    }

    public int read() {

      if (count == -1) {

        throw new InputMismatchException();

      }

      try {

        if (cur >= count) {

          cur = 0;

          count = stream.read(buffer);

          if (count <= 0) {

            return -1;

          }

        }

      } catch (IOException e) {

        throw new InputMismatchException();

      }

      return buffer[cur++];

    }

    public int readSkipSpace() {

      int c;

      do {

        c = read();

      } while (isSpace(c));

      return c;

    }

    public String nextToken() {

      int c = readSkipSpace();

      StringBuilder sb = new StringBuilder();

      while (!isSpace(c)) {

        sb.append((char) c);

        c = read();

      }

      return sb.toString();

    }

    public int nextInt() {

      int sgn = 1;

      int c = readSkipSpace();

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

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

          throw new InputMismatchException();

        }

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

        c = read();

      } while (!isSpace(c));

      res *= sgn;

      return res;

    }

  }

}


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.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 a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

import java.util.Scanner;

public class Main {

    static long cnt = 0;

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        while (t-- > 0) {

            int n = sc.nextInt();

            String s = sc.next();

            int cnt = 0;

            String ans = " ";

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

                char c = s.charAt(i);

                if ((c - '0') % 2 == 1) {

                    ans += c;

                    cnt++;

                }

                if (cnt == 2) {

                    System.out.println(ans);

                    break;

                }

            }

            if (cnt != 2) {

                System.out.println(-1);

            }

        }

    }

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.StringTokenizer;

public class drevilunderscores {

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

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

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

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

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

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

		for (int i = 0; i < n; i++) a.add(Integer.parseInt(token.nextToken()));

		System.out.println(solve(a, 30));

	}

	public static int solve(ArrayList<Integer> a, int b) {

		if (b == -1) return 0;

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

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

		for (int i : a) {

			if (((i >> b) & 1) == 0) l.add(i);

			else r.add(i);

		}

		if (l.size()==0) return solve(r, b-1);

		if (r.size()==0) return solve(l, b-1);

		return Math.min(solve(l, b-1), solve(r, b-1)) + (1 << b);

	}

}


B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.

/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

        List<Integer> maximums = new ArrayList<>();

        List<Integer> minimums = new ArrayList<>();

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

            boolean alreadyHasAscent = false;

            int totalElements = sc.nextInt();

            int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

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

                int value = sc.nextInt();

                if (value > min) {

                    alreadyHasAscent = true;

                }

                min = Math.min(min, value);

                max = Math.max(max, value);

            }

            if (alreadyHasAscent) {

                min = Integer.MIN_VALUE;

                max = Integer.MAX_VALUE;

            }

            minimums.add(min);

            maximums.add(max);

        }

        Collections.sort(minimums);

        Collections.sort(maximums);

        //out.println(maximums);

        long totalPairs = 0;

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

            totalPairs += binarySearch(maximums, minimums.get(i));

        }

        out.println(totalPairs);

    }

    private static long binarySearch(List<Integer> maximums, int minValue) {

        int n = maximums.size();

        int lo = 0, hi = n - 1;

        int res = n;

        while (lo <= hi) {

            int mid = (lo + hi) >> 1;

            if (maximums.get(mid) > minValue) {

                //out.println("ok");

                res = Math.min(res, mid);

                hi = mid - 1;

            }else {

                lo = mid + 1;

            }

        }

        return n - res;

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

            while (str == null || !str.hasMoreElements())

            {

                try

                {

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

                }

                catch (IOException  end)

                {

                    end.printStackTrace();

                }

            }

            return str.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 end)

            {

                end.printStackTrace();

            }

            return str;

        }

    }

}


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

/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static int MAX = 100005, DEPTH = 25;

    static int[] tin = new int[MAX];

    static int[] tout = new int[MAX];

    static int time = 1;

    static int[] distance = new int[MAX];

    static int[][] ancestor = new int[MAX][DEPTH];

    static Map<Integer, List<Integer>> graph = new HashMap<>();

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

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

        sc = new FastReader();

        int test = 1;

        for (int t = 1; t <= test; t++) {

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

            graph.put(i, new ArrayList<>());

        }

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

            int u = sc.nextInt();

            int v = sc.nextInt();

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

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

        }

        dfs(1, 1);

        int q = sc.nextInt();

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

            // add edge between x and y

            int x = sc.nextInt();

            int y = sc.nextInt();

            // find a path from a to b having exactly k edges

            int a = sc.nextInt();

            int b = sc.nextInt();

            int k = sc.nextInt();

            // if path length between a and b is l, then since a path can contain the same vertices and same edges multiple times,

            // we can also find a path between a and b with length l + 2 * constant

            // we should find a path with length l <= k, which have parity same as parity of k

            List<Integer> possiblePathLengths = new ArrayList<>();

            // case1 : path from a to b without using added edge between x and y

            possiblePathLengths.add(findDistanceBetweenTwoNodes(a, b));

            // case2 : path from a to x, then use added edge from x to y (only once, otherwise it won't affect the parity), and then from y to b

            possiblePathLengths.add(findDistanceBetweenTwoNodes(a, x) + 1 + findDistanceBetweenTwoNodes(b, y));

            // case3 : path from a to y, then use added edge from y to x (only once, otherwise it won't affect the parity), and then from x to b

            possiblePathLengths.add(findDistanceBetweenTwoNodes(a, y) + 1 + findDistanceBetweenTwoNodes(b, x));

            boolean found = false;

            for (int length : possiblePathLengths) {

                if (length <= k && (length % 2 == k % 2)) {

                    found = true;

                    break;

                }

            }

            out.println(found ? "YES" : "NO");

        }

    }

    private static void dfs(int currNode, int parent) {

        tin[currNode] = time++;

        ancestor[currNode][0] = parent;

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

            ancestor[currNode][j] = ancestor[ancestor[currNode][j - 1]][j - 1];

        }

        for (int adjacentNode : graph.get(currNode)) {

            if (adjacentNode == parent) {

                continue;

            }

            distance[adjacentNode] = distance[currNode] + 1;

            dfs(adjacentNode, currNode);

        }

        tout[currNode] = time++;

    }

    private static int findDistanceBetweenTwoNodes(int u, int v) {

        int lcaNode = findLCA(u, v);

        return distance[u] + distance[v] - 2 * distance[lcaNode];

    }

    private static int findLCA(int u, int v) {

        if (isAncestor(u, v)) {

            return u;

        }

        if (isAncestor(v, u)) {

            return v;

        }

        for (int j = DEPTH - 1; j >= 0; j--) {

            if (!isAncestor(ancestor[u][j], v)) {

                u = ancestor[u][j];

            }

        }

        return ancestor[u][0];

    }

    private static boolean isAncestor(int u, int v) { // check if u is ancestor of v

        return tin[u] <= tin[v] && tout[u] >= tout[v];

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

            while (str == null || !str.hasMoreElements())

            {

                try

                {

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

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.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 lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

        char prev = 'a', prevToPrev = 'a';

        String res = "";

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

            if (s[i] >= prev) {

                res += '0';

                prev = s[i];

            }else if (s[i] >= prevToPrev) {

                res += '1';

                prevToPrev = s[i];

            }else {

                out.println("NO");

                return;

            }

        }

        out.println("YES");

        out.println(res);

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

            while (str == null || !str.hasMoreElements())

            {

                try

                {

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

                }

                catch (IOException  end)

                {

                    end.printStackTrace();

                }

            }

            return str.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 end)

            {

                end.printStackTrace();

            }

            return str;

        }

    }

}