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

//package assignment;

import java.io.PrintWriter;

import java.util.*;

public class TreapMap<K extends Comparable<K>, V> implements Treap<K, V> {

    TreapNode<K, V> head;

    @Override

    public V lookup(K key) {

        TreapNode<K, V> tr = lookupH(key);

        if(tr == null) return null;

        else return tr.getValue();

    }

    private TreapNode<K, V> lookupH(K key) {

        TreapNode<K, V> curr = head;

        while (true) {

            if(curr == null) return null;

            int compareVal = curr.getKey().compareTo(key);

            if (compareVal > 0) curr = curr.getLeft();

            else if (compareVal < 0) curr = curr.getRight();

            else return curr;

        }

    }

    public void insert(K key, V value, int prio) {

        TreapNode<K, V> curr = head;

        TreapNode<K, V> toInsert = new TreapNode<>(key, value, prio);

        ArrayList<TreapNode<K, V>> path = new ArrayList<>();

        if(head == null) {

            head = toInsert;

            return;

        }

        while (true) {

            path.add(curr);

            int compareVal = curr.getKey().compareTo(key);

            if (compareVal > 0) {

                if(curr.getLeft() == null) {

                    curr.setLeft(toInsert);

                    break;

                }

                curr = curr.getLeft();

            }

            else if(compareVal == 0 && prio != Treap.MAX_PRIORITY) { // override if we're not adding a split node

                curr.setValue(value);

                return;

            }

            else {

                if(curr.getRight() == null) {

                    curr.setRight(toInsert);

                    break;

                }

                curr = curr.getRight();

            }

        }

        curr = toInsert;

        for(int i = path.size() - 1; i >= 1; i--) {

            if(path.get(i).getPrio() < curr.getPrio()) {

                if(path.get(i - 1).getLeft() == path.get(i) && path.get(i).getLeft() == curr) {

                    rotateLL(path.get(i - 1));

                }

                else if(path.get(i - 1).getLeft() == path.get(i) && path.get(i).getRight() == curr) {

                    rotateLR(path.get(i - 1));

                }

                else if(path.get(i - 1).getRight() == path.get(i) && path.get(i).getLeft() == curr) {

                    rotateRL(path.get(i - 1));

                }

                else if(path.get(i - 1).getRight() == path.get(i) && path.get(i).getRight() == curr) {

                    rotateRR(path.get(i - 1));

                }

                else {

                    System.out.println("insert is BROKEN LOL");

                }

            }

            else break;

        }

        if(head.getPrio() < curr.getPrio()) {

            if(head.getLeft() == curr) {

                head.setLeft(curr.getRight());

                curr.setRight(head);

            }

            else {

                head.setRight(curr.getLeft());

                curr.setLeft(head);

            }

            head = curr;

        }

    }

    @Override

    public void insert(K key, V value) {

        Random r = new Random();

        insert(key, value, r.nextInt(Treap.MAX_PRIORITY));

    }

    @Override

    public V remove(K key) {

        TreapNode<K, V> par = null;

        TreapNode<K, V> curr = head;

        while (true) {

            if(curr == null) return null;

            if(curr.getKey() == null) break; // join case

            int compareVal = curr.getKey().compareTo(key);

            if (compareVal > 0) {

                par = curr;

                curr = curr.getLeft();

            }

            else if (compareVal < 0) {

                par = curr;

                curr = curr.getRight();

            }

            else break;

        }

        while(curr.getLeft() != null || curr.getRight() != null) {

            int lPrio = -1;

            if(curr.getLeft() != null) lPrio = curr.getLeft().getPrio();

            int rPrio = -1;

            if(curr.getRight() != null) rPrio = curr.getRight().getPrio();

            if(rPrio > lPrio) { // swap with right then

                if(par == null) { // curr = head

                    TreapNode<K, V> temp = curr.getRight();

                    assert temp != null;

                    curr.setRight(temp.getLeft());

                    temp.setLeft(curr);

                    head = temp;

                    par = temp;

                }

                else {

                    TreapNode<K, V> temp = curr.getRight();

                    if(par.getLeft() == curr) {

                        par.setLeft(temp);

                    }

                    else {

                        par.setRight(temp);

                    }

                    curr.setRight(temp.getLeft());

                    temp.setLeft(curr);

                    par = temp;

                }

            } else {

                if(par == null) { // curr = head

                    TreapNode<K, V> temp = curr.getLeft();

                    assert temp != null;

                    curr.setLeft(temp.getRight());

                    temp.setRight(curr);

                    head = temp;

                    par = temp;

                }

                else {

                    TreapNode<K, V> temp = curr.getLeft();

                    if(par.getLeft() == curr) {

                        par.setLeft(temp);

                    }

                    else {

                        par.setRight(temp);

                    }

                    curr.setLeft(temp.getRight());

                    temp.setRight(curr);

                    par = temp;

                }

            }

        }

        if(par == null) head = null; // head = node

        else if(par.getLeft() == curr) par.setLeft(null);

        else if(par.getRight() == curr) par.setRight(null);

        return curr.getValue();

    }

    @Override

    public Treap<K, V>[] split(K key) {

        Treap<K, V>[] ans = new TreapMap[2];

        this.insert(key, null, Treap.MAX_PRIORITY);

        TreapMap<K, V> t1 = new TreapMap<>();

        t1.head = head.getLeft();

        TreapMap<K, V> t2 = new TreapMap<>();

        t2.head = head.getRight();

        ans[0] = t1;

        ans[1] = t2;

        return ans;

    }

    @Override

    public void join(Treap<K, V> t) {

        if(!(t instanceof TreapMap)) throw new IllegalArgumentException();

        TreapMap<K, V> tTr = (TreapMap<K, V>) t;

        TreapNode<K, V> joiner = new TreapNode<>(null, null, Treap.MAX_PRIORITY);

        if(tTr.head.getKey().compareTo(this.head.getKey()) < 0) {

            joiner.setLeft(tTr.head);

            joiner.setRight(this.head);

        }

        else {

            joiner.setRight(tTr.head);

            joiner.setLeft(this.head);

        }

        head = joiner;

        remove(null);

    }

    @Override

    public void meld(Treap<K, V> t) throws UnsupportedOperationException {

        if(!(t instanceof TreapMap)) return;

        meldRec(((TreapMap<K, V>) t).head);

    }

    private void meldRec(TreapNode<K, V> curr) {

        if(curr == null) return;

        TreapNode<K, V> oldHead = head;

        this.insert(curr.getKey(), curr.getValue(), curr.getPrio());

        head = this.lookupH(curr.getKey());

        meldRec(curr.getLeft());

        meldRec(curr.getRight());

        head = oldHead;

    }

    @Override

