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

public class Codeforces {

    public static class FastWriter {

        private static final int BUF_SIZE = 1 << 13;

        private final byte[] buf = new byte[BUF_SIZE];

        private final OutputStream out;

        private int ptr = 0;

        private FastWriter() {

            out = null;

        }

        public FastWriter(OutputStream os) {

            this.out = os;

        }

        public FastWriter(String path) {

            try {

                this.out = new FileOutputStream(path);

            } catch (FileNotFoundException e) {

                throw new RuntimeException("FastWriter");

            }

        }

        public FastWriter write(byte b) {

            buf[ptr++] = b;

            if (ptr == BUF_SIZE) innerflush();

            return this;

        }

        public FastWriter write(char c) {

            return write((byte) c);

        }

        public FastWriter write(char[] s) {

            for (char c : s) {

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

                if (ptr == BUF_SIZE) innerflush();

            }

            return this;

        }

        public FastWriter write(String s) {

            s.chars().forEach(c -> {

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

                if (ptr == BUF_SIZE) innerflush();

            });

            return this;

        }

        private static int countDigits(int l) {

            if (l >= 1000000000) return 10;

            if (l >= 100000000) return 9;

            if (l >= 10000000) return 8;

            if (l >= 1000000) return 7;

            if (l >= 100000) return 6;

            if (l >= 10000) return 5;

            if (l >= 1000) return 4;

            if (l >= 100) return 3;

            if (l >= 10) return 2;

            return 1;

        }

        public FastWriter write(int x) {

            if (x == Integer.MIN_VALUE) {

                return write((long) x);

            }

            if (ptr + 12 >= BUF_SIZE) innerflush();

            if (x < 0) {

                write((byte) '-');

                x = -x;

            }

            int d = countDigits(x);

            for (int i = ptr + d - 1; i >= ptr; i--) {

                buf[i] = (byte) ('0' + x % 10);

                x /= 10;

            }

            ptr += d;

            return this;

        }

        private static int countDigits(long l) {

            if (l >= 1000000000000000000L) return 19;

            if (l >= 100000000000000000L) return 18;

            if (l >= 10000000000000000L) return 17;

            if (l >= 1000000000000000L) return 16;

            if (l >= 100000000000000L) return 15;

            if (l >= 10000000000000L) return 14;

            if (l >= 1000000000000L) return 13;

            if (l >= 100000000000L) return 12;

            if (l >= 10000000000L) return 11;

            if (l >= 1000000000L) return 10;

            if (l >= 100000000L) return 9;

            if (l >= 10000000L) return 8;

            if (l >= 1000000L) return 7;

            if (l >= 100000L) return 6;

            if (l >= 10000L) return 5;

            if (l >= 1000L) return 4;

            if (l >= 100L) return 3;

            if (l >= 10L) return 2;

            return 1;

        }

        public FastWriter write(long x) {

            if (x == Long.MIN_VALUE) {

                return write("" + x);

            }

            if (ptr + 21 >= BUF_SIZE) innerflush();

            if (x < 0) {

                write((byte) '-');

                x = -x;

            }

            int d = countDigits(x);

            for (int i = ptr + d - 1; i >= ptr; i--) {

                buf[i] = (byte) ('0' + x % 10);

                x /= 10;

            }

            ptr += d;

            return this;

        }

        public FastWriter write(double x, int precision) {

            if (x < 0) {

                write('-');

                x = -x;

            }

            x += Math.pow(10, -precision) / 2;

            //		if(x < 0){ x = 0; }

            write((long) x).write(".");

            x -= (long) x;

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

                x *= 10;

                write((char) ('0' + (int) x));

                x -= (int) x;

            }

            return this;

        }

        public FastWriter writeln(char c) {

            return write(c).writeln();

        }

        public FastWriter writeln(int x) {

            return write(x).writeln();

        }

        public FastWriter writeln(long x) {

            return write(x).writeln();

        }

        public FastWriter writeln(double x, int precision) {

            return write(x, precision).writeln();

        }

        public FastWriter write(int... xs) {

            boolean first = true;

            for (int x : xs) {

                if (!first) write(' ');

                first = false;

                write(x);

            }

            return this;

        }

        public FastWriter write(long... xs) {

            boolean first = true;

            for (long x : xs) {

                if (!first) write(' ');

                first = false;

                write(x);

            }

            return this;

        }

