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.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

long f(int n, int x, int y) {
    auto sumOdd = (x+y) % 2 == 1;
    auto rowOdd = x % 2 == 1;
    auto prevRows = n % 2 == 0 ?
        cast(long)(x-1) * n/2 :
        cast(long)(x-1)/2 * (n/2 + n/2 + 1) + (!rowOdd ? (sumOdd ? n/2 : n/2+1) : 0);
    auto prevCols = (y-1) / 2;
    return 1 + prevRows + prevCols + (sumOdd ? f(n, n, n) : 0);
}

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto s = readln.chomp;

        bool ok = true;
        for (int i = 0, j = n-1; i < j; ++i, --j) {
            auto dist = abs(s[i] - s[j]);
            ok &= dist == 0 || dist == 2;
        }

        writeln(ok ? "YES" : "NO");
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

int[] a;
bool pos(int i,int j){
    int x=a[i],y=a[j];
    if(x==y) return true;
    if((x<26 && y>1 && x+1==y-1)
        ||(x>1 && y<26 && x-1==y+1))
        return true;
    return false;
}
void main(){
    int t=readln.chomp.to!int,n;
    bool ans;
    while(t--){
        n=readln.chomp.to!int;
        a=readln.strip
                .map!(to!int)
                .map!"a-96"
                .array;
        ans=true;
        foreach(i;0..n/2){
            if(!pos(i,n-i-1)){
                ans=false;
                break;
            }
        }
        if(ans)
            writeln("YES");
        else
            writeln("NO");
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int t=readln.chomp.to!int,n;
    bool ans;
    while(t--){
        n=readln.chomp.to!int;
        auto a=readln.strip
                     .map!(to!int)
                     .map!"a-96"
                     .array;
        ans=true;
        foreach(i;0..n/2){
            int d=abs(a[i]-a[n-i-1]);
            if(d==1||d>2){
                ans=false;
                break;
            }
        }
        if(ans)
            writeln("YES");
        else
            writeln("NO");
    }
}

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, std.bitmanip;

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

void solve() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    bool ok = true;

    foreach (i; 0..N/2) {
        char x = S[i];
        char y = S[N-i-1];
        if (x != y && abs(x - y) != 2) ok = false;
    }

    writeln(ok ? "YES" : "NO");
}

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.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto s = readln.chomp;

        bool ok = true;
        for (int i = 0, j = n-1; i < j; ++i, --j) {
            auto dist = abs(s[i] - s[j]);
            ok &= dist == 0 || dist == 2;
        }

        writeln(ok ? "YES" : "NO");
    }
}


import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

