D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

import java.io.BufferedWriter;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

/**

 *

 * @author kacho

 */

public class Codeforce {

    static class Reader {

        final private int BUFFER_SIZE = 1 << 16;

        private DataInputStream din;

        private byte[] buffer;

        private int bufferPointer, bytesRead;

        public Reader()

        {

            din = new DataInputStream(System.in);

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public Reader(String file_name) throws IOException

        {

            din = new DataInputStream(new FileInputStream(file_name));

            buffer = new byte[BUFFER_SIZE];

            bufferPointer = bytesRead = 0;

        }

        public String readLine() throws IOException

        {

            byte[] buf = new byte[64]; // line length

            int cnt = 0, c;

            while ((c = read()) != -1)

            {

                if (c == '\n')

                    break;

                buf[cnt++] = (byte) c;

            }

            return new String(buf, 0, cnt);

        }

        public int nextInt() throws IOException

        {

            int ret = 0;

            byte c = read();

            while (c <= ' ')

                c = read();

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

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

            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

        {

            if (din == null)

                return;

            din.close();

        }

    }

    static int n;

    static int arr[][][];

    static char res[][];

    /**

     * @param args the command line arguments

     */

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

        Reader rd = new Reader();

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new

         FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);

        n = rd.nextInt();

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

        res = new char[n][n];

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

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

                arr[i][j][0] = rd.nextInt();

                arr[i][j][1] = rd.nextInt();

            }

        }

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

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

                if (arr[i][j][0] == -1) {

                    if (res[i][j] != '\u0000') continue;

                    if (i < n - 1 && arr[i + 1][j][0] == -1) {

                        res[i][j] = 'D';

                        res[i + 1][j] = 'U';

                    } else if (j < n - 1 && arr[i][j + 1][0] == -1) {

                        res[i][j] = 'R';

                        res[i][j + 1] = 'L';

                    } else if (i > 0 && arr[i - 1][j][0] == -1) {

                        res[i][j] = 'U';

                        res[i - 1][j] = 'D';

                    } else if (j > 0 && arr[i][j - 1][0] == -1) {

                        res[i][j] = 'L';

                        res[i][j - 1] = 'R';

                    } else {

                        System.out.println("INVALID");

                        return;

                    }

                } else if (i == arr[i][j][0] - 1 && j == arr[i][j][1] - 1) {

                    dfs(arr[i][j][0] - 1, arr[i][j][1] - 1, 'X');

                }

            }

        }

        for (char[] charr : res) {

            for (char ch : charr)

                if (ch == '\u0000') {

                    System.out.println("INVALID");

                    return;

                }

        }

        System.out.println("VALID");

        for (char[] charr : res) {

            for (char ch : charr)

                out.write(ch);

            out.write('\n');

        }

        out.flush();

    }

    static void dfs(int i, int j, char ch) {

        if (res[i][j] != '\u0000') return;

        res[i][j] = ch;

        if (i < n - 1 && arr[i + 1][j][0] == arr[i][j][0] && arr[i + 1][j][1] == arr[i][j][1])

            dfs(i + 1, j, 'U');

        if (j < n - 1 && arr[i][j + 1][0] == arr[i][j][0] && arr[i][j + 1][1] == arr[i][j][1])

            dfs(i, j + 1, 'L');

        if (i > 0 && arr[i - 1][j][0] == arr[i][j][0] && arr[i - 1][j][1] == arr[i][j][1])

            dfs(i - 1, j, 'D');

        if (j > 0 && arr[i][j - 1][0] == arr[i][j][0] && arr[i][j - 1][1] == arr[i][j][1])

            dfs(i, j - 1, 'R');

    }

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

import java.util.*;

public class AddOddSubEven {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        while (t-- > 0) {

            long a = sc.nextLong();

            long b = sc.nextLong();

            if (a == b)

                System.out.println(0);

            else {

                long sub = b - a;

                if (sub > 0) {

                    if (sub % 2 != 0)

                        System.out.println(1);

                    else

                        System.out.println(2);

                } else {

                    if (sub % 2 == 0)

                        System.out.println(1);

                    else

                        System.out.println(2);

                }

            }

        }

    }

}


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

import java.io.*;

import java.util.*;

public class CF1303C {

    static String alp = "abcdefghijklmnopqrstuvwxyz";

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

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

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

        Outer:

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

            String s = in.readLine();

            String result = ""+s.charAt(0);

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

                char c = s.charAt(i);

                char d = s.charAt(i-1);

                int idx1 = result.indexOf(c);

                int idx2 = result.indexOf(d);

                if (idx1 == idx2) {

                    System.out.println("NO");

                    continue Outer;

                }

                if (idx1 < 0) {

                    if (idx2 == 0) result = c+result;

                    else if (idx2 == result.length()-1) result += c;

                    else {

                        System.out.println("NO");

                        continue Outer;

                    }

                }