    public void difference(Treap<K, V> t) throws UnsupportedOperationException {

        if(!(t instanceof TreapMap)) return;

        diffRec(((TreapMap<K, V>) t).head);

    }

    private void diffRec(TreapNode<K, V> curr) {

        if(curr == null) return;

        TreapNode<K, V> oldHead = head;

        TreapNode<K, V> tr = this.lookupH(curr.getKey());

        if(tr != null) {

            this.remove(curr.getKey());

            this.head = tr;

        }

        meldRec(curr.getLeft());

        meldRec(curr.getRight());

        head = oldHead;

    }

    @Override

    public Iterator<K> iterator() {

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

        dfs2(arr, head);

        return arr.iterator();

    }

    private void dfs2(ArrayList<K> trav, TreapNode<K, V> curr) {

        if(curr == null) return;

        dfs2(trav, curr.getLeft());

        trav.add(curr.getKey());

        dfs2(trav, curr.getRight());

    }

    @Override

    public double balanceFactor() throws UnsupportedOperationException {

        return 0;

    }

    private void rotateLL(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getLeft();

        TreapNode<K, V> c2 = c1.getLeft();

        TreapNode<K, V> temp = c2.getRight();

        p.setLeft(c2);

        c2.setRight(c1);

        c1.setLeft(temp);

    }

    private void rotateLR(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getLeft();

        TreapNode<K, V> c2 = c1.getRight();

        TreapNode<K, V> temp = c2.getLeft();

        p.setLeft(c2);

        c2.setLeft(c1);

        c1.setRight(temp);

    }

    private void rotateRL(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getRight();

        TreapNode<K, V> c2 = c1.getLeft();

        TreapNode<K, V> temp = c2.getRight();

        p.setRight(c2);

        c2.setRight(c1);

        c1.setLeft(temp);

    }

    private void rotateRR(TreapNode<K, V> p) {

        TreapNode<K, V> c1 = p.getRight();

        TreapNode<K, V> c2 = c1.getRight();

        p.setRight(c2);

        TreapNode<K, V> temp = c2.getLeft();

        c2.setLeft(c1);

        c1.setRight(temp);

    }

    private void dfs(ArrayList<String> trav, TreapNode<K, V> curr) {

        if(curr == null) return;

        trav.add(String.format("[%d] <%s, %s>%n", curr.getPrio(), curr.getKey().toString(), curr.getValue().toString()));

        dfs(trav, curr.getLeft());

        dfs(trav, curr.getRight());

    }

    public String toString() {

        StringBuilder sb = new StringBuilder();

        ArrayList<String> trav = new ArrayList<>();

        dfs(trav, head);

        for(String str : trav) sb.append(str);

        return sb.toString();

    }

    // testing- proof by ac

    // https://codeforces.com/contest/1278/problem/C

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        PrintWriter pw = new PrintWriter(System.out);

        int t = sc.nextInt();

        loop:

        while(t-- > 0) {

            int x = sc.nextInt();

            TreapMap<Integer, Integer> hs = new TreapMap<>();

            for(int i=1;i<=2*x;i++){

                hs.insert(i, 0);

            }

            int[] arr = new int[2*x];

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

                arr[i]=sc.nextInt();

                hs.remove(arr[i]);

            }

            //pw.println(hs);

            for(int i=1;i<2*x;i+=2){

                if(hs.lookup(arr[i-1]+1) != null){

                    arr[i]=arr[i-1]+1;

                    hs.remove(arr[i]);

                }

                else{

                    for(int j=arr[i-1];j<=2*x;j++){

                        if(hs.lookup(j) != null){

                            arr[i]=j;

                            hs.remove(j);

                            break;

                        }

                        if(j==2*x){

                            pw.println(-1);

                            continue loop;

                        }

                    }

                }

            }

            for(int trr : arr){

                pw.print(trr+" ");

            }

            pw.println();

        }

        pw.close();

    }

}

class TreapNode<K, V> {

    private int prio;

    private K key;

    private V value;

    private TreapNode<K, V> left;

    private TreapNode<K, V> right;

    public int getPrio() {

        return prio;

    }

    public V getValue() {

        return value;

    }

    public K getKey() {

        return key;

    }

    public TreapNode<K, V> getLeft() {

        return left;

    }

    public TreapNode<K, V> getRight() {

        return right;

    }

    public void setLeft(TreapNode<K, V> left) {

        this.left = left;

    }

    public void setValue(V value) {

        this.value = value;

    }

    public void setRight(TreapNode<K, V> right) {

        this.right = right;

    }

    public TreapNode(K key, V value, int prio) {

        this.key = key;

        this.value = value;

        this.prio = prio;

    }

    public String toString() {

        return String.format("{%s, %d}", this.key.toString(), prio);

    }

}

interface Treap<K extends Comparable<K>, V> extends Iterable<K> {

    /**

     * The maximum priority that a node can have.

     */

    public static final int MAX_PRIORITY = 65535;

    /**

     * Retrieves the value associated with a key in this dictionary.

     * If the key is null or the key is not present in this

     * dictionary, this method returns null.

     *

     * @param key   the key whose associated value

     *              should be retrieved

     * @return      the value associated with the key, or

     *              null if the key is null or the key is not in

     *              this treap

     */

    V lookup(K key);

    /**

     * Adds a key-value pair to this dictionary.  Any old value

     * associated with the key is lost.  If the key or the value is

     * null, the pair is not added to the dictionary.

     *

     * @param key      the key to add to this dictionary

     * @param value    the value to associate with the key

     */

    void insert(K key, V value);

    /**

     * Removes a key from this dictionary.  If the key is not present

     * in this dictionary, this method does nothing.  Returns the

     * value associated with the removed key, or null if the key

     * is not present.

     *

     * @param key      the key to remove

     * @return         the associated with the removed key, or null

     */

    V remove(K key);

    /**

     * Splits this treap into two treaps.  The left treap should contain

     * values less than the key, while the right treap should contain

     * values greater than or equal to the key.

     *

     * @param key    the key to split the treap with

     * @return       the left treap in index 0, the right in index 1

     */

    Treap<K, V> [] split(K key);

    /**

     * Joins this treap with another treap.  If the other treap is not

     * an instance of the implementing class, both treaps are unmodified.

     * At the end of the join, this treap will contain the result.

     * This method may destructively modify both treaps.

     *

     * @param t    the treap to join with

     */

    void join(Treap<K, V> t);

    /**

     * Melds this treap with another treap.  If the other treap is not

     * an instance of the implementing class, both treaps are unmodified.

     * At the end of the meld, this treap will contain the result.  This

     * method may destructively modify both treaps.

     *

     * If you don't implement this method, just throw an

     * UnsupportedOperationException.

     *

     * @param t    the treap to meld with.  t may be modified.

     */

    void meld(Treap<K, V> t) throws UnsupportedOperationException;

