You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times:   choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$;  remove the edge $$$(v, u)$$$;  add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto D = new int[N]; {
        void dfs(int v, int d) {
            D[v] = d;
            foreach (u; G[v]) {
                dfs(u, d+1);
            }
        }
        dfs(0, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    bool C(int h) {
        auto used = new bool[N];
        Array!int path;
        void fillused(int v) {
            if (used[v]) return;
            used[v] = true;
            foreach (u; G[v]) {
                fillused(u);
            }
        }
        int k = 0;
        auto anc = new int[N]; anc[] = -1;
        void dfs(int v) {
            path ~= v;
            int n = path.length;
            if (n - h >= 0) {
                anc[v] = path[n - h];
            }
            foreach (u; G[v]) {
                dfs(u);
            }
            path.removeBack;
        }
        dfs(0);
        foreach (j; M) {
            if (used[j]) continue;
            if (D[j] <= h) break;
            k++;
            fillused(anc[j]);
        }
        return k <= K;
    }

    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);

}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto RIDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r] is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        RIDX[i] = v;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    auto T = RootedTree(G, 0);
    bool C(int h) {
        int k = 0;
        auto used = RSQ!int(new int[N]);
        foreach (j; M) {
            if (D[j] <= h) break;
            if (used.query(j, j+1) >= 1) continue;
            k++;
            if (k > K) return false;
            int p = T.kth_ancestor(RIDX[j], h - 1);
            int i = IDX[p];
            if (R[i] + 1 - i > N - K + k) return true;
            used.add(i, R[i]+1, 1);
        }
        return true;
    }
    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

struct LazySegmentTree(T, F) {
    int n;
    T[] dat;
    F[] laz; // composition of all uniformly applied `F`s
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n-1];
        dat[] = T.unit;
        laz = new F[2*n-1];
        laz[] = F.id;
    }
    this(T[] xs) {
        this(cast(int)(xs.length));
        for (int i = 0; i < xs.length; i++) { this.dat[this.n - 1 + i] = xs[i]; }
        for (int k = this.n-2; k >= 0; k--) { this.dat[k] = T.binop(this.dat[2*k+1], this.dat[2*k+2]); }
    }
    void push(int k) {
        if (laz[k] == F.id) return;
        if (k < n - 1) {
            laz[k*2+1] = F.composite(laz[k], laz[k*2+1]);
            laz[k*2+2] = F.composite(laz[k], laz[k*2+2]);
        }
        dat[k] = laz[k](dat[k]);
        laz[k] = F.id;
    }
    // apply `f` to range [a, b). i.e. x[a] <- f(x[a]), ..., x[b-1] <- f(x[b-1])
    void apply(int a, int b, F f) { apply(a, b, f, 0, 0, n); }
    void apply(int a, int b, F f, int k, int l, int r) {
        push(k);
        if (a <= l && r <= b) {
            laz[k] = F.composite(f, laz[k]);
            push(k); // we need this line to update `dat[k]`. because (*) below uses `dat[k]` after this function call returns.
        } else if (l < b && a < r) {
            apply(a, b, f, k*2+1, l, (l+r)/2);
            apply(a, b, f, k*2+2, (l+r)/2, r);
            dat[k] = T.binop(dat[k*2+1], dat[k*2+2]); // (*)
        }
    }
    // return x[a] + x[a+1] + ... + x[b-1] (here '+' corresponds to `T.binop`)
    T query(int a, int b) { return query(a, b, 0, 0, n); }
    T query(int a, int b, int k, int l, int r) {
        push(k);
        if (b <= l || r <= a) return T.unit;
        else if (a <= l && r <= b) return dat[k];
        else {
            auto lres = query(a, b, k*2+1, l, (l+r)/2);
            auto rres = query(a, b, k*2+2, (l+r)/2, r);
            return T.binop(lres, rres);
        }
    }
    // for debugging. apply all propagated function to leaves.
    void push_all() {
        for (int k = 0; k < n-1; k++) push(k);
    }
}

struct RSQ(Integer) {
    struct T {
        Integer x;
        Integer len;
        static T binop(T a, T b) { return T(a.x + b.x, a.len + b.len); }
        enum T unit = T(0, 0);
    }
    struct F {
        Integer x;
        this(Integer x) { this.x = x; }
        T opCall(T t) { return T(x * t.len + t.x, t.len); }
        static F composite(F f, F g) { return F(f.x + g.x); }
        enum F id = F(0);
    }
    LazySegmentTree!(T, F) lst;
    this(int n_) { lst = LazySegmentTree!(T, F)(n_); }
    this(Integer[] xs) {
        lst = LazySegmentTree!(T, F)(xs.map!((x) => T(x, 1)).array);
    }
    void add(int a, int b, Integer x) {
        lst.apply(a, b, F(x));
    }
    Integer query(int a, int b) {
        return lst.query(a, b).x;
    }
}

struct RootedTree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor
    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }
    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }
    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }
    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto RIDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r] is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        RIDX[i] = v;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    auto T = RootedTree(G, 0);
    bool C(int h) {
        int k = 0;
        auto used = RSQ!int(new int[N]);
        foreach (j; M) {
            if (D[j] <= h) break;
            if (used.query(j, j+1) >= 1) continue;
            k++;
            if (k > K) return false;
            int p = T.kth_ancestor(RIDX[j], h - 1);
            int i = IDX[p];
            if (R[i] + 1 - i > N - K) return true;
            used.add(i, R[i]+1, 1);
        }
        return true;
    }
    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

struct LazySegmentTree(T, F) {
    int n;
    T[] dat;
    F[] laz; // composition of all uniformly applied `F`s
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n-1];
        dat[] = T.unit;
        laz = new F[2*n-1];
        laz[] = F.id;
    }
    this(T[] xs) {
        this(cast(int)(xs.length));
        for (int i = 0; i < xs.length; i++) { this.dat[this.n - 1 + i] = xs[i]; }
        for (int k = this.n-2; k >= 0; k--) { this.dat[k] = T.binop(this.dat[2*k+1], this.dat[2*k+2]); }
    }
    void push(int k) {
        if (laz[k] == F.id) return;
        if (k < n - 1) {
            laz[k*2+1] = F.composite(laz[k], laz[k*2+1]);
            laz[k*2+2] = F.composite(laz[k], laz[k*2+2]);
        }
        dat[k] = laz[k](dat[k]);
        laz[k] = F.id;
    }
    // apply `f` to range [a, b). i.e. x[a] <- f(x[a]), ..., x[b-1] <- f(x[b-1])
    void apply(int a, int b, F f) { apply(a, b, f, 0, 0, n); }
    void apply(int a, int b, F f, int k, int l, int r) {
        push(k);
        if (a <= l && r <= b) {
            laz[k] = F.composite(f, laz[k]);
            push(k); // we need this line to update `dat[k]`. because (*) below uses `dat[k]` after this function call returns.
        } else if (l < b && a < r) {
            apply(a, b, f, k*2+1, l, (l+r)/2);
            apply(a, b, f, k*2+2, (l+r)/2, r);
            dat[k] = T.binop(dat[k*2+1], dat[k*2+2]); // (*)
        }
    }
    // return x[a] + x[a+1] + ... + x[b-1] (here '+' corresponds to `T.binop`)
    T query(int a, int b) { return query(a, b, 0, 0, n); }
    T query(int a, int b, int k, int l, int r) {
        push(k);
        if (b <= l || r <= a) return T.unit;
        else if (a <= l && r <= b) return dat[k];
        else {
            auto lres = query(a, b, k*2+1, l, (l+r)/2);
            auto rres = query(a, b, k*2+2, (l+r)/2, r);
            return T.binop(lres, rres);
        }
    }
    // for debugging. apply all propagated function to leaves.
    void push_all() {
        for (int k = 0; k < n-1; k++) push(k);
    }
}