        public FastWriter writeln() {

            return write((byte) '\n');

        }

        public FastWriter writeln(int... xs) {

            return write(xs).writeln();

        }

        public FastWriter writeln(long... xs) {

            return write(xs).writeln();

        }

        public FastWriter writeln(char[] line) {

            return write(line).writeln();

        }

        public FastWriter writeln(char[]... map) {

            for (char[] line : map) write(line).writeln();

            return this;

        }

        public FastWriter writeln(String s) {

            return write(s).writeln();

        }

        private void innerflush() {

            try {

                out.write(buf, 0, ptr);

                ptr = 0;

            } catch (IOException e) {

                throw new RuntimeException("innerflush");

            }

        }

        public void flush() {

            innerflush();

            try {

                out.flush();

            } catch (IOException e) {

                throw new RuntimeException("flush");

            }

        }

        public FastWriter print(byte b) {

            return write(b);

        }

        public FastWriter print(char c) {

            return write(c);

        }

        public FastWriter print(char[] s) {

            return write(s);

        }

        public FastWriter print(String s) {

            return write(s);

        }

        public FastWriter print(int x) {

            return write(x);

        }

        public FastWriter print(long x) {

            return write(x);

        }

        public FastWriter print(double x, int precision) {

            return write(x, precision);

        }

        public FastWriter println(char c) {

            return writeln(c);

        }

        public FastWriter println(int x) {

            return writeln(x);

        }

        public FastWriter println(long x) {

            return writeln(x);

        }

        public FastWriter println(double x, int precision) {

            return writeln(x, precision);

        }

        public FastWriter print(int... xs) {

            return write(xs);

        }

        public FastWriter print(long... xs) {

            return write(xs);

        }

        public FastWriter println(int... xs) {

            return writeln(xs);

        }

        public FastWriter println(long... xs) {

            return writeln(xs);

        }

        public FastWriter println(char[] line) {

            return writeln(line);

        }

        public FastWriter println(char[]... map) {

            return writeln(map);

        }

        public FastWriter println(String s) {

            return writeln(s);

        }