    /**

     * Removes elements from another treap from this treap.  If the

     * other treap is not an instance of the implementing class,

     * both treaps are unmodified.  At the end of the difference,

     * this treap will contain no keys that were in the other

     * treap.  This method may destructively modify both treaps.

     *

     * If you don't implement this method, just throw an

     * UnsupportedOperationException.

     *

     * @param t   a treap containing elements to remove from this

     *            treap.  t may be destructively modified.

     */

    void difference(Treap<K, V> t) throws UnsupportedOperationException;

    /**

     * Build a human-readable version of the treap.

     * Each node in the treap will be represented as

     *

     *     [priority] <key, value>\n

     *

     * Subtreaps are indented one tab over from their parent for

     * printing.  This method prints out the string representations

     * of key and value using the object's toString(). Treaps should

     * be printed in pre-order traversal fashion.

     */

    String toString();

    /**

     * @return a fresh iterator that points to the first element in

     * this assignment.Treap and iterates in sorted order.

     */

    Iterator<K> iterator();

    /**

     * Returns the balance factor of the treap.  The balance factor

     * is the height of the treap divided by the minimum possible

     * height of a treap of this size.  A perfectly balanced treap

     * has a balance factor of 1.0.  If this treap does not support

     * balance statistics, throw an exception.

     *

     * If you don't implement this method, just throw an

     * UnsupportedOperationException.

     */

    double balanceFactor() throws UnsupportedOperationException;

}


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

import java.util.*;

public class Solution

{

     public static void main(String[] args)

     {

          Scanner sc = new Scanner(System.in);

          int testCases = sc.nextInt();

          while(testCases != 0)

          {

               int n = sc.nextInt() * 2;

               int[] arr = new int[n];

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

               {

                    arr[i] = sc.nextInt();

               }

               Arrays.sort(arr);

               int mid = arr.length / 2;

               System.out.println(Math.abs(arr[mid] - arr[mid - 1]));

               testCases -= 1;

          }

          return;

     }

     private static int getPartition(int[] arr)

     {

          Arrays.sort(arr);

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

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

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

          {

               if(i % 2 == 0)

               {

                    left.add(arr[i]);

               }

               else

               {

                    right.add(arr[i]);

               }

          }

          int mid = left.size() / 2;

          return Math.abs(left.get(mid) - right.get(mid));

     }

}


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        long t = sc.nextInt();

        while (t-- > 0) {

            int n = sc.nextInt();

            int arr[] = new int[n];

            long total = 0;

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

                arr[i] = sc.nextInt();

                total += arr[i];

            }

            long sum = 0;

            long maxi = Long.MIN_VALUE;

            ;

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

                sum += arr[i];

                if (sum > maxi) {

                    maxi = sum;

                }

                if (sum < 0) {

                    sum = 0;

                }

            }

            sum = 0L;

            long maxi2 = Long.MIN_VALUE;

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

                sum += arr[i];

                if (sum > maxi2) {

                    maxi2 = sum;

                }

                if (sum < 0) {

                    sum = 0;

                }

            }

            if (total > Math.max(maxi, maxi2)) {

                System.out.println("YES");

            } else {

                System.out.println("NO");

            }

        }

    }

}


A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

import java.io.*;

import java.util.*;

public class Codeforces {

    public static void solve() {

        FastReader input = new FastReader();

        int testcases=input.nextInt();

        while(testcases-->0){

			String str=input.next();

			int first=0,last=0;

			int count1=0,count0=0;

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

				if(str.charAt(i)=='1'){

					count1++;

				}

				else if(str.charAt(i)=='0'){

					count0++;

				}

			}

			if(count1==0||count0==0){

				System.out.println(0);

				}

				else{

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

				if(str.charAt(i)=='1'){

					first=i;

					break;

				}

			}

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

				if(str.charAt(i)=='1'){

					last=i;

					break;

					}

			}

			int count=0;

			for(int i=first;i<=last;i++){

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

					count++;

				}

			}

			System.out.println(count);

		}

		}

    }

    public static void input_output() {

        try {

            System.setIn(new FileInputStream("input.txt"));

            //System.setOut(new PrintStream("output.txt"));

        } catch (Exception e) {

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

        }

    }

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

        if (System.getProperty("ONLINE_JUDGE") == null) {

            input_output();

            solve();

            }

            else {

                solve();

            }

    }

    public static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(

                new InputStreamReader(System.in));

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

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

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

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                if (st.hasMoreTokens()) {

                    str = st.nextToken("\n");

                } else {

                    str = br.readLine();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3
2 0
0 2
2 0
OutputCopyYES
1 2 1 InputCopy5
0 1
1 3
2 1
3 0
2 0
OutputCopyYES
2 3 2 1 2

import java.io.*;

import java.util.*;

import static java.lang.Math.*;

import static java.util.Arrays.*;

public class cf1286b {

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

        int n = ri();

        Node root = null, g[] = new Node[n];

        TreeSet<Integer> set = new TreeSet<>();

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

            g[i] = new Node();

            set.add(i + 1);

        }

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

            int p = rni() - 1, c = ni();

            if(p == -1) {

                root = g[i];

            } else {

                g[p].chd.add(g[i]);

            }

            g[i].c = c + 1;

        }

        boolean yes = root.dfs(set);

        prYN(yes);

        if(yes) {

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

                if(i > 0) {

                    pr(' ');

                }

                pr(g[i].a);

            }

            prln();

        }

        close();

    }

    static class Node {

        List<Node> chd = new ArrayList<>();

        int a, c;

        boolean dfs(TreeSet<Integer> set) {

            Iterator<Integer> iter = set.iterator();

            while(c --> 0) {

                if(!iter.hasNext()) {

                    return false;

                }

                a = iter.next();

            }

            set.remove(a);

            for(Node n : chd) {

                if(!n.dfs(set)) {

                    return false;

                }

            }

            return set.isEmpty() || set.first() > a;

        }

    }

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

    static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));

    static StringTokenizer input;

    static Random rand = new Random();

    // references

    // IBIG = 1e9 + 7

    // IRAND ~= 3e8

    // IMAX ~= 2e10

    // LMAX ~= 9e18

    // constants

    static final int IBIG = 1000000007;

    static final int IRAND = 327859546;

    static final int IMAX = 2147483647;

    static final int IMIN = -2147483648;

    static final long LMAX = 9223372036854775807L;

    static final long LMIN = -9223372036854775808L;

    // util

    static int minof(int a, int b, int c) {return min(a, min(b, c));}

    static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}

    static long minof(long a, long b, long c) {return min(a, min(b, c));}

    static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}

    static int maxof(int a, int b, int c) {return max(a, max(b, c));}

    static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}

    static long maxof(long a, long b, long c) {return max(a, max(b, c));}

    static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}

    static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}

    static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}

    static int floori(double d) {return (int)d;}

    static int ceili(double d) {return (int)ceil(d);}

    static long floorl(double d) {return (long)d;}

    static long ceill(double d) {return (long)ceil(d);}

    static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static <T> void reverse(T[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {T swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}

    static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void shuffle(char[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); char swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}

    static void rsort(int[] a) {shuffle(a); Arrays.sort(a);}

    static void rsort(long[] a) {shuffle(a); Arrays.sort(a);}

    static void rsort(double[] a) {shuffle(a); Arrays.sort(a);}

    static void rsort(char[] a) {shuffle(a); Arrays.sort(a);}

    static <T> void rsort(T[] a) {shuffle(a); Arrays.sort(a);}

    static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}

    // input

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

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

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

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

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

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

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

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

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

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

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

    // output

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}


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

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.Deque;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.PriorityQueue;