struct RSQ(Integer) {
    struct T {
        Integer x;
        Integer len;
        static T binop(T a, T b) { return T(a.x + b.x, a.len + b.len); }
        enum T unit = T(0, 0);
    }
    struct F {
        Integer x;
        this(Integer x) { this.x = x; }
        T opCall(T t) { return T(x * t.len + t.x, t.len); }
        static F composite(F f, F g) { return F(f.x + g.x); }
        enum F id = F(0);
    }
    LazySegmentTree!(T, F) lst;
    this(int n_) { lst = LazySegmentTree!(T, F)(n_); }
    this(Integer[] xs) {
        lst = LazySegmentTree!(T, F)(xs.map!((x) => T(x, 1)).array);
    }
    void add(int a, int b, Integer x) {
        lst.apply(a, b, F(x));
    }
    Integer query(int a, int b) {
        return lst.query(a, b).x;
    }
}

struct RootedTree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor
    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }
    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }
    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }
    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto RIDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r] is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        RIDX[i] = v;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    auto T = RootedTree(G, 0);
    bool C(int h) {
        int k = 0;
        auto used = RSQ(N);
        foreach (j; M) {
            if (D[j] <= h) break;
            int p = T.kth_ancestor(RIDX[j], h - 1);
            int i = IDX[p];
            if (used.query(i, j+1) >= 1) continue;
            if (D[j] > h) {
                k++;
                if (k > K) return false;
                used.update(i, used.query(i,i+1) + 1);
                used.update(R[i]+1, used.query(R[i]+1,R[i]+2)-1);
            }
        }
        return true;
    }
    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

struct RootedTree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor
    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }
    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }
    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }
    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
enum int INF = 1<<28;
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto RIDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r] is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        RIDX[i] = v;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    auto T = RootedTree(G, 0);
    bool C(int h) {
        int k = 0;
        auto used = RSQ(N);
        foreach (j; M) {
            if (D[j] <= h) break;
            int p = T.kth_ancestor(RIDX[j], h - 1);
            int i = IDX[p];
            if (used.query(0, j+1) >= 1) continue;
            if (D[j] > h) {
                k++;
                if (k > K) return false;
                used.update(i, used.query(i,i+1) + 1);
                used.update(R[i]+1, used.query(R[i]+1,R[i]+2)-1);
            }
        }
        return true;
    }
    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

struct RootedTree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor
    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }
    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }
    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }
    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
enum int INF = 1<<28;
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto RIDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r] is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        RIDX[i] = v;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    auto T = RootedTree(G, 0);
    bool C(int h) {
        int k = 0;
        auto used = RSQ(N);
        foreach (j; M) {
            if (D[j] <= h) break;
            int p = T.kth_ancestor(RIDX[j], h - 1);
            int i = IDX[p];
            if (used.query(0, j+1) >= 1) continue;
            if (D[j] > h) {
                k++;
                if (k > K) return false;
                used.update(i, 1);
                used.update(R[i]+1, -1);
            }
        }
        return true;
    }
    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

struct RootedTree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor
    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }
    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }
    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }
    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
enum int INF = 1<<28;
alias RSQ = SegmentTree!(int, 0, (a, b) => a + b);

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto RIDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r] is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        RIDX[i] = v;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    auto T = RootedTree(G, 0);
    bool C(int h) {
        int k = 0;
        auto used = RMQ(N);
        foreach (j; M) {
            if (D[j] <= h) break;
            int p = T.kth_ancestor(RIDX[j], h - 1);
            int i = IDX[p];
            if (used.query(i, j+1) >= 1) continue;
            if (D[j] > h) {
                k++;
                if (k > K) return false;
                used.update(i, 1);
            }
        }
        return true;
    }
    int lb = 0, ub = D.reduce!max;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

struct LazySegmentTree(T, F) {
    int n;
    T[] dat;
    F[] laz; // composition of all uniformly applied `F`s
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n-1];
        dat[] = T.unit;
        laz = new F[2*n-1];
        laz[] = F.id;
    }
    this(T[] xs) {
        this(cast(int)(xs.length));
        for (int i = 0; i < xs.length; i++) { this.dat[this.n - 1 + i] = xs[i]; }
        for (int k = this.n-2; k >= 0; k--) { this.dat[k] = T.binop(this.dat[2*k+1], this.dat[2*k+2]); }
    }
    void push(int k) {
        if (laz[k] == F.id) return;
        if (k < n - 1) {
            laz[k*2+1] = F.composite(laz[k], laz[k*2+1]);
            laz[k*2+2] = F.composite(laz[k], laz[k*2+2]);
        }
        dat[k] = laz[k](dat[k]);
        laz[k] = F.id;
    }
    // apply `f` to range [a, b). i.e. x[a] <- f(x[a]), ..., x[b-1] <- f(x[b-1])
    void apply(int a, int b, F f) { apply(a, b, f, 0, 0, n); }
    void apply(int a, int b, F f, int k, int l, int r) {
        push(k);
        if (a <= l && r <= b) {
            laz[k] = F.composite(f, laz[k]);
            push(k); // we need this line to update `dat[k]`. because (*) below uses `dat[k]` after this function call returns.
        } else if (l < b && a < r) {
            apply(a, b, f, k*2+1, l, (l+r)/2);
            apply(a, b, f, k*2+2, (l+r)/2, r);
            dat[k] = T.binop(dat[k*2+1], dat[k*2+2]); // (*)
        }
    }
    // return x[a] + x[a+1] + ... + x[b-1] (here '+' corresponds to `T.binop`)
    T query(int a, int b) { return query(a, b, 0, 0, n); }
    T query(int a, int b, int k, int l, int r) {
        push(k);
        if (b <= l || r <= a) return T.unit;
        else if (a <= l && r <= b) return dat[k];
        else {
            auto lres = query(a, b, k*2+1, l, (l+r)/2);
            auto rres = query(a, b, k*2+2, (l+r)/2, r);
            return T.binop(lres, rres);
        }
    }
    // for debugging. apply all propagated function to leaves.
    void push_all() {
        for (int k = 0; k < n-1; k++) push(k);
    }
}