                else {

                    if (Math.abs(idx1-idx2) != 1) {

                        System.out.println("NO");

                        continue Outer;

                    }

                }

            }

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

                if (!result.contains(""+alp.charAt(i))) result += alp.charAt(i);

            }

            System.out.println("YES");

            System.out.println(result);

        }

    }

}


A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.

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

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

    static class AAnuHasAFunction {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int[] a = in.nextIntArray(n);
            int[] bits = new int[32];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < 32; j++) {
                    if ((a[i] & (1 << j)) > 0) {
                        bits[j]++;
                    }
                }
            }
//        out.println(bits);
            int max = -1;
            for (int j = 31; j >= 0; j--) {
                if (bits[j] == 1) {
                    max = j;
                    break;
                }
            }
//        out.println(max);
            int[] ans = new int[n];
            if (max == -1) {
                ans = a;
            } else {
                int first = -1;
                for (int i = 0; i < n; i++) {
                    if ((a[i] & (1 << max)) > 0) {
                        first = a[i];
                        break;
                    }
                }
//            out.println(first,"first");
                int j = 1;
                if (max != -1 && first != -1) {
                    ans[0] = first;
                    for (int i = 0; i < n; i++) {
                        if (a[i] != first && first != 0) {
                            ans[j++] = a[i];
                        }
                    }
                } else {
                    Arrays.sort(a);
                    out.println(a);
                }

            }

            out.println(ans);
        }

    }

    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 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 int[] nextIntArray(int n) {
            int[] array = new int[n];
            for (int i = 0; i < n; ++i) array[i] = nextInt();
            return array;
        }

        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(int[] array) {
            for (int i = 0; i < array.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(array[i]);
            }
        }

        public void println(int[] array) {
            print(array);
            writer.println();
        }

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

    }
}


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.

/**

 * 10/31/21 night

 * https://codeforces.com/problemset/problem/13/A

 */

// package codeforce.practice.L1000;

import java.util.*;

import java.io.*;

public class A13 {

    static PrintWriter pw;

    void solve(int a) {

        int res = 0, divide = a - 2;

        for (int base = 2; base < a; base++) {

            int sum = sumOfDigit(a, base);

            res += sum;

        }

        int g = gcd(res, divide);

        res /= g;

        divide /= g;

        pr(res + "/" + divide);

    }

    int sumOfDigit(int x, int base) {

        int res = 0;

        while (x > 0) {

            res += x % base;

            x /= base;

        }

        return res;

    }

    int gcd(int a, int b) {

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

    }

    private void run() {

        // read_write_file(); // comment this before submission

        FastScanner fs = new FastScanner();

        int a = fs.nextInt();

        solve(a);

    }

    private final String INPUT = "input.txt";

    private final String OUTPUT = "output.txt";

    void read_write_file() {

        FileInputStream instream = null;

        PrintStream outstream = null;

        try {

            instream = new FileInputStream(INPUT);

            outstream = new PrintStream(new FileOutputStream(OUTPUT));

            System.setIn(instream);

            System.setOut(outstream);

        } catch (Exception e) {

        }

    }

    public static void main(String[] args) {

        pw = new PrintWriter(System.out);

        new A13().run();

        pw.close();

    }

    void pr(int num) {

        pw.println(num);

    }

    void pr(long num) {

        pw.println(num);

    }

    void pr(double num) {

        pw.println(num);

    }

    void pr(String s) {

        pw.println(s);

    }

    void pr(char c) {

        pw.println(c);

    }

    class FastScanner {

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

        StringTokenizer st = new StringTokenizer("");

        String next() {

            while (!st.hasMoreTokens())

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        int[] readArray(int n) {

            int[] a = new int[n];

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

                a[i] = nextInt();

            return a;

        }

        Integer[] readIntegerArray(int n) {

            Integer[] a = new Integer[n];

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

                a[i] = nextInt();

            return a;

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

    }

    void tr(Object... o) {

        pw.println(Arrays.deepToString(o));

    }

}


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 Solution{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        int test_cases = sc.nextInt();

        outer : for(int h=0;h<test_cases;h++){

            long x = sc.nextLong();

            long y = sc.nextLong();

            long a = sc.nextLong();

            long b = sc.nextLong();

            if((y-x)%(a+b)!=0){

                System.out.println(-1);

            }

            else{

                System.out.println((int)(y-x)/(a+b));

            }

        }

    }

    public static int calculate_gcd(int x,int y){

        int gcd = 1;

        if(x%y==0){

            return y;

        }

        else if(y%x==0){

            return x;

        }

        else{

            for(int i=2;i<=x && i<=y;i++){

                if(x%i==0 && y%i==0){

                    gcd = i;

                }

            }

            return gcd;

        }

    }