void main() {
    int N, M, K; long P; scanf("%d %d %d %d\n", &N, &M, &K, &P);
    long[][] F = new long[][N];
    foreach (i; 0 .. N) {
        F[i] = readln.chomp.split(" ").map!(to!long).array;
    }
    long[] SR = new long[N],
           SC = new long[M];
    foreach (i; 0 .. N) {
        foreach (j; 0 .. M) {
            SR[i] += F[i][j];
            SC[j] += F[i][j];
        }
    }
    SR = SR.sort.array;
    SC = SC.sort.array;

    long DR = 0, DC = 0;

    BinaryHeap!(Array!long, "a < b") PQ;
    foreach (r; SR) PQ.insert(r);
    long[] R = new long[K + 1];
    R[0] = 0;
    foreach (i; 1 .. K + 1) {
        long r = PQ.front;
        R[i] = R[i - 1] + r;
        PQ.removeFront;
        PQ.insert(r - P * M);
    }

    PQ.clear;
    foreach (c; SC) PQ.insert(c);
    long[] C = new long[K + 1];
    C[0] = 0;
    foreach (i; 1 .. K + 1) {
        long c = PQ.front;
        C[i] = C[i - 1] + c;
        PQ.removeFront;
        PQ.insert(c - P * N);
    }

    /*
    writeln(R);
    writeln(C);
    */

    long Ans = long.min;

    foreach (long i; 0 .. K + 1) {
        Ans = max(Ans, R[cast(uint)i] + C[K - cast(uint)i] - (i * (cast(long)K - i) * P));
    }
    writeln(Ans);
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int M, N, K;
long P;
long[][] A;

long[] solve(long[] xs, long dec) {
	auto q = heapify(xs);
	long[] ret = new long[K + 1];
	foreach (k; 0 .. K) {
		const now = q.front;
		q.removeFront;
		ret[k + 1] = ret[k] + now;
		q.insert(now - dec);
	}
	return ret;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		K = readInt;
		P = readLong;
		A = new long[][](M, N);
		foreach (x; 0 .. M) foreach (y; 0 .. N) {
			A[x][y] = readLong;
		}

		long[] bs = new long[M];
		long[] cs = new long[N];
		foreach (x; 0 .. M) foreach (y; 0 .. N) {
			bs[x] += A[x][y];
			cs[y] += A[x][y];
		}

		long[] fbs = solve(bs, P * N);
		long[] fcs = solve(cs, P * M);
// writeln(fbs);
// writeln(fcs);
		long ans = long.min;
		foreach (k; 0 .. K + 1) {
			chmax(ans, fbs[k] + fcs[K - k] - P * k * (K - k));
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

void main() {
    int N, M, K; long P; scanf("%d %d %d %d\n", &N, &M, &K, &P);
    long[][] F = new long[][N];
    foreach (i; 0 .. N) {
        F[i] = readln.chomp.split(" ").map!(to!long).array;
    }
    long[] SR = new long[N],
           SC = new long[M];
    foreach (i; 0 .. N) {
        foreach (j; 0 .. M) {
            SR[i] += F[i][j];
            SC[j] += F[i][j];
        }
    }
    SR = SR.sort.array;
    SC = SC.sort.array;

    long DR = 0, DC = 0;

    BinaryHeap!(Array!long, "a < b") PQ;
    foreach (r; SR) PQ.insert(r);
    long[] R = new long[K + 1];
    R[0] = 0;
    foreach (i; 1 .. K + 1) {
        long r = PQ.front;
        R[i] = R[i - 1] + r;
        PQ.removeFront;
        PQ.insert(r - P * M);
    }

    PQ.clear;
    foreach (c; SC) PQ.insert(c);
    long[] C = new long[K + 1];
    C[0] = 0;
    foreach (i; 1 .. K + 1) {
        long c = PQ.front;
        C[i] = C[i - 1] + c;
        PQ.removeFront;
        PQ.insert(c - P * N);
    }

    /*
    writeln(R);
    writeln(C);
    */

    long Ans = 0;

    foreach (i; 0 .. K + 1) {
        Ans = max(Ans, R[i] + C[K - i] - (i * (K - i) * P));
    }
    writeln(Ans);
}

import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

void main() {
    int N, M, K, P; scanf("%d %d %d %d\n", &N, &M, &K, &P);
    int[][] F = new int[][N];
    foreach (i; 0 .. N) {
        F[i] = readln.chomp.split(" ").map!(to!int).array;
    }
    long[] SR = new long[N],
           SC = new long[M];
    foreach (i; 0 .. N) {
        foreach (j; 0 .. M) {
            SR[i] += F[i][j];
            SC[j] += F[i][j];
        }
    }
    SR = SR.sort.array;
    SC = SC.sort.array;

    struct V {
        int type; // row or column? 1 => row, 2 => column
        long value;
    }
    long DR = 0, DC = 0;
    bool comp(in V a, in V b) {
        long A = a.value - (a.type == 1 ? DR : DC),
             B = b.value - (b.type == 1 ? DR : DC);
        return A < B;
    }

    BinaryHeap!(Array!V, comp) PQ;
    foreach (r; SR) PQ.insert(V(1, r));
    foreach (c; SC) PQ.insert(V(2, c));

    long Calc(in V a) {
        return a.value - (a.type == 1 ? DR : DC);
    }

    long Ans = 0;
    while (K--) {
        V v = PQ.front;
        (v.type == 1 ? DC : DR) += P;
        PQ.insert(V(v.type, v.value - P * (v.type == 1 ? M : N)));
        Ans += Calc(PQ.front);
        PQ.removeFront;
    }
    writeln(Ans);
}

import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

void main() {
    int N, M, K, P; scanf("%d %d %d %d\n", &N, &M, &K, &P);
    int[][] F = new int[][N];
    foreach (i; 0 .. N) {
        F[i] = readln.chomp.split(" ").map!(to!int).array;
    }
    long[] SR = new long[N],
           SC = new long[M];
    foreach (i; 0 .. N) {
        foreach (j; 0 .. M) {
            SR[i] += F[i][j];
            SC[j] += F[i][j];
        }
    }
    SR = SR.sort.array;
    SC = SC.sort.array;

    long DR = 0, DC = 0;

    BinaryHeap!(Array!long, "a < b") PQ;
    foreach (r; SR) PQ.insert(r);
    long[] R = new long[K + 1];
    R[0] = 0;
    foreach (i; 1 .. K + 1) {
        long r = PQ.front;
        R[i] = R[i - 1] + r;
        PQ.removeFront;
        PQ.insert(r - P * M);
    }

    PQ.clear;
    foreach (c; SC) PQ.insert(c);
    long[] C = new long[K + 1];
    C[0] = 0;
    foreach (i; 1 .. K + 1) {
        long c = PQ.front;
        C[i] = C[i - 1] + c;
        PQ.removeFront;
        PQ.insert(c - P * N);
    }

    /*
    writeln(R);
    writeln(C);
    */

    long Ans = 0;

    foreach (i; 0 .. K + 1) {
        Ans = max(Ans, R[i] + C[K - i] - (i * (K - i) * P));
    }
    writeln(Ans);
}

import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

void main() {
    int N, M, K; long P; scanf("%d %d %d %d\n", &N, &M, &K, &P);
    long[][] F = new long[][N];
    foreach (i; 0 .. N) {
        F[i] = readln.chomp.split(" ").map!(to!long).array;
    }
    long[] SR = new long[N],
           SC = new long[M];
    foreach (i; 0 .. N) {
        foreach (j; 0 .. M) {
            SR[i] += F[i][j];
            SC[j] += F[i][j];
        }
    }
    SR = SR.sort.array;
    SC = SC.sort.array;

    long DR = 0, DC = 0;

    BinaryHeap!(Array!long, "a < b") PQ;
    foreach (r; SR) PQ.insert(r);
    long[] R = new long[K + 1];
    R[0] = 0;
    foreach (i; 1 .. K + 1) {
        long r = PQ.front;
        R[i] = R[i - 1] + r;
        PQ.removeFront;
        PQ.insert(r - P * M);
    }

    PQ.clear;
    foreach (c; SC) PQ.insert(c);
    long[] C = new long[K + 1];
    C[0] = 0;
    foreach (i; 1 .. K + 1) {
        long c = PQ.front;
        C[i] = C[i - 1] + c;
        PQ.removeFront;
        PQ.insert(c - P * N);
    }

    /*
    writeln(R);
    writeln(C);
    */

    long Ans = 0;

    foreach (long i; 0 .. K + 1) {
        Ans = max(Ans, R[cast(uint)i] + C[K - cast(uint)i] - (i * (cast(long)K - i) * P));
    }
    writeln(Ans);
}


import std.stdio, std.string;
import std.algorithm;

int gcd(int a, int b)
{
    if (b == 0) return a;
    return gcd(b, a % b);
}

void solve(int[] a)
{
    auto n = cast(int)a.length;
    int c = 0;
    foreach (i; 0 .. n)
    {
        if (a[i] == 1) ++ c;
    }
    if (c > 0)
    {
        writeln(n - c);
        return;
    }
    int ans = int.max;
    foreach (i; 0 .. n)
    {
        auto g = a[i];
        foreach (j; i + 1 .. n)
        {
            if (j - i + n - 1 >= ans) break;
            g = gcd(g, a[j]);
            if (g == 1)
            {
                ans = min(ans, j - i + n - 1);
                break;
            }
        }
    }
    if (ans == int.max) ans = -1;
    writeln(ans);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a);
    }
    return 0;
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio      : readln, writeln;
import std.array      : split;
import std.string     : chomp;
import std.conv       : to;
import std.numeric    : gcd;

void main()
{
    auto n = readln.chomp.to!int;
    auto xs = readln.chomp.split.to!(int[]);

    auto p = xs[0];
    auto e = 0;
    foreach (x; xs)
    {
        p = gcd(p, x);
        if (x == 1)
        {
            e++;
        }
    }
    if (p != 1)
    {
        writeln(-1);
        return;
    }
    if (e > 0)
    {
        writeln(n-e);
        return;
    }
    auto ans = n * 10;
    void dfs(uint i, int c)
    {
        if (c >= ans)
        {
            return;
        }
        if (i > 0)
        {
            auto g = gcd(xs[i], xs[i-1]);
            if (g == 1)
            {
                ans = c;
                return;
            }
            if (xs[i] != g)
            {
                auto t1 = xs[i]; xs[i] = g; dfs(i, c + 1); xs[i] = t1;
            }
            if (xs[i-1] != g)
            {
                auto t2 = xs[i-1]; xs[i-1] = g; dfs(i-1, c+1); xs[i-1] = t2;
            }
        }
        if (i+1 < n)
        {
            auto g = gcd(xs[i], xs[i+1]);
            if (g == 1)
            {
                ans = c;
                return;
            }
            if (xs[i] != g)
            {
                auto t1 = xs[i]; xs[i] = g; dfs(i, c+1); xs[i] = t1;
            }
            if (xs[i+1] != g)
            {
                auto t2 = xs[i+1]; xs[i+1] = g; dfs(i+1, c+1); xs[i+1] = t2;
            }
        }
    }
    foreach (i, _ ; xs)
    {
        dfs(i, 0);
    }
    ans += n;
    writeln(ans);
}

/+ dub.sdl:
    name "A"
    dependency "dcomp" version=">=0.7.4"
+/

import std.stdio, std.algorithm, std.range, std.conv;
import std.numeric : gcd;
// import dcomp.foundation, dcomp.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    int n;
    sc.read(n);
    long[] a;
    sc.read(a);
    int zc = a.count(1).to!int;
    if (zc) {
        writeln(n - zc);
        return 0;
    }
    int ans = 10000;
    foreach (l; 0..n) {
        long g = 0;
        foreach (r; l+1..n+1) {
            g = gcd(g, a[r-1]);
            if (g == 1) {
                ans = min(ans, 2*(r-l-1) + l + (n-r));
            }
        }
    }
    if (ans == 10000) ans = -1;
    writeln(ans);
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}

import core.bitop : popcnt;
static if (!__traits(compiles, popcnt(ulong.max))) {
    public import core.bitop : popcnt;
    int popcnt(ulong v) {
        return popcnt(cast(uint)(v)) + popcnt(cast(uint)(v>>32));
    }
}

bool poppar(ulong v) {
    v^=v>>1;
    v^=v>>2;
    v&=0x1111111111111111UL;
    v*=0x1111111111111111UL;
    return ((v>>60) & 1) != 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.array;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                FastAppender!(E[]) buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

T[N] fixed(T, size_t N)(T[N] a) {return a;}

struct FastAppender(A, size_t MIN = 4) {
    import std.algorithm : max;
    import std.conv;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

    private alias T = ElementEncodingType!A;
    private T* _data;
    private uint len, cap;

    @property size_t length() const {return len;}
    bool empty() const { return len == 0; }

    void reserve(size_t nlen) {
        import core.memory : GC;
        if (nlen <= cap) return;

        void* nx = GC.malloc(nlen * T.sizeof);

        cap = nlen.to!uint;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void opOpAssign(string op : "~")(T item) {
        if (len == cap) {
            reserve(max(MIN, cap*2));
        }
        _data[len++] = item;
    }

    void insertBack(T item) {
        this ~= item;
    }

    void removeBack() {
        len--;
    }

    void clear() {
        len = 0;
    }
    ref inout(T) back() inout { assert(len); return _data[len-1]; }
    ref inout(T) opIndex(size_t i) inout { return _data[i]; }

    T[] data() {
        return (_data) ? _data[0..len] : null;
    }
}

/*
This source code generated by dcomp and include dcomp's source code.
dcomp's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dcomp)
dcomp's License: MIT License(https://github.com/yosupo06/dcomp/blob/master/LICENSE.txt)
*/

import std.algorithm;
import std.array;
import std.conv;
import std.numeric;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		int c = a.count (1);
		if (c > 0)
		{
			writeln (n - c);
			continue;
		}

		int d = n;
		for (int i = 0; i < n; i++)
		{
			int v = a[i];
			for (int j = i + 1; j < n; j++)
			{
				v = gcd (v, a[j]);
				if (v == 1)
				{
					d = min (d, j - i);
					break;
				}
			}
		}
		if (d < n)
		{
			writeln (d + n - 1);
			continue;
		}

		writeln (-1);
	}
}

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();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      int ans = int.max;

      const cnt1 = cast(int)(A.count(1));
      if (cnt1 >= 1) {
        chmin(ans, N - cnt1);
      }

      foreach (i; 0 .. N) {
        long g = 0;
        foreach (j; i .. N) {
          g = gcd(g, A[j]);
          if (g == 1) {
            chmin(ans, (j - i) + (N - 1));
            break;
          }
        }
      }
      writeln((ans >= int.max) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}


import std.stdio;
import std.string;

int main()
{
	int a=0;
	readf(" %d", &a);
	int[] m = new int[a];
	for (int i=0; i<a; i++)
	{
		readf(" %d", &m[i]);
	}
	int max=-1;
	int sum=0;
	for (int i=0; i<a; i++)
	{
		if (m[i]>max)
		{
			max=m[i];
		}
	}
	for (int i=0; i<a; i++)
	{
		sum=sum+m[i];
	}
	writeln(max*(a-1)-(sum-max));
	return 0;
}

import std.stdio;
import std.algorithm;
import std.range;
import std.string;

int [101] mas;
void main(string[] args)
{
    int n = 0;
    int k = 0;
    scanf("%d",&n);
    for(int i = 0; i < n; i++)
    {
        scanf("%d",&mas[i]);
        k = max(k,mas[i]);
    }
    int ans=0;
    for(int i = 0; i < n; i++)
    {
        ans += k - mas[i];
    }
    writeln(ans);
}


import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long[] as = rlong(n);
		log("as:", as);

		long u;
		foreach(a; as) u += a;

		long v;
		foreach(a; as) v ^= (a * 2);

		log("u:", u, "v:", v);

		long[] ans;

		{
			long tmp = 1;
			while(tmp <= u || tmp <= v) tmp *= 2;
			if(u % 2 == 1 && tmp % 2 == 0) tmp += 1;
			if(u % 2 == 0 && tmp % 2 == 1) tmp -= 1;
			log("tmp:", tmp);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			log("ans:", ans, "u:", u, "v:", v);
		}

		if(u < v){
			log("u < v");
			long tmp = (v - u) / 2;
			log("tmp:", tmp);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			log("ans:", ans, "u:", u, "v:", v);
		}

		ans.length.writeln;
		ans.map!(to!string).array.join(" ").writeln;

	}
}

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

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
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; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
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 = 998244353;
//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 t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		if (x % 2 == 1)
		{
			a ~= 1;
			x += 1;
			ans[ti] ~= 1;
		}
		long y;
		foreach (i; 0..a.length)
		{
			y ^= a[i];
		}
		debug writeln("x:", x, " y:", y);
		long tmp;
		foreach (i; 1..64)
		{
			auto bit = 1L << i;
			if (((x >> i) & 1) == ((y >> (i-1)) & 1))
				continue;
			tmp += bit;
			x   += bit;
			y   ^= bit;
		}
		ans[ti] ~= tmp;
	}

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