struct RSQ(Integer) {
    struct T {
        Integer x;
        Integer len;
        static T binop(T a, T b) { return T(a.x + b.x, a.len + b.len); }
        enum T unit = T(0, 0);
    }
    struct F {
        Integer x;
        this(Integer x) { this.x = x; }
        T opCall(T t) { return T(x * t.len + t.x, t.len); }
        static F composite(F f, F g) { return F(f.x + g.x); }
        enum F id = F(0);
    }
    LazySegmentTree!(T, F) lst;
    this(int n_) { lst = LazySegmentTree!(T, F)(n_); }
    this(Integer[] xs) {
        lst = LazySegmentTree!(T, F)(xs.map!((x) => T(x, 1)).array);
    }
    void add(int a, int b, Integer x) {
        lst.apply(a, b, F(x));
    }
    Integer query(int a, int b) {
        return lst.query(a, b).x;
    }
}

struct RootedTree {
    int[][] G;
    int N;
    int root;
    int[] parent;
    int[] depth;        // depth[v]: distance from root
    int[][] ancestor;   // ancestor[v][i]: v's {2^i}-th ancestor
    void init_parent() {
        void dfs(int v, int prev, int d) {
            parent[v] = prev;
            depth[v] = d;
            foreach (next; G[v]) {
                if (next == prev) continue;
                dfs(next, v, d + 1);
            }
        }
        dfs(root, -1, 0);
    }
    void init_ancestor() {
        int L = bsr(N) + 1;
        this.ancestor = new int[][](N, L);
        foreach (ref e; ancestor) e[] = -1;
        for (int v = 0; v < N; v++) {
            ancestor[v][0] = parent[v];
        }
        for (int i = 1; i < L; i++) {
            for (int v = 0; v < N; v++) {
                if (ancestor[v][i-1] == -1) continue;
                ancestor[v][i] = ancestor[ ancestor[v][i-1] ][i-1];
            }
        }
    }
    this(int[][] G, int root) {
        this.N = cast(int)G.length;
        this.G = G;
        this.root = root;
        this.depth = new int[N];
        this.parent = new int[N];
        init_parent();
        init_ancestor();
    }
    int kth_ancestor(int v, int k) {
        // return v's k-th ancestor
        for (int i = 0; i <= bsr(N); i++) {
            if (k & (1<<i)) {
                v = ancestor[v][i];
                if (v == -1) return v;
            }
        }
        return v;
    }
}

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}
enum int INF = 1<<28;
alias RMQ = SegmentTree!(int, -INF, (a, b) => max(a, b));

import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r) is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    bool C(int h) {
        auto used = new bool[N];
        int k = 0;
        foreach (j; M) {
            if (used[j]) continue;
            if (D[j] > h) {
                k++;
                int i = j;
                while (true) {
                    if (D[i] == D[j] - h + 1) break;
                    i--;
                }
                for (int l = i; l < R[i]; l++) {
                    used[l] = true;
                }
            }
        }
        return k <= K;
    }
    int lb = 0, ub = N;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }

    auto IDX = new int[N];
    auto R = new int[N]; // R[i] = r means [i, r) is the all node of the subtree whose root is i
    auto D = new int[N];
    void dfs(int v, ref int i, int d) {
        IDX[v] = i;
        D[i] = d;
        int orgi = i;
        foreach (u; G[v]) {
            i++;
            dfs(u, i, d+1);
        }
        R[orgi] = i;
    }
    {
        int i = 0;
        dfs(0, i, 0);
    }

    auto M = iota(N).array.sort!((i, j) => D[i] > D[j]).array;
    bool C(int h) {
        auto used = new bool[N];
        int k = 0;
        foreach (j; M) {
            if (used[j]) continue;
            if (D[j] > h) {
                k++;
                int i = j;
                while (true) {
                    used[i] = true;
                    if (D[i] == D[j] - h + 1) break;
                    i--;
                }
            }
        }
        return k <= K;
    }
    int lb = 0, ub = N;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (C(mid) ? ub : lb) = mid;
    }
    writeln(ub);
}

import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1] - 1;
        G[p] ~= i;
    }
    BinaryHeap!(Array!int) Q;
    void dfs(int v, int d) {
        if (G[v].empty) {
            Q.insert(d);
        } else {
            foreach (u; G[v]) {
                dfs(u, d+1);
            }
        }
    }
    dfs(0, 0);

    for (int k = 0; k < K; k++) {
        auto c = Q.front; Q.removeFront;
        int a = c / 2;
        int b = c - a;
        Q.insert(a);
        Q.insert(b);
    }
    writeln(Q.reduce!max);
}


You are given two strings $$$s$$$ and $$$t$$$, both consisting of exactly $$$k$$$ lowercase Latin letters, $$$s$$$ is lexicographically less than $$$t$$$.Let's consider list of all strings consisting of exactly $$$k$$$ lowercase Latin letters, lexicographically not less than $$$s$$$ and not greater than $$$t$$$ (including $$$s$$$ and $$$t$$$) in lexicographical order. For example, for $$$k=2$$$, $$$s=$$$"az" and $$$t=$$$"bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

The first line of the input contains one integer $$$k$$$ ($$$1 \le k \le 2 \cdot 10^5$$$) — the length of strings. The second line of the input contains one string $$$s$$$ consisting of exactly $$$k$$$ lowercase Latin letters. The third line of the input contains one string $$$t$$$ consisting of exactly $$$k$$$ lowercase Latin letters. It is guaranteed that $$$s$$$ is lexicographically less than $$$t$$$. It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

Print one string consisting exactly of $$$k$$$ lowercase Latin letters — the median (the middle element) of list of strings of length $$$k$$$ lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    auto T = readln.chomp;

    int[] U;
    int carry = 0;

    foreach_reverse (i; 0..N) {
        int s = S[i] - 'a' + T[i] - 'a' + carry;
        carry = s / 26;
        U ~= s % 26;
    }

    if (carry != 0) {
        U ~= carry;
    }

    foreach (i; 0..U.length.to!int/2) {
        swap(U[i], U[$-i-1]);
    }

    dchar[] ans;
    int tmp = 0;

    foreach (i, x; U) {
        tmp = tmp * 26 + x;
        int y = tmp / 2;
        if (i != 0 || U.length == N) {
            ans ~= to!dchar(y + 'a');
        }
        tmp %= 2;
    }

    ans.writeln;
}


Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:   +<name> for 'Add' command.  -<name> for 'Remove' command.  <sender_name>:<message_text> for 'Send' command.  <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.