    public static long calculate_factorial(long x){

        long ans = 1;

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

            ans*=i;

        }

        return ans;

    }

    public static void swap(int a[], int b[], int index_a, int index_b){

        int temp = a[index_a];

        a[index_a] = b[index_b];

        b[index_b] = temp;

    }

    public static long find_maximum(long a[]){

        long max = Long.MIN_VALUE;

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

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

        }

        return max;

    }

    public static long find_minimum(long a[]){

        long min = Long.MAX_VALUE;

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

            min = Math.min(a[i], min);

        }

        return min;

    }

}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

import java.util.*;

import java.math.*;

import java.io.*;

public class Main {

	static ArrayList<Integer> prime = new ArrayList<>();

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

	static ArrayList<Integer> arr;

	static ArrayList<Long> prefix;

	static ArrayList<Long> pre = new ArrayList<>();

	static final long LMAX = 9223372036854775807L;

	static ArrayList<Integer> arr1 = new ArrayList<>();

	static ArrayList<ArrayList<Integer>> vis = new ArrayList<>();

	static int dr[] = {1, 0, -1, 0};

	static int dc[] = {0, -1, 0, 1};

	static class FastReader {

		BufferedReader br;

		StringTokenizer st;

		public FastReader() {

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

		}

		String next() {

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

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

			} catch (Exception e) {

				e.printStackTrace();

			}