        public FastWriter println() {

            return writeln();

        }

    }

    static final class InputReader {

        private final InputStream stream;

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

        private int curChar;

        private int numChars;

        public InputReader(InputStream stream) {

            this.stream = stream;

        }

        private int read() throws IOException {

            if (curChar >= numChars) {

                curChar = 0;

                numChars = stream.read(buf);

                if (numChars <= 0) {

                    return -1;

                }

            }

            return buf[curChar++];

        }

        public final int readInt() throws IOException {

            return (int) readLong();

        }

        public final long readLong() throws IOException {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

                if (c == -1) throw new IOException();

            }

            boolean negative = false;

            if (c == '-') {

                negative = true;

                c = read();

            }

            long res = 0;

            do {

                res *= 10;

                res += c - '0';

                c = read();

            } while (!isSpaceChar(c));

            return negative ? -res : res;

        }

        public final int[] readIntArray(int size) throws IOException {

            int[] array = new int[size];

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

                array[i] = readInt();

            }

            return array;

        }

        public final long[] readLongArray(int size) throws IOException {

            long[] array = new long[size];

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

                array[i] = readLong();

            }

            return array;

        }

        public final String readString() throws IOException {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            StringBuilder res = new StringBuilder();

            do {

                res.append((char) c);

                c = read();

            } while (!isSpaceChar(c));

            return res.toString();

        }

        private boolean isSpaceChar(int c) {

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

        }

    }

    static long mulmod(long a, long b,

                       long mod) {

        long res = 0; // Initialize result

        a = a % mod;

        while (b > 0) {

            // If b is odd, add 'a' to result

            if (b % 2 == 1) {

                res = (res + a) % mod;

            }

            // Multiply 'a' with 2

            a = (a * 2) % mod;

            // Divide b by 2

            b /= 2;

        }

        // Return result

        return res % mod;

    }

    static long pow(long a, long b, long MOD) {

        long x = 1, y = a;

        while (b > 0) {

            if (b % 2 == 1) {

                x = (x * y);

                if (x > MOD) x %= MOD;

            }

            y = (y * y);

            if (y > MOD) y %= MOD;

            b /= 2;

        }

        return x;

    }

    static long[] f = new long[200001];

    static long InverseEuler(long n, long MOD) {

        return pow(n, MOD - 2, MOD);

    }

    static long C(int n, int r, long MOD) {

        return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD;

    }

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

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

    public static class Pair {

        public int a;

        public int b;

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Pair pair = (Pair) o;

            return a == pair.a &&

                    b == pair.b;

        }

        @Override

        public int hashCode() {

            return Objects.hash(a, b);

        }

        public Pair(int a, int b) {

            this.a = a;

            this.b = b;

        }

    }

    static class Pair2 {

        public long cost;

        int node;

        public Pair2(long cos, int node) {

            this.cost = cos;

            this.node = node;

        }

    }

    static long compute_hash(String s) {

        int p = 31;

        int m = 1000000007;

        long hash_value = 0;

        long p_pow = 1;

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

            char c = s.charAt(i);

            hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;

            p_pow = (p_pow * p) % m;

        }

        return hash_value;

    }

    public static class SegmentTree {

        long[][] tree;

        int n;

        public SegmentTree(int[] nodes) {

            tree = new long[nodes.length * 4][2];

            n = nodes.length;

            build(0, n - 1, 0, nodes);

        }

        private void build(int l, int r, int pos, int[] nodes) {

            if (l == r) {

                tree[pos][0] = nodes[l];

                tree[pos][1] = l;

                return;

            }

            int mid = (l + r) / 2;

            build(l, mid, 2 * pos + 1, nodes);

            build(mid + 1, r, 2 * pos + 2, nodes);

            if (tree[2 * pos + 1][0] > tree[2 * pos + 2][0]) {

                tree[pos][1] = tree[2 * pos + 1][1];

            } else {

                tree[pos][1] = tree[2 * pos + 2][1];

            }

            tree[pos][0] = Math.max(tree[2 * pos + 1][0], tree[2 * pos + 2][0]);

        }

        //        public void update(int pos, int val) {

        //            updateUtil(0, n - 1, 0, pos, val);

        //        }

        public long[] get(int l, int r) {

            return getUtil(0, n - 1, 0, l, r);

        }

        private long[] getUtil(int l, int r, int pos, int ql, int qr) {

            if (ql > r || qr < l) {

                return new long[]{-1, -1};

            }

            if (l >= ql && r <= qr) {

                return tree[pos];

            }

            int mid = (l + r) / 2;

            long[] left = getUtil(l, mid, 2 * pos + 1, ql, qr);

            long[] right = getUtil(mid + 1, r, 2 * pos + 2, ql, qr);

            long choice = right[1];

            if (left[0] > right[0]) choice = left[1];

            return new long[]{Math.max(left[0], right[0]), choice};

        }

        //        private void updateUtil(int l, int r, int pos, int i, int val) {

        //            if (i < l || i > r) {

        //                return;

        //            }

        //            if (l == r) {

        //                tree[pos] = val;

        //                return;

        //            }

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

        //            updateUtil(l, mid, 2 * pos + 1, i, val);

        //            updateUtil(mid + 1, r, 2 * pos + 2, i, val);

        //            tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];

        //        }

    }

    static int counter = 0;

    static int[] rIn;

    static int[] rOut;

    static int[] lIn;

    static int[] lOut;

    private static int[] flatten;

    private static int[] lFlatten;

    static long answer = 0;

    static int VISITED = 1;

    static int VISITING = 2;

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

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

    public static class Pair22 {

        int num, pos;

        public Pair22(int x, int y) {

            this.num = x;

            this.pos = y;

        }

    }

    public static long sumofdig(long n) {

        long sum = 0;

        while (n > 0) {

            sum += n % 10;

            n /= 10;

        }

        return sum;

    }

    public static class DK {

        int D, K;

        public DK(int d, int k) {

            D = d;

            K = k;

        }

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            DK dk = (DK) o;

            return D == dk.D &&

                    K == dk.K;

        }

        @Override

        public int hashCode() {

            return Objects.hash(D, K);

        }

    }

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

        //https://i...content-available-to-author-only...e.com/ebRGa6

        InputReader in = new InputReader(System.in);

        FastWriter out = new FastWriter(System.out);

//

//        f[0] = 1;

//        f[1] = 1;

//        for (int i = 2; i < 200001; ++i) {

//            f[i] = f[i-1] * i;

//            f[i] %= 100000000000000007L;