Print a single number — answer to the problem.

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

import std.stdio;
import std.string;

int getMessageLength(string m) {
    int len = 0;

    foreach (i, char c; m) {
        if (c == ':') {
            len = m.length - i - 1;
            break;
        }
    }

    return len;
}

void main() {
    int numChatters = 0;
    int bytesSent = 0;

    string line;
    while ((line = readln.chomp) != null) {
        if (line[0] == '+') {
            numChatters++;
        } else if (line[0] == '-') {
            numChatters--;
        } else {
            bytesSent += (getMessageLength(line) * numChatters);
        }
    }

    writeln(bytesSent);
}


Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:   The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.

In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set. In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set. In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

import std.stdio, std.string, std.algorithm;
import std.conv, std.array, std.container;

void u(int[] a) {
    writef("%d", a.length);
    foreach (x; a) {
        writef(" %d", x);
    }
    writeln;
}

void main() {
    int n; readf("%d\n", &n);
    auto a = stdin.readln.split.map!(to!int).array;
    auto ns = a.partition3(0);
    if (ns[2].length == 0) {
        ns[2] ~= ns[0][$ - 2 .. $];
        ns[0] = ns[0][0 .. $ - 2];
    }
    if (ns[0].length % 2 == 0) {
        ns[1] ~= ns[0][$ - 1];
        ns[0] = ns[0][0 .. $ - 1];
    }
    u(ns[0]);
    u(ns[2]);
    u(ns[1]);
}

import std.algorithm;
import std.container;
import std.exception;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto x = array (filter !("a <  0") (a));
		auto y = array (filter !("a >  0") (a));
		auto z = array (filter !("a == 0") (a));
		if (y.length == 0)
		{
			assert (x.length >= 3);
			y ~= x[0..2];
			x = x[2..$];
		}
		if (x.length % 2 == 0)
		{
			z ~= x[0..1];
			x = x[1..$];
		}
		writefln ("%s %(%s %)", x.length, x);
		writefln ("%s %(%s %)", y.length, y);
		writefln ("%s %(%s %)", z.length, z);
	}
}

import std.stdio, std.string, std.algorithm;
import std.conv, std.array, std.container;

void u(Array!int a) {
    writef("%d", a.length);
    foreach (x; a) {
        writef(" %d", x);
    }
    writeln;
}

void main() {
    int n; readf("%d\n", &n);
    auto a = stdin.readln.split.map!(to!int);
    bool f = true;
    Array!int e, o, z;
    foreach (x; a) {
        if (x == 0) {
            z.insert(x);
        } else if (f &&  x % 2 != 0) {
            o.insert(x);
            f = false;
        } else {
            e.insert(x);
        }
    }
    u(o);
    u(e);
    u(z);
}

import std.stdio, std.string, std.algorithm;
import std.conv, std.array, std.container;

void u(int[] a) {
    writef("%d", a.length);
    foreach (x; a) {
        writef(" %d", x);
    }
    writeln;
}

void main() {
    int n; readf("%d\n", &n);
    auto a = stdin.readln.split.map!(to!int).array;
    auto ns = a.partition3(0);
    if (ns[2].length == 0) {
        ns[2] ~= ns[0][$ - 2 .. $];
        ns[0] = ns[0][0 .. $ - 2];
    }
    if (ns[0].length % 2 == 0) {
        ns[1] ~= ns[0][$ - 1];
        ns[0] ~= ns[0][0 .. $ - 1];
    }
    u(ns[0]);
    u(ns[2]);
    u(ns[1]);
}

import std.stdio, std.string, std.algorithm;
import std.conv, std.array, std.container;

void u(int[] a) {
    writef("%d", a.length);
    foreach (x; a) {
        writef(" %d", x);
    }
    writeln;
}

void main() {
    int n; readf("%d\n", &n);
    auto a = stdin.readln.split.map!(to!int).array;
    auto ns = a.partition3(0);
    if (ns[2].length == 0) {
        ns[2] ~= ns[0][$ - 2 .. $];
        ns[0] = ns[0][0 .. $ - 2];
    }
    if (ns[0].length % 2 == 0) {
        ns[1] ~= ns[0][$ - 1];
        ns[0] ~= ns[0][0 .. $ - 1];
    }
    foreach (x; ns) {
        u(x);
    }
}

import std.algorithm;
import std.container;
import std.exception;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto x = array (filter !("a <  0") (a));
		auto y = array (filter !("a >  0") (a));
		auto z = array (filter !("a == 0") (a));
		if (y.length == 0)
		{
			assert (x.length >= 3);
			y ~= x[0..2];
			x = x[2..$];
		}
		writefln ("%s %(%s %)", x.length, x);
		writefln ("%s %(%s %)", y.length, y);
		writefln ("%s %(%s %)", z.length, z);
	}
}


Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.Sonya has drawn $$$n$$$ numbers in a row, $$$a_i$$$ is located in the $$$i$$$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.For example, if the numbers $$$[1, 5, 4, 1, 3]$$$ are written, and Sonya gives the number $$$1$$$ to the first robot and the number $$$4$$$ to the second one, the first robot will stop in the $$$1$$$-st position while the second one in the $$$3$$$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $$$4$$$ to the first robot and the number $$$5$$$ to the second one, they will meet since the first robot will stop in the $$$3$$$-rd position while the second one is in the $$$2$$$-nd position.Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($$$p$$$, $$$q$$$), where she will give $$$p$$$ to the first robot and $$$q$$$ to the second one. Pairs ($$$p_i$$$, $$$q_i$$$) and ($$$p_j$$$, $$$q_j$$$) are different if $$$p_i\neq p_j$$$ or $$$q_i\neq q_j$$$.Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.

The first line contains a single integer $$$n$$$ ($$$1\leq n\leq 10^5$$$) — the number of numbers in a row. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1\leq a_i\leq 10^5$$$) — the numbers in a row.