			return str;

		}

	}

	static class FastWriter {

		private final BufferedWriter bw;

		public FastWriter() {

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

		}

		public void print(Object object) throws IOException {

			bw.append("" + object);

		}

		public void println(Object object) throws IOException {

			print(object);

			bw.append("\n");

		}

		public void close() throws IOException {

			bw.close();

		}

	}

	public static class Pair {

		int first;

		int second;

		Pair(int first , int second ) {

			this.first = first ;

			this.second = second;

		}

	}

	public static void main(String[] args) {

		try {

			FastReader in = new FastReader();

			FastWriter out = new FastWriter();

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

			// 		@Override public int compare(Pair o1, Pair o2) {

			// 			if (o1.second < o2.second ) { // change (>) for desending order

			// 				return -1;

			// 			} else if (o1.second == o2.second ) {

			// 				return 0;

			// 			} else {

			// 				return 1;

			// 			}

			// 		}

			// 	});

			// int testcases = in.nextInt();

			int testcases = 1;

			while ( testcases -- > 0 ) {

				long ans1 = 0, ans2 = 0, ans3 = 0, ans4 = 0;

				double n = in.nextDouble();

				double ans = 0.0 ;

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

					double x = (double) 1 / i ;

					ans += x ;

					// out.print(x);

				}

				out.println(ans);

			}

			out.close();

		} catch (Exception e) {

			return;

		}

	}

	private static void dfs(int i, int j , int  n , int m , char arr[][] ) {

		if  ( arr[i][j] == '#' ) return ;

		arr[i][j] = '#';

		// ~~~~~

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

			int x = dr[k] + i;

			int y = dc[k] + j;

			if ( x >= 0 && x < n && y >= 0 && y < m && arr[x][y] == '.'  ) {

				dfs(x, y, n , m , arr );

			}

		}

		// ~~~~~

	}

	private static void bfs( Stack<Pair> q, char[][] arr , int[][] vis ) {

		int n = arr.length;

		int m = arr[0].length;

		while (!q.isEmpty()) {

			int i = q.peek().first;

			int j = q.peek().second;

			vis[i][j] = 1;

			q.pop();

			int dr[] = {1, 0, -1, 0};

			int dc[] = {0, -1, 0, 1};

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

				int x = dr[k] + i;

				int y = dc[k] + j;

				if ( x >= 0 && x < n && y >= 0 && y < m  && arr[x][y] == '.' && vis[x][y] != 1 ) {

					q.add(new Pair(x, y));

				}

			}

		}

	}

	public static boolean isSatisfy( ArrayList<Integer> arr , int l , int r ) {

		int ans = 0;

		if ( l == 0 || arr.get(l) < arr.get(l - 1) ) ans++;

		if ( r == arr.size() - 1 || arr.get(r) < arr.get(r + 1) ) ans++;

		if ( ans == 2 ) return true;

		return false;

	}

	public static ArrayList<Long> prefixSum() {

		int mod = 100000;

		// ArrayList<Integer> arr ;

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

		long prev = 0;

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

			prev += i;

			prefix.add(prev);

		}

		return prefix;

	}

	public static long sumRem(int x ) {

		if ( x <= 1 ) return 1;

		return x + sumRem(x - 1);

	}

	public static boolean isSquare( int n ) {

		int sqrt = (int) Math.sqrt(n);

		return (sqrt * sqrt == n );

	}

	public static void swap ( int l , int r , ArrayList<Integer> a ) {

		int t = a.get(l) ;

		a.add(l, a.get(r) );

		a.add(r, t);

	}

	public static void fib( int a , int b , int n) {

		int x = Math.floorMod(a, mod);

		int y = Math.floorMod(b, mod);

		arr = new ArrayList<>();

		arr.add(a);

		arr.add(b);

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

			int cur = Math.floorMod((y - x), mod);

			x = y;

			y = cur;

			arr.add(y);

		}

	}

	public static String reverseString( String s1 ) {

		String s = "";

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

			s += s1.charAt(i);

		}

		return s;

	}

	public static long countSetBits(long n) {

		long count = 0;

		while (n > 0) {

			count += n & 1;

			n >>= 1;

		}

		return count;

	}

	public static void sortbykey(HashMap<Long, Long> map) {

		TreeMap<Long, Long> sorted = new TreeMap<>();

		sorted.putAll(map);

	}

	public static long sum(int n) {

		if ( n <= 1 ) return n;

		return n + sum(n - 1);

	}

	public static ArrayList<Long> prefix( ArrayList<Long> arr1 ) {

		Collections.sort(arr1);

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

		long prefix = 0;

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

			prefix += arr1.get(i);

			arr.add(prefix);

		}

		return arr;

	}

	public static int solve(int[][] m, int n) {

		int ans = 0;

		int vis[][] = new int[n][n];

		int di[] = {1, 0, 0, -1};

		int dj[] = {0, -1, 1, 0};

		if (m[0][0] == 1) mazerunner(0, 0, m, n, ans, "", vis, di, dj);

		return ans;

	}

	public static void mazerunner(int i, int j, int m[][], int n, int ans, String move, int vis[][], int di[] , int dj[]) {

		if ( i == n - 1 && j == n - 1) {

			ans++;

			return;

		}

		String dir = "DLRU";

		for (int ind = 0; ind < 4; ind++) {

			int nexti = i + di[ind];

			int nextj = j + dj[ind];

			if (nexti >= 0 && nextj >= 0 && nexti < n && nextj < n && vis[nexti][nextj] == 0 && m[nexti][nextj] == 1) {

				vis[i][j] = 0;

				mazerunner(nexti, nextj, m, n, ans, move + dir.charAt(ind), vis, di, dj);

				vis[i][j] = -1;

			}

		}

	}

	public static long pow( long k , long n ) {

		long ans = 1;

		while ( n > 0 ) {

			if ( n % 2 == 1 ) {

				ans = (ans * k) % mod;

				n--;

			} else {

				k = (k * k) % mod;

				n /= 2;

			}

		}

		return ans % mod;

	}

	public static long fact(long n ) {

		long ans = 0;

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

			ans += (long)i;

		}

		return ans;

	}

	public static boolean isValid( long mid, long arr[] , long k ) {

		long req = 0;

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

			req += Math.min( (arr[i] - arr[i - 1] ) , mid );

		}

		req += mid;

		if ( req >= k ) return true;

		return false;

	}

	public static String sortString(String inputString) {

		char tempArray[] = inputString.toCharArray();

		Arrays.sort(tempArray);

		return new String(tempArray);

	}

	private static void reverse( ArrayList<Long> arr , int i, int j ) {

		while ( i <= j ) {

			swap( arr, i, j);

			i++; j--;

		}

	}

	private static void swap( ArrayList<Long> arr , int i, int j ) {

		long temp = arr.get(i);

		arr.set(i, arr.get(j));

		arr.set(j, temp);

	}

	private static boolean isPrime(long n ) {

		if ( n == 1 ) return true;

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

			if ( n % i == 0 ) {

				return false ;

			}

		}

		return true;

	}

	private static boolean[] sieve() {

		int n = 100000000;

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

		Arrays.fill(sieve, true);

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

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

				sieve[j] = false;

			}

		}

		return sieve;

	}

	private static ArrayList<Integer> generatePrimes(int n ) {

		boolean sieve[] = sieve();

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

			if ( sieve[i] == true ) {

				prime.add(i);

			}

		}

		return prime;

	}

	private static void segmentedSieve( int l  , int r ) {

		int n = (int) Math.sqrt(r);

		ArrayList<Integer> pr = generatePrimes(n);

		int dummy[] = new int[r - l + 1];

		Arrays.fill(dummy, 1);

		for ( int p : pr ) {

			int firstMultiple = (l / p) * p;

			if ( firstMultiple < l ) firstMultiple += p;

			for ( int j = Math.max(firstMultiple, p * p); j <= r; j += p) {

				dummy[j - l] = 0;

			}

		}

		for ( int i = l; i <= r; i++) {

			if ( dummy[i - l] == 1 ) {

				System.out.println(i);

			}

		}

	}

	private static int[] primeFactors() {

		int n = 1000000;

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

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

			prime[i] = i;

		}

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

			if ( prime[i] == i ) {

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

					if ( prime[j] == j ) {

						prime[j] = i;

					}

				}

			}

		}

		return prime;

	}

	private static boolean isPalindrome(String s ) {

		int i = 0, j = s.length() - 1;

		while ( i <= j ) {

			if ( s.charAt(i) != s.charAt(j) ) {

				return false;

			}

			i++; j--;

		}

		return true;

	}

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

		long ans = 1;

		while ( b > 0 ) {

			if ( (b & 1) != 0 ) {

				ans = binMultiply(ans, a);

			}

			a = binMultiply(a, a );

			b >>= 1;

		}

		return ans;

	}

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

		long ans = 0;

		while ( b > 0 ) {

			if ( (b & 1) != 0 ) {

				ans = (ans + a % mod ); // if  m is given in ques than use ans = ans+a % m ;

			}

			a = (a + a) % mod; // if m is given in ques than use a = (a+a)%m;

			b >>= 1;

		}

		return ans;

	}

	private static int GCD ( int a , int b ) {

		if ( b == 0) return a;

		return GCD( b , a % b);

	}

	private static int binarySearch(int l , int r , int[] arr , int find ) {

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

		if ( arr[mid] == find ) {

			return mid;

		} else if ( arr[mid] > find ) {

			return binarySearch(l, mid - 1, arr, find);

		}

		return binarySearch(mid + 1, r, arr, find);

	}

	private static int upper_bound(ArrayList<Integer> arr , int element ) {

		int l = 0 ;

		int h = arr.size() - 1;

		int mid = 0;

		while ( h - l > 1 ) {

			mid = (h + l) / 2;

			if ( arr.get(mid) <=  element ) {

				l = mid + 1;

			} else {

				h = mid ;

			}

		}

		if ( arr.get(l) > element ) return l;

		if ( arr.get(h) > element ) return h;

		return -1;

	}

	private static int lower_bound( long arr[] , long element ) {

		int l = 0 ;

		int h = arr.length - 1;

		int mid = 0;

		while ( h - l > 1 ) {

			mid = (h - l) / 2;

			if ( arr[mid] < element ) {

				l = mid + 1;

			} else {

				h = mid ;

			}

		}

		if ( arr[l] >= element ) return l;

		if ( arr[h] >= element ) return h;

		return -1;

	}

}