//        }

        int t = 1;

        while (t-- > 0) {

            int n = in.readInt();

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

            for (int i = 0; i < n; ++i) g.add(new ArrayList<>());

            int[] cost = new int[n];

            int parent = 0;

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

                int from = i;

                int to = in.readInt();

                cost[i] = in.readInt();

                to--;

                if (to != -1) {

                    g.get(from).add(to);

                    g.get(to).add(from);

                } else {

                    parent = i;

                }

            }

            List<Integer> val = dfs(g, parent, -1, cost);

            if (val.size() != n) {

                System.out.println("NO");

            } else {

                System.out.println("YES");

                int[] ans = new int[n];

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

                    ans[val.get(i)] = i + 1;

                }

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

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

                }

            }

            out.flush();

        }

    }

    private static List<Integer> dfs(List<List<Integer>> g, int cur, int last, int[] cost) {

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

        for (int i = 0; i < g.get(cur).size(); ++i) {

            int ntb = g.get(cur).get(i);

            if (ntb != last) {

                nodes.addAll(dfs(g, ntb, cur, cost));

            }

        }

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

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

            if (cost[cur] == i) {

                ans.add(cur);

                ans.add(nodes.get(i));

            } else {

                ans.add(nodes.get(i));

            }

        }

        if (cost[cur] == nodes.size()) {

            ans.add(cur);

        }

        if (cost[cur] > nodes.size()) {

            return new ArrayList<>();

        }

        return ans;

    }

//    private static Pair22 dfss(List<LinkedHashSet<Integer>> g, int node, HashSet<Integer> vis, int[] dis, int[] dis2) {

//        if (vis.contains(node)) return new Pair22(dis[node], dis2[node], -1);

//        vis.add(node);

//        int min = dis[node];

//        for (Integer ntb : g.get(node)) {

//            if (dis[ntb] > dis[node])

//                dfss(g, ntb, vis, dis, dis2);

//            if (dis[ntb] <= dis[node]) {

//                min = Math.min(min, dis[ntb]);

//            } else {

//                min = Math.min(min, dis2[ntb]);

//            }

//        }

//        //        if (dis)

//        dis2[node] = min;

//        return new Pair22(dis[node], min, -1);

//    }

    private static int solver(int[] nums, int pos, int[] dp) {

        if (pos >= nums.length) return 0;

        if (dp[pos] != Integer.MAX_VALUE) return dp[pos];

        int min = solver(nums, pos + 2, dp) + nums[pos];

        min = Math.min(solver(nums, pos + 3, dp) + nums[pos], min);

        if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 3, dp));

        if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 4, dp));

        //        System.out.println(pos + " " + min);

        return dp[pos] = min;

    }

    static int countFreq(String pattern, String text) {

        int m = pattern.length();

        int n = text.length();

        int res = 0;

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

            int j;

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

                if (text.charAt(i + j) != pattern.charAt(j)) {

                    break;

                }

            }

            if (j == m) {

                res++;

                j = 0;

            }

        }

        return res;

    }

    private static void dfsR(List<List<Integer>> g, int node, int[] v) {

        rIn[node] = counter;

        flatten[counter++] = v[node];

        for (int i = 0; i < g.get(node).size(); ++i) {

            dfsR(g, g.get(node).get(i), v);

        }

        rOut[node] = counter;

        flatten[counter++] = v[node] * -1;

    }

    private static void dfsL(List<List<Integer>> g, int node, int[] v) {

        lIn[node] = counter;

        lFlatten[counter++] = v[node];

        for (int i = 0; i < g.get(node).size(); ++i) {

            dfsL(g, g.get(node).get(i), v);

        }

        lOut[node] = counter;

        lFlatten[counter++] = v[node] * -1;

        TreeMap<String, Integer> map = new TreeMap<>();

    }

    private static void preprocess(int pos, int[][] pre, List<List<Integer>> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) {

        tin[pos] = counter++;

        traverse[depth] = pos;

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

            pre[pos][i] = traverse[depth - (1 << i)];

        }

        for (int i = 0; i < tree.get(pos).size(); ++i) {

            if (tree.get(pos).get(i) != last)

                preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout);

        }

        tout[pos] = counter++;

    }

    static long gcd(long a, long b) {

        while (b != 0) {

            long t = a;

            a = b;

            b = t % b;

        }

        return a;

    }

    static long lcm(long a, long b) {

        return a * b / gcd(a, b);

    }

    static boolean submit = true;

    static void debug(String s) {

        if (!submit)

            System.out.println(s);

    }

    static void debug(int s) {

        LinkedHashSet<Integer> exist = new LinkedHashSet<>();

            /*

            4 2 3 _ 2 4 3 _

             */

    }

}


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 :