Print one number — the number of possible pairs that Sonya can give to robots so that they will not meet.

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    auto cnt = new int[10 ^^ 5 + 1];
    cnt[] = 0;
    arr.each!(x => ++cnt[x]);
    auto vals = cnt.count!(x => x > 0);

    bool[10 ^^ 5 + 1] done;
    done[] = false;
    long ans = 0;
    foreach (e; arr) {
        cnt[e] -= 1;
        if (cnt[e] == 0) --vals;

        if (done[e]) continue;

        ans += vals;
        done[e] = true;
    }

    ans.writeln;
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    bool[10 ^^ 5 + 1] done;
    done[] = false;
    long ans = 0;
    foreach (e; arr) {
        cnt[e] -= 1;
        if (cnt[e] == 0) cnt.remove(e);

        if (done[e]) continue;

        ans += cnt.length;
        done[e] = true;
    }

    ans.writeln;
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    int [int] cnt;
    arr.each!(x => ++cnt[x]);

    int [int] done;
    long ans = 0;
    foreach (e; arr) {
        cnt[e] -= 1;
        if (cnt[e] == 0) cnt.remove(e);

        if (e in done) continue;

        ans += cnt.length;
        done[e] = true;
    }

    ans.writeln;
}


Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.

The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.

Print a single integer — the minimal time required to eat all nuts in seconds.

import std.stdio, std.string, std.algorithm;
import std.conv, std.array;
import std.container;
import std.typecons;
import std.math;

void main() {
    int n; readf("%d\n", &n);
    int[] h = new int[n];
    for (int i = 0; i < n; i++) {
        readf("%d\n", &h[i]);
    }
    int t = 0;
    int c = 0;
    for (int i = 0; i < n; i++) {
        t += abs(h[i] - c);
        c = h[i];
    }
    t += n;
    t += n - 1;
    writeln(t);
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio;

immutable int MAX = 10^^6;

void main() {
    auto N = readln.chomp.to!int;
    auto pos = readln.chomp.to!int;
    long ans = pos + 1;
    foreach (_; 0..N-1) {
        auto H = readln.chomp.to!int;
        auto npos = min(pos, H);
        ans += pos - npos + 1 + H - npos + 1;
        pos = H;
    }
    ans.writeln;
}

module main;

import std.stdio : readln, writeln, write, writefln, writef;
import std.conv : to;
import std.array : split, replace;
import std.string : strip;
import std.algorithm : max, min, map, reduce, sort, reverse;
import std.functional : memoize;

version = B;

version (A)
{
    void main()
    {
        auto sequence = read_one!string();
        auto instructions = read_one!string();
        size_t position = 0;
        foreach (instruction; instructions)
        {
            if (sequence[position] == instruction)
            {
                position += 1;
            }
        }
        writeln(position + 1);
    }
}
version (B)
{
    T abs(T)(T x)
    {
        if (x < 0) return -x; return x;
    }
    void main()
    {
        auto n = read_one!int();
        auto heights = new int[n+1];
        foreach (i; 1..n+1)
        {
            heights[i] = read_one!int();
        }
        auto answer = n * 2 - 1;
        foreach (i; 0..n)
        {
            answer += abs(heights[i] - heights[i+1]);
        }
        writeln(answer);
        // walks: heights[0] + (heights[i] - heights[i-1]).map!abs.sum
        // jumps: n-1
        // eats: n
    }
}
version (C)
{
    void main()
    {
        auto n = read_one!int();
    }
}
version (D)
{
    void main()
    {
        auto n = read_one!int();
    }
}
version (E)
{
    void main()
    {
    }
}

T read_one(T)()
{
    return readln().strip().to!T();
}

T[] read_some(T)()
{
    T[] ret;
    foreach (e; readln().strip().split())
    {
        ret ~= e.to!T();
    }
    return ret;
}

T[m] read_fixed(int m, T)()
{
    T[m] ret;
    foreach (i, e; readln().strip().split())
    {
        ret[i] = e.to!T();
    }
    return ret;
}

import std.stdio, std.algorithm, std.string, std.conv, std.array, std.range, std.math;
int readint() { return readln.chomp.to!int; }
int[] readints() { return readln.split.to!(int[]); }

void main() {
    int n = readint();
    int[] hs;
    foreach(i; 0..n) hs ~= readint();

    int t, ph;
    foreach (i, h ; hs) {
        t += h - ph;
        t++;
        if (i != n-1) {
            t += max(0, h - hs[i+1]);
            ph = min(h, hs[i+1]);
            t++;
        }
    }

    writeln(t);
    string _ = readln;
}

import std.conv;
import std.math;
import std.stdio;
import std.string;

private const JUMP_TIME = 1;
private const EAT_TIME = 1;

void main() {
	auto
		trees_count = read(),
		position = read(),
		time = position + EAT_TIME;

	foreach (i; 1 .. trees_count) {
		auto tree = read();

		time += abs(position - tree) + EAT_TIME + JUMP_TIME;

		position = tree;
	}

	stdout.write(time);
}

int read() {
	return to!int(strip(stdin.readln()));
}

import std.conv;
import std.math;
import std.stdio;
import std.string;

private const JUMP_TIME = 1;
private const EAT_TIME = 1;

void main() {
	auto
		trees_count = read(),
		position = read(),
		time = position + EAT_TIME;

	foreach (i; 1 .. trees_count) {
		auto tree = read();

		time += abs(position - tree) + EAT_TIME + JUMP_TIME;
	}

	stdout.write(time);
}

int read() {
	return to!int(strip(stdin.readln()));
}


There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.

The first line contains three integers n, k and p (1 ≤ n ≤ 1 000, n ≤ k ≤ 2 000, 1 ≤ p ≤ 109) — the number of people, the number of keys and the office location. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — positions in which people are located initially. The positions are given in arbitrary order. The third line contains k distinct integers b1, b2, ..., bk (1 ≤ bj ≤ 109) — positions of the keys. The positions are given in arbitrary order. Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.

Print the minimum time (in seconds) needed for all n to reach the office with keys.

NoteIn the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto P = s[2];
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;
    A.sort();
    B.sort();

    long hi = 2 * 10^^ 9 + 1;
    long lo = -1;

    while (hi - lo > 1) {
        long mid = (hi + lo) / 2;
        int p = -1;
        foreach (i; 0..N) {
            p++;
            while (p < K && abs(A[i] - B[p]) + abs(B[p] - P) > mid) p++;
        }
        if (p < K) hi = mid;
        else lo = mid;
    }

    hi.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k, p;
    readf("%s %s %s", &n, &k, &p);
    readln;

    auto rd = () => readln.chomp.split.map!(to!int).array.sort().array;

    auto a = rd();
    auto b = rd();

    bool isOk(int m) {
        debug { m.writeln; }

        bool chk(int m, int[] a, int[] b) {
            auto toTake = (true).repeat(b.length).array;
            foreach (el; a) {
                bool found = false;
                foreach (i, ky; b) {
                    if (!toTake[i]) { continue; }

                    if (abs(el - ky) + abs(ky - p) > m) { continue; }

                    toTake[i] = false;
                    found = true;
                    break;
                }

                if (!found) { return false; }
            }

            return true;
        }

        return chk(m, a, b) || chk(m, a.retro().array, b.retro().array);
    }

    int le = 0, r = 10 ^^ 9 * 2;
    while (le < r) {
        int m = le + (r - le) / 2;

        if (isOk(m)) r = m;
        else le = m+1;
    }

    le.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k, p;
    readf("%s %s %s", &n, &k, &p);
    readln;

    auto rd = () => readln.chomp.split.map!(to!int).array.sort().array;

    auto a = rd();
    auto b = rd();

    bool isOk(int m) {
        debug { m.writeln; }

        bool chk(int m, int[] a, int[] b) {
            auto toTake = (true).repeat(b.length).array;
            foreach (el; a) {
                bool found = false;
                foreach (i, ky; b) {
                    if (!toTake[i]) { continue; }

                    if (abs(el - ky) + abs(ky - p) > m) { continue; }

                    toTake[i] = false;
                    found = true;
                    break;
                }

                if (!found) { return false; }
            }

            return true;
        }

        return chk(m, a, b) || chk(m, a.retro().array, b.retro().array)
            || chk(m, a.retro().array, b) || chk(m, a, b.retro().array);
    }

    int le = 0, r = 10 ^^ 9 * 2;
    while (le < r) {
        int m = le + (r - le) / 2;

        if (isOk(m)) r = m;
        else le = m+1;
    }

    le.writeln;
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      const P = readLong();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }
      auto B = new long[K];
      foreach (j; 0 .. K) {
        B[j] = readLong();
      }
      A.sort;
      B.sort;

      long ans = long.max;
      foreach (j0; 0 .. K - N + 1) {
        long mx;
        foreach (i; 0 .. N) {
          chmax(mx, abs(A[i] - B[j0 + i]) + abs(B[j0 + i] - P));
        }
        chmin(ans, mx);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto P = s[2];
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;
    A.sort();
    B.sort();

    long hi = 2 * 10^^ 9 + 1;
    long lo = -1;

    while (hi - lo > 1) {
        long mid = (hi + lo) / 2;
        int p = 0;
        foreach (i; 0..N) {
            while (p < K && abs(A[i] - B[p]) + abs(B[p] - P) > mid) p++;
        }
        if (p < K) hi = mid;
        else lo = mid;
    }

    hi.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k, p;
    readf("%s %s %s", &n, &k, &p);
    readln;

    auto rd = () => readln.chomp.split.map!(to!int).array.sort().array;

    auto a = rd();
    auto b = rd();

    bool isOk(int m) {
        debug { m.writeln; }

        bool chk(int m, int[] a, int[] b) {
            auto toTake = (true).repeat(b.length).array;
            foreach (el; a) {
                bool found = false;
                foreach (i, ky; b) {
                    if (!toTake[i]) { continue; }

                    if (abs(el - ky) + abs(ky - p) > m) { continue; }

                    toTake[i] = false;
                    found = true;
                    break;
                }

                if (!found) { return false; }
            }

            return true;
        }

        return chk(m, a, b) || chk(m, a.retro().array, b.retro().array)
            || chk(m, a.retro().array, b) || chk(m, a, b.retro().array);
    }

    int le = 1, r = 10 ^^ 9 * 2;
    while (le < r) {
        int m = le + (r - le) / 2;

        if (isOk(m)) r = m;
        else le = m+1;
    }

    le.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k, p;
    readf("%s %s %s", &n, &k, &p);
    readln;

    auto rd = () => readln.chomp.split.map!(to!int).array.sort().array;

    auto a = rd();
    auto b = rd();

    bool isOk(int m) {
        debug { m.writeln; }

        bool chk(int m, int[] a, int[] b) {
            auto toTake = (true).repeat(b.length).array;
            foreach (el; a) {
                bool found = false;
                foreach (i, ky; b) {
                    if (!toTake[i]) { continue; }

                    if (abs(el - ky) + abs(ky - p) > m) { continue; }

                    toTake[i] = false;
                    found = true;
                    break;
                }

                if (!found) { return false; }
            }

            return true;
        }

        return chk(m, a, b) || chk(m, a.retro().array, b.retro().array) || chk(m, a.retro().array, b);
    }

    int le = 1, r = 10 ^^ 9 * 2;
    while (le < r) {
        int m = le + (r - le) / 2;

        if (isOk(m)) r = m;
        else le = m+1;
    }

    le.writeln;
}