import std.stdio;
import std.array;
import std.algorithm : map, sum, fold;
import std.string : strip, split;
import std.conv : to;

void main()
{
  int t;
  readf!"%d\n"(t);
  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = readln.strip.split.map!(to!ulong);

    // append at most 3 elements so that s = 2*x (= x<<1)
    auto s = a.sum;
    auto x = a.fold!"a ^ b"(0uL);

    writefln("2\n%d %d", x, s+x);
  }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		auto totalSum = a.reduce !(q{a + b});
		auto totalXor = a.reduce !(q{a ^ b});

		a ~= totalXor;
		totalSum += totalXor;
		totalXor ^= totalXor;

		a ~= totalSum;
		totalXor ^= totalSum;
		totalSum += totalSum;

		writeln (2, " ", a[$ - 2], " ", a[$ - 1]);
	}
}

import std.stdio;
import std.array;
import std.algorithm : map, sum, fold;
import std.string : strip, split;
import std.conv : to;

void main()
{
  int t;
  readf!"%d\n"(t);
  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = readln.strip.split.map!(to!int);

    // append at most 3 elements so that s = 2*x (= x<<1)
    auto s = a.sum;
    auto x = a.fold!"a ^ b"(0);

    writefln("2\n%d %d", x, s+x);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long[] as = rlong(n);
		log("as:", as);

		long u;
		foreach(a; as) u += a;

		long v;
		foreach(a; as) v ^= (a * 2);

		log("u:", u, "v:", v);

		long[] ans;

		{
			long tmp = 1;
			while(tmp <= u || tmp <= v) tmp *= 2;
			if(u % 2 && tmp > 1) tmp += 1;
			log("tmp:", tmp);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			log("ans:", ans, "u:", u, "v:", v);
		}

		if(u < v){
			log("u < v");
			long tmp = (v - u) / 2;
			log("tmp:", tmp);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			log("ans:", ans, "u:", u, "v:", v);
		}

		ans.length.writeln;
		ans.map!(to!string).array.join(" ").writeln;

	}
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long[] as = rlong(n);
		log("as:", as);

		long u;
		foreach(a; as) u += a;

		long v;
		foreach(a; as) v ^= (a * 2);

		log("u:", u, "v:", v);

		long[] ans;
		if(u > v){
			log("u > v");
			long tmp = 1;
			while(tmp <= u) tmp *= 2;
			if(u % 2) tmp += 1;
			log("tmp:", tmp);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			log("ans:", ans, "u:", u, "v:", v);
		}
		if(u < v){
			log("u < v");
			long tmp = (v - u) / 2;
			log("tmp:", tmp);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			ans ~= tmp, u += tmp, v ^= (tmp * 2);
			log("ans:", ans, "u:", u, "v:", v);
		}

		ans.length.writeln;
		ans.map!(to!string).array.join(" ").writeln;

	}
}

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

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
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; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
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 = 998244353;
//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 t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		if (x % 2 == 1)
		{
			a ~= 1;
			x += 1;
			ans[ti] ~= 1;
		}
		long y;
		foreach (i; 0..n)
		{
			y ^= a[i];
		}
		long tmp;
		foreach (i; 1..64)
		{
			auto bit = 1L << i;
			if (((x >> i) & 1) == ((y >> (i-1)) & 1))
				continue;
			tmp += bit;
			x   += bit;
			y   ^= bit;
		}
		ans[ti] ~= tmp;
	}

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


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


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


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

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

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


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

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

	stdout.write(time);
}

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


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


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