import java.util.Queue;

import java.util.Random;

import java.util.Stack;

import java.util.StringTokenizer;

import java.util.TreeMap;

import java.util.TreeSet;

public class hacker49 {

	static class FastReader

    {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(new

                     InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  e)

                {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException e)

            {

                e.printStackTrace();

            }

            return str;

        }

    }

	static long[] x= {1,1,1,0,0,0,-1,-1,-1};

	static long[] y= {1,-1,0,-1,0,1,1,-1,0};

	public static void main(String[] args) {

		OutputStream outputStream =System.out;

	    PrintWriter out =new PrintWriter(outputStream);

		FastReader s=new FastReader();

	long x=s.nextLong();

	long n=s.nextLong();

	if(x>n) {

		System.out.println(-1);

	}else {

	if(n==0 && x==0) {

		System.out.println(0);

	}

	else if(n==x) {

			System.out.println(1);

			System.out.println(x);

		}else if(((n-1)^1) ==x){

			System.out.println(2);

			System.out.println((n-1)+" "+1);

		}

		else if((n-x)%2==0) {

			if(x==0) {

				System.out.println(2);

				System.out.println((n/2)+" "+(n/2));

			}

			else {

				boolean p=false;

				long d=(n^x);

				d/=2;

				long k=n-d;

				if((d^k)==x) {

					System.out.println(2);

					System.out.println(d+" "+k);

				}else {

			System.out.println(3);

			System.out.println(x+" "+(n-x)/2+" "+(n-x)/2);

		}}

	}else {

		System.out.println(-1);

	}

		}

			out.close();

	}

	public static int[] KMP( String str) {

		int[] a=new int[str.length()];

		int j;

		int i;

     for(i=1,j=0;i<str.length();) {

    	 if(str.charAt(i)==str.charAt(j)) {

    		 a[i]=j+1;

    		 j++;

    		 i++;

    	 }else {

    		 if(j!=0) {

    			 j=a[j-1];

    		  }else {

    			 a[j]=0;

    			 i++;

    		 }

    	 }

     }

		return a;

	}

	static int[] k=new int[200001];

	public static void CS(long[] arr,long[] segtree,int low,int high,int pos) {

		if(low==high) {

			segtree[pos]=arr[low];

			return;

		}

		int mid=(low+high)/2;

		CS(arr,segtree,low,mid,2*pos+1);

		CS(arr,segtree,mid+1,high,2*pos+2);

		segtree[pos]=GCD(segtree[2*pos+1],segtree[2*pos+2]);

		}

	public static long RS(long[] segtree,int qlow,int qhigh,int low,int high,int pos) {

		if(low>=qlow && high<=qhigh) {

			return segtree[pos];

		}

		if(qhigh<low || qlow>high) {

			return 0;

		}

		int mid=(low+high)/2;

	return GCD(RS(segtree,qlow,qhigh,low,mid,2*pos+1),RS(segtree,qlow,qhigh,mid+1,high,2*pos+2));

	}

	public static void US(long[] segtree,int low,int high,int pos ,long new_val,int index,long prev_val,int c,int n) {

//		if(index>high || index<low) {

//			return ;

//		}

		if(low==high) {

			segtree[pos]=new_val;

			return;

		}

//		segtree[pos]+=diff;

//		 segtree[pos] = (segtree[pos] ^ prev_val) ^ new_val;

		if(high!=low) {

			int mid=(high+low)/2;

			if(index<=mid) {

			US(segtree,low,mid,2*pos+1,new_val,index,prev_val,c+1,n);}else {

			US(segtree,mid+1,high,2*pos+2,new_val,index,prev_val,c+1,n);}

			if((n-c)%2!=0) {

				segtree[pos]=(segtree[2*pos+1]|segtree[2*pos+2]);

			}else {

				segtree[pos]=(segtree[2*pos+1]^segtree[2*pos+2]);

			}

		}

	}

	static int nextPowerOf2(int n)

	{

	    n--;

	    n |= n >> 1;

	    n |= n >> 2;

	    n |= n >> 4;

	    n |= n >> 8;

	    n |= n >> 16;

	    n++;

	    return n;

	}

	public static int longest_Repeating_Subsequence(String str,int n) {

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

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

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

				if(str.charAt(i-1)==str.charAt(j-1) &&  i!=j) {

					dp[i][j]=1+dp[i-1][j-1];

				}else {

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

				}

			}

		}

		return dp[n][n];

	}

	public static int d1(ArrayList<Integer> e,int n,int i) {

		int l=-1;

		int r=n;

				;

		while(r>l+1) {

			int mid=(l+r)/2;

//			long h=mid^n;

//			System.out.println(e.get(mid)+" "+mid);

			if(e.get(mid)>i) {

				r=mid;

			}else {

				l=mid;

			}

		}

		return r;

	}

	public static int upper_bound(int[] a ,int x,int n) {

		int l=-1;

		int r=n;

		while(r>l+1) {

			int mid=(l+r)/2;

			if(a[mid]>x) {

				r=mid;

			}else {

				l=mid;

			}

		}

		return r;

	}

	public static int lower_bound(long[] a ,long x,int n) {

		int l=-1;

		int r=n;

		while(r>l+1) {

			int mid=(l+r)/2;

			if(a[mid]<=x) {

				l=mid;

			}else {

				r=mid;

			}

		}

		return l;

	}

	static long get=0;

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

//	static int[] dx= {2,2,-2,-2,-1,-1,1,1};

//	static int[] dy= {1,-1,-1,1,-2,2,-2,2};

//	static int[][] vis1=new int[101][101];

//	static boolean valid(int x,int y,int n) {

//		if(x>=1 && x<=n && y>=1 && y<=n) {

//			return true;

//		}

//		return false;

//	}

//	static void dfs(int x,int y,char[][] a,int n,char t) {

//		a[x][y]=t;