Is it really?! The robot only existing in my imagination?! The Colossal Walking Robot?!!— Kochiya Sanae Sanae made a giant robot — Hisoutensoku, but something is wrong with it. To make matters worse, Sanae can not figure out how to stop it, and she is forced to fix it on-the-fly.The state of a robot can be represented by an array of integers of length $$$n$$$. Initially, the robot is at state $$$a$$$. She wishes to turn it into state $$$b$$$. As a great programmer, Sanae knows the art of copy-and-paste. In one operation, she can choose some segment from given segments, copy the segment from $$$b$$$ and paste it into the same place of the robot, replacing the original state there. However, she has to ensure that the sum of $$$a$$$ does not change after each copy operation in case the robot go haywire. Formally, Sanae can choose segment $$$[l,r]$$$ and assign $$$a_i = b_i$$$ ($$$l\le i\le r$$$) if $$$\sum\limits_{i=1}^n a_i$$$ does not change after the operation.Determine whether it is possible for Sanae to successfully turn the robot from the initial state $$$a$$$ to the desired state $$$b$$$ with any (possibly, zero) operations.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2\cdot 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n\leq 2\cdot 10^5$$$, $$$1 \leq m\leq 2\cdot 10^5$$$) — the length of $$$a$$$, $$$b$$$ and the number of segments. The second line contains $$$n$$$ intergers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial state $$$a$$$. The third line contains $$$n$$$ intergers $$$b_1,b_2,\ldots,b_n$$$ ($$$1 \leq b_i \leq 10^9$$$) — the desired state $$$b$$$. Then $$$m$$$ lines follow, the $$$i$$$-th line contains two intergers $$$l_i,r_i$$$ ($$$1 \leq l_i < r_i \leq n$$$) — the segments that can be copy-pasted by Sanae. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.