import java.io.*;

import java.util.*;

public class Main {

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

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

	static int n, grid[][], dx[], dy[];

	static Pair adj[][];

	static boolean valid(int r, int c) {

		return r >= 0 && r < n && c >= 0 && c < n;

	}

	static boolean dfs(int r, int c) {

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

			int nr = r + dx[i], nc = c + dy[i];

			if (valid(nr, nc) && adj[nr][nc].r == -2) {

				grid[r][c] = i;

				return true;

			}

		}

		return false;

	}

	static void dfs2(int r, int c) {

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

			int nr = r + dx[i], nc = c + dy[i];

			if (valid(nr, nc) && grid[nr][nc] == -1) {

				if (adj[nr][nc].r == adj[r][c].r && adj[nr][nc].c == adj[r][c].c) {

					grid[nr][nc] = (i + 2) % 4;

					dfs2(nr, nc);

				}

			}

		}

	}

	static void bfs(Pair p) {

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

		q.add(p);

		while (!q.isEmpty()) {

			Pair u = q.poll();

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

				int nr = u.r + dx[i], nc = u.c + dy[i];

				if (valid(nr, nc) && grid[nr][nc] == -1) {

					if (adj[nr][nc].r == adj[u.r][u.c].r && adj[nr][nc].c == adj[u.r][u.c].c) {

						grid[nr][nc] = (i + 2) % 4;

						q.add(new Pair(nr,nc));

					}

				}

			}

		}

	}

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

		n = sc.nextInt();

		grid = new int[n][n];

		adj = new Pair[n][n];

		dx = new int[] { 0, 1, 0, -1 };

		dy = new int[] { 1, 0, -1, 0 };

		for (int[] arr : grid)

			Arrays.fill(arr, -1);

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

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

				adj[i][j] = new Pair(sc.nextInt() - 1, sc.nextInt() - 1);

			}

		}

		boolean flag = true;

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

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

				if (grid[i][j] == -1) {

					if (adj[i][j].r == -2) {

						flag &= dfs(i, j);

					} else {

						if (adj[i][j].r == i && adj[i][j].c == j) {

							grid[i][j] = 4;

							bfs(new Pair(i,j));

						}

					}

				}

			}

		}

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

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

				if (grid[i][j] == -1)

					flag = false;

			}

		}

		out.println(flag ? "VALID" : "INVALID");

		if (flag) {

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

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

					int x = grid[i][j];

					if (x == 0)

						out.print("R");

					else if (x == 1)

						out.print("D");

					else if (x == 2)

						out.print("L");

					else if (x == 3)

						out.print("U");

					else

						out.print("X");

				}

				out.println();

			}

		}

		out.close();

	}

	static class Pair {

		int r, c;

		public Pair(int r, int c) {

			this.r = r;

			this.c = c;

		}

	}

}

class Scanner {

	StringTokenizer st;

	BufferedReader br;

	public Scanner(InputStream system) {

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

	}

	public Scanner(String file) throws Exception {

		br = new BufferedReader(new FileReader(file));

	}

	public String next() throws IOException {

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

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

		return st.nextToken();

	}

	public String nextLine() throws IOException {

		return br.readLine();

	}

	public int nextInt() throws IOException {

		return Integer.parseInt(next());

	}

	public double nextDouble() throws IOException {

		return Double.parseDouble(next());

	}

	public Long nextLong() throws IOException {

		return Long.parseLong(next());

	}

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.*;

import static java.lang.Double.parseDouble;

import static java.lang.Integer.parseInt;

import static java.lang.Long.parseLong;

import static java.lang.System.in;

import static java.lang.System.out;

public class SolutionE extends Thread {

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(new

                                            InputStreamReader(in));

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return parseInt(next());

        }

        long nextLong() {

            return parseLong(next());

        }