//		vis1[x][y]=1;

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

//			if(valid(x+dx[i],y+dy[i],n) && vis1[x+dx[i]][y+dy[i]]==0) {

//				dfs(x+dx[i],y+dy[i],a,n,(t=='W')?'B':'W');

//			}

//		}

//	}

	static int[] par=new int[200001];

	static void bfs() {

		Queue<Integer> q=new LinkedList<>();

		q.add(1);

		vis[1]=1;

		h[1]=1;

		while(!q.isEmpty()) {

			int node=q.poll();

			for(int i=0;i<f1[node].size();i++) {

				if(vis[f1[node].get(i)]==0) {

					q.add(f1[node].get(i));

					vis[f1[node].get(i)]=1;

					h[f1[node].get(i)]=h[node]+1;

					par[f1[node].get(i)]=node;

				}

			}

		}

	}

	static int[] h=new int[200001];

	static int[] subtree=new int[200001];

	static int[] vis=new int[200001];

	static HashMap<Integer,pair> e=new HashMap<>();

	static ArrayList<Integer>[] f1=new ArrayList[200001];

	static PriorityQueue<pair> q=new PriorityQueue<>();

	static ArrayList<pair>[] f=new ArrayList[200001];

//	static void bfs() {

//		Queue<node> q=new LinkedList<>();

//		q.add(new node(1,0));

//		h[1]=0;

//		vis[1]=1;

//		while(!q.isEmpty()) {

//			node p=q.poll();

////			h[p.a]=p.b;

//			for(int i=0;i<f1[p.a].size();i++) {

//				if(vis[f1[p.a].get(i)]==0) {

//					q.add(new node(f1[p.a].get(i),p.b+1));

//					h[f1[p.a].get(i)]=p.b+1;

//					vis[f1[p.a].get(i)]=1;

//				}

//			}

//		}

//	}

	static int dfs(int node) {

		int c=1;

		vis[node]=1;

		for(int i=0;i<f1[node].size();i++) {

			if(vis[f1[node].get(i)]==0) {

				c+=dfs(f1[node].get(i));

			}

		}

		subtree[node]=c;

		return c;

	}

	static void dfs2(int node,int v) {

		vis[node]=1;

		if(ans[node]==1) {

			get+=v;

		}

		for(int i=0;i<f1[node].size();i++) {

			if(vis[f1[node].get(i)]==0) {

				dfs2(f1[node].get(i),v+((ans[node]==0)?1:0));

			}

		}

	}

static long m=-1;

static void sf(long[] min){

        int n = min.length;

        Random rnd = new Random();

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

            long tmp = min[i];

            int randomPos = i + rnd.nextInt(n-i);

            min[i] = min[randomPos];

            min[randomPos] = tmp;

        }

}

	static class pair implements Comparable<pair>{

		private long a;

		private long b;

		private long c;

		pair(long a,long b,long c){

			this.a=a;

//			this.f=f;

			this.b=b;

			this.c=c;

//			this.d=d;

//			this.e=e;

		}

		public int compareTo(pair o) {

			if(o.c!=this.c) {

//			return Integer.compare(o.c, this.c);}

//		else {

				return Long.compare(this.c,o.c);

			}else {

				return Long.compare(this.a*this.b,o.a*o.b);

			}

		}

//

	}

	static class node implements Comparable<node>{

		private long a;

		private long b;

		private long c;

		node(long a,long b,long c){

			this.a=a;

			this.b=b;

			this.c=c;

		}

		public int compareTo(node o) {

//			return Long.compare(arg0, arg1)

			if(this.c!=o.c) {

				return Long.compare(o.c, this.c);

			}else {

				return Long.compare(this.b, o.b);

			}

		}

	}

//	public static int upper_bound(long[] a ,long x,int n) {

//		int l=-1;

//		int r=n;

//		while(r>l+1) {

//			int mid=(l+r)/2;

//			if(a[mid]<x) {

//				l=mid;

//			}else {

//				r=mid;

//			}

//		}

//		return r;

//

//	}

//	public static int lower_bound(long[] a ,long x,int m) {

//		int l=0;

//		int r=m+1;

//		while(r>l+1) {

//			int mid=(l+r)/2;

//			if(a[mid]>=x) {

//				r=mid;

//			}else {

//				l=mid;

//			}

//		}

//		return r;

//

//	}

	public static long lb(int n,long[] pre,long k,long a,long b,long x,long y) {

		long l=0;

		long r=n+1;

		while(l<r) {

			long mid=(l+r)/2;

			long sum=0;

			long gcd=GCD(a,b);

			long g=mid/(a*b/gcd);

			long a1=mid/a;

			long b1=mid/b;

			sum+=(pre[(int) g]*(x+y))/100;

			if(x>=y) {

				sum+=((pre[(int) a1]-pre[(int) g])*x)/100;

				sum+=(((pre[(int)(a1+b1-g)]-pre[(int)(a1)])*y))/100;

			}else {

				sum+=((pre[(int) b1]-pre[(int) g])*y)/100;

				sum+=(((pre[(int)(a1+b1-g)]-pre[(int)(b1)])*x))/100;

			}

			if(sum>=k) {

				r=mid;

			}else {

				l=mid+1;

			}

//			System.out.println(mid+" "+h);

		}

		return r;

	}

	public static long[] merge_sort(long[] A, int start, int end) {

		if (end > start) {

			int mid = (end + start) / 2;

			long[] v = merge_sort(A, start, mid);

			long[] o = merge_sort(A, mid + 1, end);

			return (merge(v, o));

		} else {

			long[] y = new long[1];

			y[0] = A[start];

			return y;

		}

	}

	public static long[] merge(long a[], long b[]) {

		long[] temp = new long[a.length + b.length];

		int m = a.length;

		int n = b.length;

		int i = 0;

		int j = 0;

		int c = 0;

		while (i < m && j < n) {

			if (a[i] < b[j]) {

				temp[c++] = a[i++];

			} else {

				temp[c++] = b[j++];

			}

		}

		while (i < m) {

			temp[c++] = a[i++];

		}

		while (j < n) {

			temp[c++] = b[j++];

		}

		return temp;

	}

	public static int[] Create(int[] a,int n) {

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

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

			int j=i;

			int h=a[i];

			while(i<=n) {

				b[i]+=h;

				i=get_next(i);

			}

			i=j;

		}

		return b;

	}

public static int get_next(int a) {

	return a+(a&-a);

}

public static int get_parent(int a) {

	return a-(a&-a);

}

public static int query_1(int[] b,int index) {

	int sum=0;

	if(index<=0) {

		return 0;

	}

	while(index>0) {

		sum+=b[index];

		index=get_parent(index);

	}

	return sum;

}