For each test case, print "YES" (without quotes) if $$$a$$$ can be turned into $$$b$$$, or "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteTest case 1:One possible way of turning $$$a$$$ to $$$b$$$:First, select $$$[1,3]$$$. After the operation, $$$a=[3,2,5,2,3]$$$.Then, select $$$[2,5]$$$. After the operation, $$$a=[3,2,5,4,1]=b$$$.Test case 2:It can be shown that it is impossible to turn $$$a$$$ into $$$b$$$.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readInt;
        auto A = new long[N]; foreach (u; 0 .. N) A[u] = readInt;
        auto B = new long[N]; foreach (u; 0 .. N) B[u] = readInt;
        auto L = new int[M];
        auto R = new int[M];
        foreach (i; 0 .. M) {
          L[i] = readInt - 1;
          R[i] = readInt;
        }

        auto G = new int[][N + 1];
        foreach (i; 0 .. M) {
          G[L[i]] ~= i;
          G[R[i]] ~= i;
        }

        auto ds = new long[N + 1];
        foreach (u; 0 .. N) {
          ds[u + 1] = ds[u] + (B[u] - A[u]);
        }

        auto fs = new bool[N + 1];
        foreach (u; 0 .. N + 1) {
          fs[u] = (ds[u] != 0);
        }
        auto set = redBlackTree(iota(N + 1).array);
        DList!int que;
        foreach (i; 0 .. M) {
          if (!fs[L[i]] && !fs[R[i]]) {
            que ~= i;
          }
        }
        for (; !que.empty; ) {
          const i = que.front;
          que.removeFront;
          auto ran = set.upperBound(L[i]);
          int[] us;
          foreach (u; ran) {
            if (u >= R[i]) break;
            us ~= u;
          }
          foreach (u; us) {
            fs[u] = false;
            foreach (j; G[u]) {
              if (!fs[L[j]] && !fs[R[j]]) {
                que ~= j;
              }
            }
          }
          set.removeKey(us);
        }

        bool ans = true;
        foreach (u; 0 .. N + 1) {
          ans = ans && !fs[u];
        }
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readInt;
        auto A = new int[N]; foreach (u; 0 .. N) A[u] = readInt;
        auto B = new int[N]; foreach (u; 0 .. N) B[u] = readInt;
        auto L = new int[M];
        auto R = new int[M];
        foreach (i; 0 .. M) {
          L[i] = readInt - 1;
          R[i] = readInt;
        }

        auto G = new int[][N + 1];
        foreach (i; 0 .. M) {
          G[L[i]] ~= i;
          G[R[i]] ~= i;
        }

        auto ds = new int[N + 1];
        foreach (u; 0 .. N) {
          ds[u + 1] = ds[u] + (B[u] - A[u]);
        }

        auto fs = new bool[N + 1];
        foreach (u; 0 .. N + 1) {
          fs[u] = (ds[u] != 0);
        }
        auto set = redBlackTree(iota(N + 1).array);
        DList!int que;
        foreach (i; 0 .. M) {
          if (!fs[L[i]] && !fs[R[i]]) {
            que ~= i;
          }
        }
        for (; !que.empty; ) {
          const i = que.front;
          que.removeFront;
          auto ran = set.upperBound(L[i]);
          int[] us;
          foreach (u; ran) {
            if (u >= R[i]) break;
            us ~= u;
          }
          foreach (u; us) {
            fs[u] = false;
            foreach (j; G[u]) {
              if (!fs[L[j]] && !fs[R[j]]) {
                que ~= j;
              }
            }
          }
          set.removeKey(us);
        }

        bool ans = true;
        foreach (u; 0 .. N + 1) {
          ans = ans && !fs[u];
        }
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}


Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 10^3$$$) — the number of flowers and visitors respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1\leq l_i\leq r_i\leq n$$$), meaning that $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive.

Print the string of $$$n$$$ characters. The $$$i$$$-th symbol should be «0» if you want to put a rose in the $$$i$$$-th position, otherwise «1» if you want to put a lily. If there are multiple answers, print any.

NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions;  in the segment $$$[1\ldots3]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$;  in the segment $$$[2\ldots4]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$;  in the segment $$$[2\ldots5]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$. The total beauty is equal to $$$2+2+4=8$$$.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions;  in the segment $$$[5\ldots6]$$$, there are one rose and one lily, so the beauty is equal to $$$1\cdot 1=1$$$;  in the segment $$$[1\ldots4]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$;  in the segment $$$[4\ldots6]$$$, there are two roses and one lily, so the beauty is equal to $$$2\cdot 1=2$$$. The total beauty is equal to $$$1+4+2=7$$$.

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    int n, m;
    readf("%s %s", &n, &m);
    readln;

    auto arr = ['0','1'].replicate(n).take(n).array;

    arr.writeln;
}


In order to do some research, $$$n^2$$$ labs are built on different heights of a mountain. Let's enumerate them with integers from $$$1$$$ to $$$n^2$$$, such that the lab with the number $$$1$$$ is at the lowest place, the lab with the number $$$2$$$ is at the second-lowest place, $$$\ldots$$$, the lab with the number $$$n^2$$$ is at the highest place.To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number $$$u$$$ to the lab with the number $$$v$$$ if $$$u > v$$$.Now the labs need to be divided into $$$n$$$ groups, each group should contain exactly $$$n$$$ labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group $$$A$$$ to a group $$$B$$$ is equal to the number of pairs of labs ($$$u, v$$$) such that the lab with the number $$$u$$$ is from the group $$$A$$$, the lab with the number $$$v$$$ is from the group $$$B$$$ and $$$u > v$$$. Let's denote this value as $$$f(A,B)$$$ (i.e. $$$f(A,B)$$$ is the sum of units of water that can be sent from a group $$$A$$$ to a group $$$B$$$).For example, if $$$n=3$$$ and there are $$$3$$$ groups $$$X$$$, $$$Y$$$ and $$$Z$$$: $$$X = \{1, 5, 6\}, Y = \{2, 4, 9\}$$$ and $$$Z = \{3, 7, 8\}$$$. In this case, the values of $$$f$$$ are equal to:  $$$f(X,Y)=4$$$ because of $$$5 \rightarrow 2$$$, $$$5 \rightarrow 4$$$, $$$6 \rightarrow 2$$$, $$$6 \rightarrow 4$$$,  $$$f(X,Z)=2$$$ because of $$$5 \rightarrow 3$$$, $$$6 \rightarrow 3$$$,  $$$f(Y,X)=5$$$ because of $$$2 \rightarrow 1$$$, $$$4 \rightarrow 1$$$, $$$9 \rightarrow 1$$$, $$$9 \rightarrow 5$$$, $$$9 \rightarrow 6$$$,  $$$f(Y,Z)=4$$$ because of $$$4 \rightarrow 3$$$, $$$9 \rightarrow 3$$$, $$$9 \rightarrow 7$$$, $$$9 \rightarrow 8$$$,  $$$f(Z,X)=7$$$ because of $$$3 \rightarrow 1$$$, $$$7 \rightarrow 1$$$, $$$7 \rightarrow 5$$$, $$$7 \rightarrow 6$$$, $$$8 \rightarrow 1$$$, $$$8 \rightarrow 5$$$, $$$8 \rightarrow 6$$$,  $$$f(Z,Y)=5$$$ because of $$$3 \rightarrow 2$$$, $$$7 \rightarrow 2$$$, $$$7 \rightarrow 4$$$, $$$8 \rightarrow 2$$$, $$$8 \rightarrow 4$$$. Please, divide labs into $$$n$$$ groups with size $$$n$$$, such that the value $$$\min f(A,B)$$$ over all possible pairs of groups $$$A$$$ and $$$B$$$ ($$$A \neq B$$$) is maximal.In other words, divide labs into $$$n$$$ groups with size $$$n$$$, such that minimum number of the sum of units of water that can be transported from a group $$$A$$$ to a group $$$B$$$ for every pair of different groups $$$A$$$ and $$$B$$$ ($$$A \neq B$$$) as big as possible.Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values $$$f$$$ for some division.If there are many optimal divisions, you can find any.