class DisjointSet {

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

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

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

	public DisjointSet(int n ) {

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

			rank.add(0);

			parent.add(i);

			size.add(1);

		}

	}

	public int findUPar(int node ) {

		if ( node == parent.get(node) ) return node;

		int ulp = findUPar(parent.get(node));

		parent.set(node, ulp);

		return parent.get(node);

	}

	public void unionBySize(int u, int v) {

		int ulp_u = findUPar(u);

		int ulp_v = findUPar(v);

		if ( ulp_u == ulp_v ) return ;

		if ( size.get(ulp_u) < size.get(ulp_v) ) {

			parent.set(ulp_u, ulp_v);

			size.set(ulp_v, size.get(ulp_v) + size.get(ulp_u) );

		} else {

			parent.set(ulp_v, ulp_u);

			size.set(ulp_u, size.get(ulp_v) + size.get(ulp_u) );

		}

	}

	public void unionByRank(int u, int v) {

		int ulp_u = findUPar(u);

		int ulp_v = findUPar(v);

		if ( ulp_u == ulp_v ) return ;

		if ( rank.get(ulp_u) < rank.get(ulp_v) ) {

			parent.set(ulp_u, ulp_v);

		} else if ( rank.get(ulp_v) < rank.get(ulp_u) ) {

			parent.set(ulp_v, ulp_u);

		} else {

			parent.set(ulp_v, ulp_u);

			int rankU = rank.get(ulp_u);

			rank.set(ulp_u, rankU + 1);

		}

	}

}

class Pair {

	int first;

	int second;

	Pair(int first , int second ) {

		this.first = first ;

		this.second = second;

	}

}


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

/*

1

2 3

 */

public class D {

	static int ind1, ind2;

	public static void main(String[] args) {

		FastScanner fs=new FastScanner();

		int n=fs.nextInt(), m=fs.nextInt();

		int[][] arrays=new int[n][m];

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

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

				arrays[i][j]=fs.nextInt();

		int low=0, high=1000_000_001;

		while (low!=high) {

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

			if (possible(mid, arrays, n, m)) {

				low=mid;

			}

			else {

				high=mid-1;

			}

		}

		possible(low, arrays, n, m);

		System.out.println(ind1+" "+ind2);

	}