public static int query(int[] b,int n,int l,int r) {

	int sum=0;

	sum+=query_1(b,r);

	sum-=query_1(b,l-1);

	return sum;

}

public static void update(int[] a,int[] b,int n,int index,int val) {

	int diff=val-a[index];

	a[index]+=diff;

	while(index<=n) {

		b[index]+=diff;

		index=get_next(index);

	}

}

//	public static void Create(int[] a,pair[] segtree,int low,int high,int pos) {

//		if(low>high) {

//			return;

//		}

//		if(low==high) {

//			segtree[pos].b.add(a[low]);

//			return ;

//		}

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

//		Create(a,segtree,low,mid,2*pos);

//		Create(a,segtree,mid+1,high,2*pos+1);

//		segtree[pos].b.addAll(segtree[2*pos].b);

//		segtree[pos].b.addAll(segtree[2*pos+1].b);

//	}

//	public static void update(pair[] segtree,int low,int high,int index,int pos,int val,int prev) {

//		if(index>high || index<low) {

//			return ;

//		}

//		if(low==high && low==index) {

//			segtree[pos].b.remove(prev);

//			segtree[pos].b.add(val);

//			return;

//		}

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

//			 update(segtree,low,mid,index,2*pos,val,prev);

//			 update(segtree,mid+1,high,index,2*pos+1,val,prev);

//			 segtree[pos].b.clear();

//			  segtree[pos].b.addAll(segtree[2*pos].b);

//			  segtree[pos].b.addAll(segtree[2*pos+1].b);

//

//	}

//	public static pair query(pair[] segtree,int low,int high,int qlow,int qhigh ,int pos) {

//		if(low>=qlow && high<=qhigh) {

//			return segtree[pos];

//		}

//		if(qhigh<low || qlow>high) {

//			return new pair();

//		}

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

//	  pair a1=query(segtree,low,mid,qlow,qhigh,2*pos);

//	  pair a2=query(segtree,mid+1,high,qlow,qhigh,2*pos+1);

//	  pair a3=new pair();

//	  a3.b.addAll(a1.b);

//	  a3.b.addAll(a2.b);

//	  return a3;

//

//	}

//

//	public static int nextPowerOf2(int n)

//	{

//	    n--;

//	    n |= n >> 1;

//	    n |= n >> 2;

//	    n |= n >> 4;

//	    n |= n >> 8;

//	    n |= n >> 16;

//	    n++;

//	    return n;

//	}

//

////	static class pair implements Comparable<pair>{

////		private int a;

////		private long b;

//////		private long c;

////		pair(int a,long b){

////			this.a=a;

////			this.b=b;

//////			this.c=c;

////		}

////		public int compareTo(pair o) {

//////		if(this.a!=o.a) {

//////			return Long.compare(this.a, o.a);

//////		}else {

////			return Long.compare(o.b,this.b);

//////		}

////		}

////	}

//	static class pair implements Comparable<pair>{

//		private int a;

//		private int b;

//		pair(int a,int b){

////			this.b=new HashSet<>();

//			this.a=a;

//			this.b=b;

//		}

//		public int compareTo(pair o) {

//			return Integer.compare(this.b, o.b);

//		}

//	}

	public static int lower_bound(ArrayList<Long> a ,int n,long x) {

		int l=0;

		int r=n;

		while(r>l+1) {

			int mid=(l+r)/2;

			if(a.get(mid)<=x) {

				l=mid;

			}else {

				r=mid;

			}

		}

		return l;

	}

	public static int[] is_prime=new int[10000001];

	public static ArrayList<Long> primes=new ArrayList<>();

 	public static void sieve() {

		long maxN=100000000;

		for(long i=1;i<=maxN;i++) {

			is_prime[(int) i]=1;

		}

		is_prime[0]=0;

		is_prime[1]=0;

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

			if(is_prime[(int) i]==1) {

//				primes.add((int) i);

				for(long j=i*i;j<=maxN;j+=i) {

					is_prime[(int) j]=0;

				}

			}

		}

		for(long i=0;i<=maxN;i++) {

			if(is_prime[(int) i]==1) {

				primes.add(i);

			}

		}

	}

//	public static pair[] merge_sort(pair[] A, int start, int end) {

//		if (end > start) {

//			int mid = (end + start) / 2;

//			pair[] v = merge_sort(A, start, mid);

//			pair[] o = merge_sort(A, mid + 1, end);

//			return (merge(v, o));

//		} else {

//			pair[] y = new pair[1];

//			y[0] = A[start];

//			return y;

//		}

//	}

//	public static pair[] merge(pair a[], pair b[]) {

//		pair[] temp = new pair[a.length + b.length];

//		int m = a.length;

//		int n = b.length;

//		int i = 0;

//		int j = 0;

//		int c = 0;

//		while (i < m && j < n) {

//			if (a[i].b >= b[j].b) {

//				temp[c++] = a[i++];

//

//			} else {

//				temp[c++] = b[j++];

//			}

//		}

//		while (i < m) {

//			temp[c++] = a[i++];

//		}

//		while (j < n) {

//			temp[c++] = b[j++];

//		}

//		return temp;

//	}

	public static long im(long a) {

		return binary_exponentiation_1(a,mod-2)%mod;

	}

	public static long binary_exponentiation_1(long a,long n) {

		long res=1;

		while(n>0) {

			if(n%2!=0) {

				res=((res)%(mod) * (a)%(mod))%(mod);

				n--;

			}else {

				a=((a)%(mod) *(a)%(mod))%(mod);

				n/=2;

			}

		}

		return (res)%(mod);

	}

	public static long b1(long a,long n) {

		long res=1;

		while(n>0) {

			if(n%2!=0) {

				res=((res)%(mod) * (a)%(mod))%(mod);

				n--;

			}else {

				a=((a)%(mod) *(a)%(mod))%(mod);

				n/=2;

			}

		}

		return (res)%(mod);

	}

	public static double bn1(double a,double n) {

		double res=1;

		while(n>0) {

			if(n%2!=0) {

//				res=((res)%(1000000007) * (a)%(1000000007))%(1000000007);

				res=(res*a);

				n--;

			}else {

//				a=((a)%(1000000007) *(a)%(1000000007))%(1000000007);

				a=(a*a);

				n/=2;

			}

		}

		return (res);

	}

	public static long bn(long a,long n) {

		long res=1;

		while(n>0) {

			if(n%2!=0) {

				res=res*a;

				n--;

			}else {

				a*=a;

				n/=2;

			}

		}

		return res;

	}

public static long[] fac=new long[300001];

public static void ff() {

		fac[0]=(long)1;

		fac[1]=(long)1;

		for(long i=2;i<=300000;i++) {

			fac[(int) i]=(fac[(int) (i-1)]*i)%(mod);

		}

	}