        double nextDouble() {

            return parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    private static final FastReader scanner = new FastReader();

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

    public static void main(String[] args) {

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

    }

    public void run() {

        solve();

        out.close();

    }

    private static void solve() {

        int n = scanner.nextInt();

        int[] a = new int[n];

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

            a[i] = scanner.nextInt();

        }

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

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

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

                if (l + size > n) {

                    break;

                }

                int r = l + size;

                dp[l][r] = -1;

                if (size == 1) {

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

                    continue;

                }

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

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

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

                    }

                }

            }

        }

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

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

            int minValue = 2000;

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

                minValue = 1;

            }

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

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

                    int value = 1 + dp2[j];

                    minValue = Math.min(minValue, value);

                }

            }

            dp2[i] = minValue;

        }

        out.println(dp2[n]);

    }

}


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

// package c1324;

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

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

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

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

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

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

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

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

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

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

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

  static class MyScanner {
    BufferedReader br;
    StringTokenizer st;

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

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

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

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


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String s = input.nextLine();

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

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

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

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

        }

        int q = input.nextInt();

        while (q-- != 0) {

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

            int distinct = 0;

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

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

            }

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

                System.out.println("No");

            } else {

                System.out.println("Yes");

            }

        }

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

    static long n;

    static int m;

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

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

        Reader input = new Reader();

        StringBuilder output = new StringBuilder();

        int t = input.nextInt();

        while(t > 0) {

            n = input.nextLong();

            m = input.nextInt();

            a = new int[m];

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

            long sum = 0;

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

            if(sum < n) {

                output.append(-1);

            } else {

                output.append(solve());

            }

            --t;

            output.append("\n");

        }

        System.out.print(output);

    }

    static long solve() {

        map = new int[30];

        v = new int[30];

        v[0] = 1;

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

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

        }

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

            int left = 0, right = 30, middle;

            while(left < right) {

                middle = left+right>>1;

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

                    ++map[middle];

                    break;

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

                    right = middle;

                } else {

                    left = middle+1;

                }

            }

        }

        needs = new int[30];

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

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

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

        }

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

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

                map[i] -= needs[i];

                needs[i] = 0;

            } else {

                needs[i] -= map[i];

                map[i] = 0;

            }

        }

        long count = 0;

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

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

                map[i] -= needs[i];

                needs[i] = 0;

                if(i+1 < 30) {

                    int temp = map[i]/2;

                    map[i+1] += temp;

                    map[i] -= temp*2;

                }

            } else {

                needs[i] -= map[i];

                map[i] = 0;

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

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

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

                            ++map[k];

                            ++count;

                        }

                        ++map[i];

                        --map[j];

                        break;

                    }

                }

                --i;

            }

        }

        return count;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

    static int n;

    static int[] a;

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

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

        Reader input = new Reader();

        n = input.nextInt();

        a = new int[n];

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

            a[i] = input.nextInt();

        }

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

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

            used[a[i]] = true;

        }

        int evens = 0, odds = 0;

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

            if(!used[i]) {

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

                else ++odds;

            }

        }

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

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

    }

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

        if(p >= n) {

            return 0;

        }

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

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

        }

        int answer = n+1;

        if(a[p] != 0) {

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

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

        } else {

            if(evens > 0) {

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

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

                answer = Math.min(test, answer);

            }

            if(odds > 0) {

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

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

                answer = Math.min(test, answer);

            }

        }

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

        return answer;

    }

    static class Reader {

        BufferedReader bufferedReader;

        StringTokenizer string;

        public Reader() {

            InputStreamReader inr = new InputStreamReader(System.in);

            bufferedReader = new BufferedReader(inr);

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public double nextDouble() throws IOException {

            return Double.parseDouble(next());

        }

        public String nextLine() throws IOException {

            return bufferedReader.readLine();

        }

    }

}


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

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int t=1;

//		t=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

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

			int n=f.nextInt();

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

			int[] dp=new int[26];

			int[] ans=new int[n];

			int a1=0;

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

				int cd=1;

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

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

				a1=Math.max(cd, a1);

				ans[i]=cd;

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

			}

			System.out.println(a1);;

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

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

			System.out.println();

		}

		out.close();

	}

	static void sort(int[] p) {

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

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

        Collections.sort(q);

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

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

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

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

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

			return a;

		}

	}

}

//Some things to notice

//Check for the overflow

//Binary Search

//Bitmask

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


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