	static boolean possible(int min, int[][] arrays, int n, int m) {

		boolean[] possible=new boolean[1<<m];

		int[] used=new int[1<<m];

		int arrayInd=0;

		for (int[] a:arrays) {

			arrayInd++;

			int mask=0;

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

				if (a[i]>=min) mask+=1<<i;

			possible[mask]=true;

			used[mask]=arrayInd;

		}

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

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

				if (possible[i]&&possible[j]&&((i|j)==((1<<m)-1))) {

					ind1=used[i];

					ind2=used[j];

					return true;

				}

		return false;

	}

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreElements())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

	}

}


import java.util.*;

import java.io.*;

public class perfectkeyboard {

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

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

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

		while (t-- > 0) {

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

			String str = st.nextToken();

			boolean[] vis = new boolean[26];

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

			boolean ispos = true;

			int ix = -1;

			for (char ch : str.toCharArray()) {

				if (vis[ch - 'a']) {

					if (ix - 1 >= 0 && res.get(ix - 1) == ch)

						ix--;

					else if (ix + 1 < res.size() && res.get(ix + 1) == ch)

						ix++;

					else {

						ispos = false;

						break;

					}

				} else {

					if (ix + 1 == res.size()) {

						res.add(ch);

						ix++;

					} else if (ix == 0) {

						res.add(0, ch);

						ix = 0;

					} else {

						ispos = false;

						break;

					}

					vis[ch - 'a'] = true;

				}

				if (!ispos)

					break;

			}

			if (!ispos) {

				pw.println("NO");

			} else {

				pw.println("YES");

				for (char ch : res) {

					pw.print(ch);

				}

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

					if (!vis[i]) {

						pw.print((char) (i + 'a'));

					}

				}

				pw.println();

			}

		}

		pw.close();

	}

}


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

import java.util.*;
public class Game23 {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        int a= sc.nextInt();
        int b= sc.nextInt();
        int count=0;
        if(b%a!=0){
            System.out.println(-1);
            return;
        }
        int x=b/a;
        while(x%3==0){
            count++;
            x=x/3;
        }
        while(x%2==0){
            count++;
            x=x/2;
        }
        if(x!=1){
            System.out.println(-1);
            return;
        }
        System.out.println(count);
    }
}


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

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int t=1;

//		t=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

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

			int n= f.nextInt();

			int[] a=f.readArray(n);

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

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

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

				dp[i][i]=a[i];

			}

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

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

					dp[i][j]=-1;

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

						if(dp[i][k]!=-1 && dp[i][k]==dp[k+1][j])

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

					}

				}

			}

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

				dp2[i]=Integer.MAX_VALUE;

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

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

						dp2[i]=Math.min(dp2[i], dp2[j]+1);

					}

				}

			}

			System.out.println(dp2[n]);

		}

		out.close();

	}

	static void sort(long[] p) {

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

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

        Collections.sort(q);

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

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}

//Some things to notice

//Check for the overflow

//Binary Search

//Bitmask

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


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

import java.io.*;

import java.util.*;

public class HelloWorld{

    static class Step{

        long no;

        String comm;

        Step(long no, String comm){

            this.no = no;

            this.comm = comm;

        }

    }

    private static ArrayList<Step> ls;

    private static long k;

    private static void check(){

        if(k > 0)   return;

        PrintWriter pw = new PrintWriter(System.out);

        pw.println("YES");

        pw.println(ls.size());

        for(Step step : ls)

            pw.println(+step.no+" "+step.comm);

        pw.flush();

        pw.close();

        System.exit(0);

    }

    private static void addStep(long no, String comm){

        if(no == 0 || comm.length() == 0)

            return;

        Step ns = new Step(no, comm);

        ls.add(ns);

        k -= no*comm.length();

        check();

        //System.out.println(+k);

    }

    public static void main(String []args){

        Scanner sc = new Scanner(System.in);

        int r = sc.nextInt(), c = sc.nextInt();

        k = sc.nextLong();

        long max = 4*r*c-2*r-2*c;

        if(k > max){

            System.out.println("NO");

            System.exit(0);

        }

        ls = new ArrayList<>();

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

            String sdir = (i%2 == 0)?"R":"L";

            long lim = Math.min(k, c-1);

            //System.out.println(+lim+" "+sdir);

            addStep(lim, sdir);

            if(i != r-1)

                addStep(1, "D");

        }

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

            String sdir = ((i+r)%2 == 1)?"UDL":"UDR";

            long lim = Math.min(k, 3*(c-1));

            addStep(lim/3, sdir);

            addStep(1, sdir.substring(0, (int)(lim%3)));

            addStep(1, "U");

        }

        addStep(k, "L");

    }

}


A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2
3
4
OutputCopy7
11

/* package codechef; // don't place package name! */

import java.util.*;

import java.lang.*;

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */

public class Codechef

{

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