The only line contains one number $$$n$$$ ($$$2 \leq n \leq 300$$$).

Output $$$n$$$ lines: In the $$$i$$$-th line print $$$n$$$ numbers, the numbers of labs of the $$$i$$$-th group, in any order you want. If there are multiple answers, that maximize the minimum number of the sum of units of water that can be transported from one group the another, you can print any.

NoteIn the first test we can divide $$$9$$$ labs into groups $$$\{2, 8, 5\}, \{9, 3, 4\}, \{7, 6, 1\}$$$.From the first group to the second group we can transport $$$4$$$ units of water ($$$8 \rightarrow 3, 8 \rightarrow 4, 5 \rightarrow 3, 5 \rightarrow 4$$$).From the first group to the third group we can transport $$$5$$$ units of water ($$$2 \rightarrow 1, 8 \rightarrow 7, 8 \rightarrow 6, 8 \rightarrow 1, 5 \rightarrow 1$$$).From the second group to the first group we can transport $$$5$$$ units of water ($$$9 \rightarrow 2, 9 \rightarrow 8, 9 \rightarrow 5, 3 \rightarrow 2, 4 \rightarrow 2$$$).From the second group to the third group we can transport $$$5$$$ units of water ($$$9 \rightarrow 7, 9 \rightarrow 6, 9 \rightarrow 1, 3 \rightarrow 1, 4 \rightarrow 1$$$).From the third group to the first group we can transport $$$4$$$ units of water ($$$7 \rightarrow 2, 7 \rightarrow 5, 6 \rightarrow 2, 6 \rightarrow 5$$$).From the third group to the second group we can transport $$$4$$$ units of water ($$$7 \rightarrow 3, 7 \rightarrow 4, 6 \rightarrow 3, 6 \rightarrow 4$$$).The minimal number of the sum of units of water, that can be transported from one group to another is equal to $$$4$$$. It can be proved, that it is impossible to make a better division.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;

struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}

Input input;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto brange(alias low, alias high, alias pred, bool value)()
{
  return iota(low, high + 1).map!((a) => cast(int) pred(a)).assumeSorted.equalRange(value);
}
auto ftrue(alias low, alias high, alias pred)()
{
  return brange!(low, high, pred, false).length + low;
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t;
      get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
struct ModNum(T)
{
  T representative, modulus;
  this(T representative, T modulus)
  {
    this.representative = representative;
    this.modulus = modulus;
  }
  T minimalPositiveRepresentative()
  {
    return ((representative % modulus) + modulus) % modulus;
  }
  T minimalNegativeRepresentative()
  {
    return ((representative % modulus) - modulus) % modulus;
  }
  T maxRepresentative(T upperBound)
  {
    return upperBound - pmod(upperBound - representative, modulus);
  }
  T minRepresentative(T lowerBound)
  {
    return lowerBound + pmod(representative - lowerBound, modulus);
  }
}
// minimum possible representative of x modulo m.
T pmod(T)(T x, T m)
{
  return (x % m + m) % m;
}
// solves ax + by = gcd(a, b) and returns gcd(a, b)
T extendedEuclideanAlgorithm(T)(T a, T b, out T x, out T y)
{
  if (a == 0)
    {
      x = 0, y = 1;
      return b;
    }
  T x1, y1;
  auto d = egcd(b % a, a, x1, y1);
  x = y1 - (b / a) * x1, y = x1;
  return d;
}
alias egcd = extendedEuclideanAlgorithm;
// solves ax = b (mod m) giving a solution as a modulus class.
bool solveLinearCongruence(T)(T a, T b, T m, out ModNum!T res)
{
  T x, p;
  b = pmod(b, m);
  T y;
  T g = egcd(a, m, x, y);
  if (b % g != 0)
    return false;
  p = m / g;
  x = pmod(x * b / g, p);
  res.representative = x;
  res.modulus = p;
  return true;
}

void main()
{
  alias ln = int;
  ln n; get(n);
  ln sn = n * n;
  ln[] sets = new ln[n];
  ln curr = 0;
  for(ln i = 1; i <= n; i++)
    {
      ln fd = 2 * (n - i) + 1;
      ln ld = 2 * i - 1;
      ln tn = 0;
      for(ln q = i; q <= sn;)
	{
	  write(q, " ");
	  if (tn)
	      q += ld;
	  else
	      q += fd;
	  tn ^= 1;
	}
      writeln();
    }

}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto ans = new long[][](n);
	foreach (i; 0..n*n)
	{
		auto pos = i % n;
		if ((i / n) % 2 == 1)
		{
			pos = n - pos - 1;
		}
		ans[pos] ~= i+1;
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}


Today at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of $$$x$$$ as $$$S(x)$$$. Then $$$S(5)=5$$$, $$$S(38)=S(3+8=11)=S(1+1=2)=2$$$, $$$S(10)=S(1+0=1)=1$$$.As a homework Petya got $$$n$$$ tasks of the form: find $$$k$$$-th positive number whose digital root is $$$x$$$.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $$$n$$$ tasks from Petya's homework.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$) — the number of tasks in Petya's homework. The next $$$n$$$ lines contain two integers $$$k_i$$$ ($$$1 \le k_i \le 10^{12}$$$) and $$$x_i$$$ ($$$1 \le x_i \le 9$$$) — $$$i$$$-th Petya's task in which you need to find a $$$k_i$$$-th positive number, the digital root of which is $$$x_i$$$.

Output $$$n$$$ lines, $$$i$$$-th line should contain a single integer — the answer to the $$$i$$$-th problem.

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void solve() {
    auto s = readln.split.map!(to!long);
    auto K = s[0];
    auto X = s[1];
    long ans;

    if (X == 9) {
        ans = 9 * K;
    } else {
        ans = 9 * (K - 1) + X;
    }

    ans.writeln;
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) solve;
}