public static long mod=1000000007;

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

		if(b==(long)0) {

			return a;

		}

		return GCD(b , a%b);

	}

public static long c=0;

}


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

import java.util.Scanner;

public class CFR620D2 {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        int n=sc.nextInt();

        while(n>0){

            n--;

            int x=sc.nextInt();

            int y=sc.nextInt();

            int a=sc.nextInt();

            int b=sc.nextInt();

           int L=(y-x);

           int jump=a+b;

           if(L%jump==0){

            System.out.println((int)L/jump);

           }else{

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

           }

        }

    }

}


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

import java.util.*;

public class Main

{

	public static void main(String[] args) {

        Scanner s=new Scanner(System.in);

        int n=s.nextInt();

        while(n-->0)

        {

           int a=s.nextInt();

           int b=s.nextInt();

           int c=s.nextInt();

           int q=s.nextInt();

           int target=(a+b+c+q)/3;

           if((a<=target)&&(b<=target)&&(c<=target)&&((a+b+c+q)%3==0))

           {

               System.out.println("YES");

           }

           else

           {

               System.out.println("NO");

           }

        }

}

}


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

import java.math.BigInteger;

import java.util.Scanner;

public class Main {

    public static void main(String[] args){

        Scanner in = new Scanner(System.in);

        int num = in.nextInt();

        int div;

        int radix = 2;

        int res = 0;

        while(radix <= num-1){

            div = num;

            while(div >= radix){

                res += div%radix;

                div /= radix;

            }

            res += div;

            radix += 1;

        }

        int count = num-2;

        int gcd = BigInteger.valueOf(res).gcd(BigInteger.valueOf(count)).intValue();

        System.out.println(res/gcd + "/" + count/gcd);

    }

}


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

import java.util.*;

import java.io.*;

public class Main {

  static StringBuilder sb;

  static dsu dsu;

  static long fact[];

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

  static void solve() {

    int n = i();

    int x = i();

    String str = s();

    int cnt0 = 0;

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

        if(str.charAt(i)=='0') cnt0++;

    }

    int obal = 2*cnt0-n; // cnt0 - cnt1 , cnt0 - (n-cnt0)

    int cbal = 0;

    int ans = 0;

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

        if(obal==0&&cbal==x){

            System.out.println(-1);

            return;

        }

        if(obal!=0&&((x-cbal)%(obal))==0){

            if((x-cbal)/obal>=0){

                ans++;

            }

        }

        if(str.charAt(i)=='0') cbal++;

        else cbal--;

    }

    System.out.println(ans);

  }

  public static void main(String[] args) {

    sb = new StringBuilder();

    int test = i();

    while (test-- > 0) {

      solve();

    }

    System.out.println(sb);

  }

  /*

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

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

   */

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

  static long ncr(int n, int r) {

    if (r > n)

      return (long) 0;

    long res = fact[n] % mod;

    // System.out.println(res);

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

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

    // System.out.println(res);

    return res;

  }

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

  {

    if (y == 0)

      return 1;

    long res = 1;

    while (y > 0) {

      if (y % 2 == 1) {

        res = (res * x) % mod;

        y--;

      }

      x = (x * x) % mod;

      y = y / 2;

    }

    return res;

  }

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

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

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

  static class dsu {

    int parent[];

    dsu(int n) {

      parent = new int[n];

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

        parent[i] = -1;

    }

    int find(int a) {

      if (parent[a] < 0)

        return a;

      else {

        int x = find(parent[a]);

        parent[a] = x;

        return x;

      }

    }

    void merge(int a, int b) {

      a = find(a);

      b = find(b);

      if (a == b)

        return;

      parent[b] = a;

    }

  }

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

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

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

    long num = n;

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

      if (n % i == 0) {

        int nt = 0;

        while (n % i == 0) {

          n = n / i;

          nt++;

        }

        h.put(i, nt);

      }

    }

    if (n != 1)

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

    return h;

  }

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

  static class Pair implements Comparable<Pair> {

    int x;

    long y;

    Pair(int x, long y) {

      this.x = x;

      this.y = y;

    }

    public int compareTo(Pair o) {

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

    }

  }

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

  static class InputReader {

    private InputStream stream;

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

    private int curChar;

    private int numChars;

    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public int read() {

      if (numChars == -1)

        throw new InputMismatchException();

      if (curChar >= numChars) {

        curChar = 0;

        try {

          numChars = stream.read(buf);

        } catch (IOException e) {

          throw new InputMismatchException();

        }

        if (numChars <= 0)

          return -1;

      }

      return buf[curChar++];

    }

    public int Int() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      int sgn = 1;

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

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

          throw new InputMismatchException();

        res *= 10;

        res += c - '0';

        c = read();

      } while (!isSpaceChar(c));

      return res * sgn;

    }

    public String String() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      StringBuilder res = new StringBuilder();

      do {

        res.appendCodePoint(c);

        c = read();

      } while (!isSpaceChar(c));

      return res.toString();

    }

    public boolean isSpaceChar(int c) {

      if (filter != null)

        return filter.isSpaceChar(c);

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

    }

    public String next() {

      return String();

    }

    public interface SpaceCharFilter {

      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

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

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

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

        if (i != 0)

          writer.print(' ');

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

    public void flush() {

      writer.flush();

    }

  }

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

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

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

    int n = a2.length;

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

    for (long i : a2)

      l.add(i);

    Collections.sort(l);

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

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

    return a2;

  }

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

    int n = a2.length;

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

    for (char i : a2)

      l.add(i);

    Collections.sort(l);

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

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

    return a2;

  }

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

    long res = 1;

    while (y > 0) {

      if (y % 2 != 0) {

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

        y--;

      }

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

      y = y / 2;

    }

    return res;

  }

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

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

    if (x == 0)

      return y;

    else

      return gcd(y % x, x);

  }

  // ******LOWEST COMMON MULTIPLE

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

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

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

  }

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

  public static int i() {

    return in.Int();

  }

  public static long l() {

    String s = in.String();

    return Long.parseLong(s);

  }

  public static String s() {

    return in.String();

  }

  public static int[] readArrayi(int n) {

    int A[] = new int[n];

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

      A[i] = i();

    }

    return A;

  }

  public static long[] readArray(long n) {

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

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

      A[i] = l();

    }

    return A;

  }

}


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

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

public class E
{
    static class SegNode
    {
        int lo, hi, mid;
        int sum, id = -1;
        SegNode left, right;

        SegNode(int a, int b)
        {
            lo = a;
            hi = b;
            mid = (lo + hi) / 2;

            if (lo != hi)
            {
                left = new SegNode(lo, mid);
                right = new SegNode(mid+1, hi);
            }
        }