	{

		// your code goes here

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		while(t-->0)

		{

		    long n=sc.nextLong();

		    while(n>1)

		    {

		    if(n%2==0)

		    {

		         System.out.print(1);

		         n=n-2;

		    }

		    else if(n==3)

		    {System.out.print("7");

		    break;}

		    else if (n%2==1)

		    {

		         n=n-3;

		         System.out.print("7");

		         n=n/2;

		         while(n-->0)

		         {

		              System.out.print("1");

		         }

		         break;

		    }

		    }

		    System.out.println();

		}

	}

}


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

// package codeforce.cf617;

import java.io.PrintWriter;

import java.util.*;

public class E2 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        PrintWriter pw = new PrintWriter(System.out);

//        int t = sc.nextInt();

        int t = 1;

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

            solve(sc, pw);

        }

        pw.close();

    }

    static void solve(Scanner in, PrintWriter out){

        int n = in.nextInt();

        char[] cs = in.next().toCharArray();

        int[] dp = new int[26];

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

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

            int idx = cs[i] - 'a';

            int state = 0;

            for (int j = idx + 1; j < 26; j++) {

                state |= dp[j];

            }

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

                if ((state | (1 << j)) != state){

                    ans.add(j + 1);

                    dp[idx] |= (1 << j);

                    break;

                }

            }

        }

        int st = 0;

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

            st |= dp[i];

        }

        int cnt = 0;

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

            if ((st | (1 << i)) == st){

                cnt++;

            }

        }

        out.println(cnt);

        for(int x : ans){

            out.print(x+" ");

        }

        out.println();

    }

    // Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2

    // worst case since it uses a version of quicksort. Although this would never

    // actually show up in the real world, in codeforces, people can hack, so

    // this is needed.

    static void ruffleSort(int[] a) {

        //ruffle

        int n=a.length;

        Random r=new Random();

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

            int oi=r.nextInt(n), temp=a[i];

            a[i]=a[oi];

            a[oi]=temp;

        }

        //then sort

        Arrays.sort(a);

    }

}


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

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int ttt=1;

//		ttt=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

		outer:for(int tt=0;tt<ttt;tt++) {

			int n=f.nextInt();

			double[] a=new double[n];

			for(int i=0;i<n;i++) a[i]=f.nextDouble();

			Stack<double[]> stack = new Stack();

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

				double sum = a[i];

				int len = 1;

				while (!stack.isEmpty()) {

					double[] top = stack.peek();

					if (sum / len > top[0]) {

						sum += top[0] * top[1];

						len += top[1];

						stack.pop();

					} else

						break;

				}

				double curr = sum / len;

				stack.push(new double[] { curr, len });

			}

			while (!stack.isEmpty()) {

				double[] curr = stack.pop();

				while (curr[1]-- > 0)

					out.println(curr[0]);

			}

		}

		out.close();

	}

	static void sort(int[] p) {

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

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

        Collections.sort(q);

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

    }

    static long gcd(long a,long b) {

    	if(a==0) return b;

    	return gcd(b%a,a);

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}