import java.io.*;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashSet;

import java.util.StringTokenizer;

public class Hyperset {

    static int mod = 1000000007;

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

        FastReader reader = new FastReader();

        FastWriter writer = new FastWriter();

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

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

        String[] cards = new String[n];

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

            cards[i] = reader.readString();

        }

        int triple = 0;

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

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

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

                StringBuilder b = new StringBuilder("");

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

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

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

                    } else {

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

                            b.append('S');

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

                            b.append('E');

                        } else {

                            b.append('T');

                        }

                    }

                }

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

                seen.add(cards[j]);

            }

        }

        writer.writeSingleInteger(triple);

    }

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

        if (n < 2) {

            return;

        }

        int mid = n / 2;

        int[] l = new int[mid];

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

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

            l[i] = a[i];

        }

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

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

        }

        mergeSort(l, mid);

        mergeSort(r, n - mid);

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

    }

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

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

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

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

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

            }

            else {

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

            }

        }

        while (i < left) {

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

        }

        while (j < right) {

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

        }

    }

    public static class FastReader {

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

        StringTokenizer tokenizer;

        public int readSingleInt() throws IOException {

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

        }

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

            int[] nums = new int[numInts];

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

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

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

            }

            return nums;

        }

        public String readString() throws IOException {

            return reader.readLine();

        }

    }

    public static class FastWriter {

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

        public void writeSingleInteger(int i) throws IOException {

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

            writer.newLine();

            writer.flush();

        }

        public void writeSingleLong(long i) throws IOException {

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

            writer.newLine();

            writer.flush();

        }

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

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

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

            }

            writer.newLine();

            writer.flush();

        }

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

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

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

            }

            writer.newLine();

            writer.flush();

        }

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

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

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

            }

            writer.newLine();

            writer.flush();

        }

        public void writeString(String s) throws IOException {

            writer.write(s);

            writer.newLine();

            writer.flush();

        }

    }

}


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

	import java.io.*;

	import java.util.*;

	public class ProblemD {

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

			Scanner in = new Scanner();

			int n = in.readInt();

			int a[] = new int[n];

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

			int mx = 0;

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

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

				long sum = 0;

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

					sum+=a[j];

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

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

					long cur = 0;

					int pos  = 0;

					mp.put(0l, -1);

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

						cur+=a[z];

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

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

							mp.clear();

						}

						mp.put(cur, z);

					}

					/*if(sum == 2){

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

					}*/

					if(l.size()>mx){

						mx = l.size();

						res = new ArrayList<>(l);

					}

				}

			}

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

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

		}

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

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

		}

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

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

			for(long it:list){

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

					sofar = Math.abs(it - target);

					nearest = it;

				}

			}

			return nearest;

		}

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

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

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

				if(n%i == 0){

					l.add(i);

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

				}

			}

			Collections.sort(l);

			return l;

		}

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

			int t = a[i];

			a[i] = a[j];

			a[j] = t;

		}

		public static boolean isSorted(long a[]){

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

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

			}

			return true;

		}

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

			int index = -1;

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

			while(l<=r){

				int mid = (l+r)/2;

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

					index = mid;

					r = mid-1;

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

					r  = mid-1;

				}else l  = mid+1;

			}

			return index;

		}

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

			int index = -1;

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

			while(l<=r){

				int mid = (l+r)/2;

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

					index=  mid;

					l = mid+1;

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

					l  = mid+1;

				}else r  = mid-1;

			}

			return index;

		}

		public static void sort(int arr[]){

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

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

			Collections.sort(list);

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

		}

		static class Pair{

			int x,y;

			public Pair(int x,int y){

				this.x = x;

				this.y = y;

			}

		}

		static class Scanner{

			BufferedReader br;

			StringTokenizer st;

			public Scanner(){

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

			}

		    public String read()

		    {

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

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

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

		         }

		         return st.nextToken();

		     }

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

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

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

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

		}

}


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

import java.io.*;

import java.math.*;

import java.util.*;

// @author : Dinosparton

public class test {

	   static class Pair{

		   long x;

		   long y;

		   Pair(long x,long y){

			   this.x = x;

			   this.y = y;

		   }

	   }

	   static class Compare {

		     void compare(Pair arr[], int n)

		    {

		        // Comparator to sort the pair according to second element

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

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

		            {

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

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

		            	}

		            	else {

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

		            	}

		            }

		        });

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

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