        void set(int pos, int val, int id)
        {
            if (lo == hi)
            {
                sum = val;
                this.id = id;
                return;
            }

            if (pos <= mid)
                left.set(pos, val, id);
            else
                right.set(pos, val, id);

            sum = left.sum + right.sum;
        }

        int sum(int a, int b)
        {
            if (a <= lo && hi <= b)
                return sum;

            int val = 0;

            if (a <= mid)
                val += left.sum(a, Math.min(mid, b));
            if (mid+1 <= b)
                val += right.sum(Math.max(mid+1, a), b);

            return val;
        }

        int getId(int pos)
        {
            if (lo == hi)
                return id;

            if (pos <= mid)
                return left.getId(pos);
            else
                return right.getId(pos);
        }

    }
    static void solve(FastIO io)
    {
        int n = io.nextInt();
        int m = io.nextInt();

        int[] msg = new int[m];
        int[] min = new int[n];
        int[] max = new int[n];

        for (int i = 0; i < n; i++)
            min[i] = max[i] = i;

        for (int i = 0; i < m; i++)
        {
            msg[i] = io.nextInt() - 1;

            min[msg[i]] = 0;
        }

        int[] pos = new int[n];
        SegNode root = new SegNode(0, n + m);

        for (int i = 0; i < n; i++)
        {
            pos[i] = m + i;
            root.set(m+i, 1, i);
        }

        int ptr = m - 1;

        for (int i = 0; i < m; i++)
        {
            int k = msg[i];
            int p = root.sum(0, pos[k] - 1);

            max[k] = Math.max(max[k], p);

            root.set(pos[k], 0, -1);

            pos[k] = ptr--;

            root.set(pos[k], 1, k);
        }

        ptr = 0;

        for (int i = 0; i < n + m; i++)
        {
            int k = root.getId(i);
            if (k != -1)
                max[k] = Math.max(max[k], ptr++);
        }

        for (int i = 0; i < n; i++)
            io.println((min[i] + 1) + " " + (max[i] + 1));
    }

    public static void main(String[] args)
    {
        FastIO io = new FastIO();

        solve(io);

        io.close();
    }

    static class FastIO extends PrintWriter
    {
        StringTokenizer st = new StringTokenizer("");
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

        FastIO()
        {
            super(System.out);
        }

        String next()
        {
            while (!st.hasMoreTokens())
            {
                try {
                    st = new StringTokenizer(r.readLine());
                } catch (Exception e) { }
            }
            return st.nextToken();
        }

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

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

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


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

import java.lang.*;
import java.math.*;
import java.io.*;
import java.security.SecureRandom;
import java.util.*;
public class Main{
    public static int mod=(int)(1e9) + 7;

    public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    public static PrintWriter ot=new PrintWriter(System.out);

    public static int[] take_arr(int n){
        int a[]=new int[n];
        try {
            String s[]=br.readLine().trim().split(" ");
            for(int i=0;i<n;i++)
            a[i]=Integer.parseInt(s[i]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }
    public static List<Integer> take_list(int n){
        List<Integer> a=new ArrayList<>();
        try {
            String s[]=br.readLine().trim().split(" ");
            for(int i=0;i<n;i++)
            a.add(Integer.parseInt(s[i]));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		try{
            int t=1;//Integer.parseInt(br.readLine().trim());

            int cno=1;
            while(t-->0){

                String s[]=br.readLine().trim().split(" ");

                int n = Integer.parseInt(s[0]);
                // int m = Integer.parseInt(s[1]);
                // solve(br.readLine());
                // int k = Integer.parseInt(s[2]);
                // char ch[] = br.readLine().trim().toCharArray();
                // int a[] = take_arr(n);
                // int b[] = take_arr(m);
                // long n = Long.parseLong(s[0]);
                // long m = Long.parseLong(s[1]);
                solve(n);
                // solve()
                // solve(n, m);

                // solve(ch);
            }
            ot.close();
            br.close();
        }catch(Exception e){
            e.printStackTrace();
            return;
        }
    }
    static void solve(int n) throws IOException{
        String s[] = br.readLine().trim().split(" ");
        c = new int[n + 1];
        for(int i = 1; i <= n; i++)
            c[i] = Integer.parseInt(s[i - 1]);
        adj = new ArrayList<>();
        for(int i = 0; i <= n; i++)
            adj.add(new ArrayList<>());
        for(int i = 1; i < n; i++){
            s = br.readLine().trim().split(" ");
            int u = Integer.parseInt(s[0]);
            int v = Integer.parseInt(s[1]);
            adj.get(u).add(v);
            adj.get(v).add(u);
        }
        dp = new int[n + 1];
        ans = new int[n + 1];
        dfs(1, -1);
        dfs2(1, -1);
        for(int i = 1; i <= n; i++)
            ot.print(ans[i] + " ");
        ot.println();
    }
    static void dfs2(int node, int par){
        ans[node] = dp[node];
        for(int ngr : adj.get(node)){
            if(ngr != par){
                dp[node] -= Math.max(0, dp[ngr]);
                dp[ngr] += Math.max(0, dp[node]);
                dfs2(ngr, node);
                dp[ngr] -= Math.max(0, dp[node]);
                dp[node] += Math.max(0, dp[ngr]);
            }
        }
    }
    static int dfs(int node, int par){
        int ans = (c[node] == 0 ? -1 : 1);
        for(int ngr : adj.get(node)){
            if(ngr != par){
               ans += Math.max(0, dfs(ngr, node));
            }
        }
        return dp[node] = ans;
    }
    static int ans[];
    static int c[];
    static int dp[];
    static List<List<Integer>> adj;
}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

import java.io.IOException;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

import java.io.BufferedWriter;

import java.io.OutputStreamWriter;

public class Solution {

    static Reader input = new Reader();

    static int n;

    static int[] a;

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

        n = input.nextInt();

        a = new int[n];

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

            a[i] = input.nextInt();

        }

        long[] dp = new long[n];

        int[] next = new int[n];

        double[] answer = new double[n];

        answer[n-1] = a[n-1];

        next[n-1] = n-1;

        dp[n-1] = a[n-1];

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

            dp[i] = a[i];

            next[i] = i;

            for(int j = i+1; j < n; j = next[j]+1) {

                if(((double)dp[i]/(double)(next[i]-i+1)) >= answer[j]) {

                    next[i] = next[j];

                    dp[i] += dp[j];

                } else break;

            }

            answer[i] = (double)dp[i]/(double)(next[i]-i+1);

        }

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

        int i = 0, j;

        String temp;

        while(i < n) {

            temp = String.format("%.9f", answer[i]);

            for(j = i; j <= next[i]; ++j) {

                writer.write(temp+"\n");

            }

            i = j;

        }

        writer.flush();

    }

    static class Reader {

        BufferedReader reader;

        StringTokenizer string;

        public Reader() {

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

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

    }

}