A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8
))((())(
OutputCopy6
InputCopy3
(()
OutputCopy-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.

import java.util.*;

import java.io.*;

public class Practice {
	static boolean multipleTC = false;
	FastReader in;
	PrintWriter out;

	final static int mod = 1000000007;
	final static int mod2 = 998244353;
	final double E = 2.7182818284590452354;
	final double PI = 3.14159265358979323846;
	int MAX = 100005;

	public static void main(String[] args) throws Exception {
		new Practice().run();
	}

	void run() throws Exception {
		in = new FastReader();
		out = new PrintWriter(System.out);
		int T = (multipleTC) ? ni() : 1;
		pre();
		for (int t = 1; t <= T; t++)
			solve(t);
		out.flush();
		out.close();
	}

	void pre() throws Exception {
	}

	// All the best
	void solve(int TC) throws Exception {
		int n = ni();
		char s[] = nln().toCharArray();
		int open = 0, close = 0;
		for (int i = 0; i < n; i++) {
			if (s[i] == '(') {
				open++;
			} else {
				close++;
			}
		}
		if (open != close) {
			pn("-1");
		} else {
			open = 0;
			close = 0;
			int res = 0;
			Stack<pair> st = new Stack<>();
			for (int i = 0; i < n; i++) {
				if (s[i] == ')' && !st.isEmpty() && st.peek().x == '(') {
					st.pop();
					if (s[i] == '(') {
						open++;
					} else {
						close++;
					}
					if (st.isEmpty()) {
						open = close = 0;
					}
				} else {
					st.push(new pair(s[i], i));
					if (s[i] == '(') {
						open++;
					} else {
						close++;
					}
					if (open == close) {

						res += (open + close);
						open = close = 0;
						st.clear();
					}
				}
			}
			pn(res);
		}
	}

	class pair {
		char x;
		int y;

		pair(char x, int y) {
			this.x = x;
			this.y = y;
		}

		@Override
		public String toString() {
			return "(" + x + "," + y + ")";
		}

	}

	int[] readArr(int n) throws Exception {
		int arr[] = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = ni();
		}
		return arr;
	}

	void sort(int arr[]) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < arr.length; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = 0; i < arr.length; i++)
			arr[i] = list.get(i);
	}

	public long max(long... arr) {
		long max = arr[0];
		for (long itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public int max(int... arr) {
		int max = arr[0];
		for (int itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public long min(long... arr) {
		long min = arr[0];
		for (long itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public int min(int... arr) {
		int min = arr[0];
		for (int itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public long sum(long... arr) {
		long sum = 0;
		for (long itr : arr)
			sum += itr;
		return sum;
	}

	public long sum(int... arr) {
		long sum = 0;
		for (int itr : arr)
			sum += itr;
		return sum;
	}

	String bin(long n) {
		return Long.toBinaryString(n);
	}

	String bin(int n) {
		return Integer.toBinaryString(n);
	}

	static int bitCount(int x) {
		return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
	}

	static void dbg(Object... o) {
		System.err.println(Arrays.deepToString(o));
	}

	int bit(long n) {
		return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
	}

	int abs(int a) {
		return (a < 0) ? -a : a;
	}

	long abs(long a) {
		return (a < 0) ? -a : a;
	}

	void p(Object o) {
		out.print(o);
	}

	void pn(Object o) {
		out.println(o);
	}

	void pni(Object o) {
		out.println(o);
		out.flush();
	}

	String n() throws Exception {
		return in.next();
	}

	String nln() throws Exception {
		return in.nextLine();
	}

	int ni() throws Exception {
		return Integer.parseInt(in.next());
	}

	long nl() throws Exception {
		return Long.parseLong(in.next());
	}

	double nd() throws Exception {
		return Double.parseDouble(in.next());
	}

	class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		public FastReader(String s) throws Exception {
			br = new BufferedReader(new FileReader(s));
		}

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

		String nextLine() throws Exception {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				throw new Exception(e.toString());
			}
			return str;
		}
	}
}


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

import java.io.*;

import java.math.*;

import java.util.*;

// @author : Dinosparton

public class test {

	static class Pair {

		Double x;

		int y;

		Pair(Double x, int y) {

			this.x = x;

			this.y = y;

		}

	}

	static class Compare {

		void compare(Pair arr[], int n) {

			// Comparator to sort the pair according to second element

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

				@Override

				public int compare(Pair p1, Pair p2) {

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

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

					} else {

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

					}

//		            	return Double.compare(a[0], b[0]);

				}

			});

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

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

//		        }

//		        System.out.println();

		}

	}

	static class Scanner {

		BufferedReader br;

		StringTokenizer st;

		public Scanner() {

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

		}

		String next() {

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

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		String nextLine() {

			String str = "";

			try {

				str = br.readLine();

			} catch (IOException e) {

				e.printStackTrace();

			}

			return str;

		}

	}

	static int dp[][][][];

	static int recursion(int p[], int index,int odd,int even,int last) {

		if (index == p.length) {

			return 0;

		}

		if(dp[index][odd][even][last] != -1) {

			return dp[index][odd][even][last];

		}

		if(p[index] == 0) {

			int pos1 = 1000;

			int pos2 = 1000;

			if(odd > 0) {

				 pos1 = (last!=0 && last == 1 ? 0 : 1) + recursion(p,index+1,odd-1,even,1);

			}

			if(even > 0) {

				 pos2 = (last!=0 && last == 2 ? 0 : 1) + recursion(p,index+1,odd,even-1,2);

			}

			return dp[index][odd][even][last] = Math.min(pos1, pos2);

		}

		return dp[index][odd][even][last] = (last!=0 && last == p[index] ? 0 : 1) + recursion(p,index+1,odd,even,p[index]);

	}

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

		Scanner sc = new Scanner();

		StringBuilder res = new StringBuilder();

		int tc = 1;

		while (tc-- > 0) {

			int n = sc.nextInt();

			int p[] = new int[n];

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

				p[i] = sc.nextInt();

			}

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

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

				if (p[i] != 0) {

					visit[p[i]] = true;

				}

			}

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

				if (p[i] == 0) {

					continue;

				} else {

					p[i] = (p[i] % 2 == 0) ? 2 : 1;

				}

			}

			int odd = 0;

			int even = 0;

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

				if (!visit[i]) {

					if (i % 2 == 0) {

						even++;

					} else {

						odd++;

					}

				}

			}

			dp = new int[n+1][odd + 1][even + 1][3];

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

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

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

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

							dp[i][j][k][l] = -1;

						}

					}

				}

			}

//            System.out.println(odd);

			res.append(recursion(p, 0,odd,even,0) - 1 + "\n");

		}

		System.out.println(res);

	}

}