//		        }

//		        System.out.println();

		    }

		}

	   static class Scanner {

	        BufferedReader br;

	        StringTokenizer st;

	        public Scanner()

	        {

	            br = new BufferedReader(

	                new InputStreamReader(System.in));

	        }

	        String next()

	        {

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

	                try {

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

	                }

	                catch (IOException e) {

	                    e.printStackTrace();

	                }

	            }

	            return st.nextToken();

	        }

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

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

	        double nextDouble()

	        {

	            return Double.parseDouble(next());

	        }

	        String nextLine()

	        {

	            String str = "";

	            try {

	                str = br.readLine();

	            }

	            catch (IOException e) {

	                e.printStackTrace();

	            }

	            return str;

	        }

	    }

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

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

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

		   max[src] = a[src];

		   for(int i : adj[src]) {

			   if(i == par) {

				   continue;

			   }

				   dfs(i,src,adj,a);

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

		   }

	   }

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

		   ans[src] = max[src];

		   for(int i : adj[src]) {

			   if(i == par) {

				   continue;

			   }

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

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

			   dfs(i,src,adj);

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

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

		   }

	   }

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

		   Scanner sc = new Scanner();

		   StringBuilder res = new StringBuilder();

		   int tc = 1;

		   while(tc-->0) {

			   int n = sc.nextInt();

			   int a[] = new int[n];

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

				   a[i] = sc.nextInt();

				   if(a[i] == 0) {

					   a[i] = -1;

				   }

			   }

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

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

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

			   }

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

				   int src = sc.nextInt()-1;

				   int dest = sc.nextInt()-1;

				   adj[src].add(dest);

				   adj[dest].add(src);

			   }

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

			   dfs(0,-1,adj);

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

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

			   }

		   }

		   System.out.println(res);

	   }

}


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

import java.util.Scanner;

public class CF1009{

	public static void main(String[] args){

		Scanner scan = new Scanner(System.in);

		int testCases = scan.nextInt();

		while(testCases>0){

			String firstString = scan.next();

			String secondString = scan.next();

			String thirdString = scan.next();

			boolean flag = false;

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

				char a = firstString.charAt(i);

				char b = secondString.charAt(i);

				char c = thirdString.charAt(i);

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

					flag = true;

				}

			}

			if(flag){

				System.out.println("NO");

			}else{

				System.out.println("YES");

			}

			testCases--;

		}

	}

}


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

import java.util.Arrays;

import java.util.Scanner;

public class B1311 {

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

	static int t = sc.nextInt();

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

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

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

	public static void main(String[] args) {

		while((t--) > 0) {

			Arrays.fill(c,false);

			boolean flag = true;

			int n = sc.nextInt();

			int m = sc.nextInt();

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

				a[i] = sc.nextInt();

			}

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

				p[j] = sc.nextInt();

				c[p[j]] = true;

			}

			int k = 0;

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

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

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

						if(c[j]) {

							k = a[j];

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

							a[j + 1] = k;

						}

						else {

							flag = false;

						}

					}

				}

			}

			if(!flag) {

				System.out.println("NO");

			}else {

				System.out.println("YES");

			}

		}

	}

 }


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

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

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

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

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

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

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

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

        }
        pw.flush();
    }

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

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

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

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

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

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

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

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

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

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

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

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

    }

    static class MathUtils {
        public MathUtils() {
        }

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

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

    static class ArrayUtils {
        public ArrayUtils() {
        }

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

            return b;
        }

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

            return ans;
        }

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

            return ans;
        }
    }

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


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

import java.util.*;

public class infiniteprefixes {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while (t-- > 0) {

			int n = sc.nextInt();

			int x = sc.nextInt();

			String s = sc.next();

			int[] cnt = new int[n];

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

			int ans = 0;

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

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

					c++;

					c0++;

				} else {

					c--;

					c1++;

				}

				cnt[i] = c;

			}

			d = c0 - c1;

			if (d == 0) {

				c = 0;

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

					if (cnt[i] == x)

						c++;

				}

				if (c != 0)

					ans = -1;

				else

					ans = 0;

			} else {

				if (x == 0)

					ans++;

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

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

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

							ans++;

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

							ans++;

					}

				}

			}

			System.out.println(ans);

		}

	}

}