Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.

The first line contains single integer n (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers written in the vertices. The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 ≤ pi ≤ n, 1 ≤ wi ≤ 109) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1). It is guaranteed that the given graph is a tree.

Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.

NoteIn the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).

import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		alias Edge = Tuple !(int, q{v}, int, q{w});
		immutable int steps = 18;
		immutable int inf = int.max / 2;
		auto p = new Edge [] [steps];
		p[0] = new Edge [n];
		p[0][0] = Edge (-1, inf);
		auto adj = new int [] [n];
		foreach (i; 1..n)
		{
			int v;
			int w;
			readf (" %s %s", &v, &w);
			v--;
			p[0][i] = Edge (v, w);
			adj[v] ~= i;
		}
		foreach (step; 1..steps)
		{
			p[step] = p[step - 1].dup;
			foreach (i; 0..n)
			{
				int cv = p[step][i].v;
				int cw = p[step][i].w;
				if (cw < inf)
				{
					p[step][i] = Edge (p[step - 1][cv].v,
					    min (inf, p[step - 1][cv].w + cw));
				}
			}
		}

		auto ans = new int [n];
		foreach (i; 0..n)
		{
			int v = i;
			ans[v] += 1;
			foreach_reverse (step; 0..steps)
			{
				if (a[i] >= p[step][v].w)
				{
					a[i] -= p[step][v].w;
					v = p[step][v].v;
				}
			}
			v = p[0][v].v;
			if (v != -1)
			{
				ans[v] -= 1;
			}
		}

		int recur (int v)
		{
			int res = ans[v];
			foreach (u; adj[v])
			{
				res += recur (u);
			}
			ans[v] = res;
			return res;
		}

		recur (0);
		ans[] -= 1;
		writefln ("%(%s %)", ans);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(long)).array;
		alias Edge = Tuple !(int, q{v}, long, q{w});
		immutable int steps = 18;
		immutable long inf = long.max / 2;
		auto p = new Edge [] [steps];
		p[0] = new Edge [n];
		p[0][0] = Edge (-1, inf);
		auto adj = new int [] [n];
		foreach (i; 1..n)
		{
			int v;
			long w;
			readf (" %s %s", &v, &w);
			v--;
			p[0][i] = Edge (v, w);
			adj[v] ~= i;
		}
		debug {writeln (p[0]);}
		foreach (step; 1..steps)
		{
			p[step] = new Edge [n];
			foreach (i; 0..n)
			{
				p[step][i] = p[step - 1][i];
				int cv = p[step][i].v;
				long cw = p[step][i].w;
				if (cw < inf)
				{
					p[step][i] = Edge (p[step - 1][cv].v,
					    p[step - 1][cv].w + cw);
				}
			}
			debug {writeln (p[step]);}
		}

		auto ans = new int [n];
		foreach (i; 0..n)
		{
			int v = i;
			ans[v] += 1;
			foreach_reverse (step; 0..steps)
			{
				if (a[i] >= p[step][v].w)
				{
					a[i] -= p[step][v].w;
					v = p[step][v].v;
				}
			}
			v = p[0][v].v;
			debug {writeln (i, " ", v);}
			if (v != -1)
			{
				ans[v] -= 1;
			}
		}

		int recur (int v)
		{
			debug {writeln (v);}
			int res = ans[v];
			foreach (u; adj[v])
			{
				res += recur (u);
			}
			ans[v] = res;
			return res;
		}

		recur (0);
		ans[] -= 1;
		writefln ("%(%s %)", ans);
	}
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct SegTree {
    long[ ][800_000] _t;
    long[ ][ ] t;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void init(int i, const(long)[ ] a) {
        assert(!a.empty);
        if (a.length == 1)
            t[i] = [a[0]];
        else {
            auto mid = a.length >> 1;
            init(lc(i), a[0 .. mid]);
            init(rc(i), a[mid .. $]);
            t[i] = merge(t[lc(i)], t[rc(i)]).array();
        }
    }

    int countLessEqual(int left, int right, long value) const {
        value++;

        int get(int i, int lb, int rb, int left, int right) {
            if (left >= right)
                return 0;
            if (lb == left && rb == right)
                return cast(int)assumeSorted(t[i][ ]).lowerBound(value).length;
            int mid = (lb + rb) >> 1;
            int a = get(lc(i), lb, mid, left, min(mid, right));
            int b = get(rc(i), mid, rb, max(left, mid), right);
            return a + b;
        }

        return get(0, 0, n, left, right);
    }
}

int gid;
long[200_000] _magic;
long[ ] magic;

struct Node {
    int value;
    long distToRoot;
    int left, right;
    int parentLen;
    Node*[ ] children;

    void calcDist(long d) {
        distToRoot = d + parentLen;
        magic[gid++] = distToRoot - value;
        left = gid;
        foreach (node; children)
            node.calcDist(distToRoot);
        right = gid;
    }
}

int n;
Node[200_000] _nodes;
Node[ ] nodes;
SegTree sgt;

void main() {
    _nodes[0].parentLen = 0;
    while (read(&n)) {
        nodes = _nodes[0 .. n];
        magic = _magic[0 .. n];
        version (LocalProject)
            foreach (ref node; nodes)
                node.children = null;
        foreach (ref node; nodes)
            read(&node.value);
        foreach (ref node; nodes[1 .. $]) {
            int p, w;
            read(&p, &w);
            p--;
            node.parentLen = w;
            nodes[p].children ~= &node;
        }
        gid = 0;
        nodes[0].calcDist(0);
        debug writeln(magic);
        //debug foreach (ref node; nodes)
        //    writeln(node);
        sgt.t = sgt._t[0 .. n << 2];
        version (LocalProject)
            foreach (ref ls; sgt.t)
                ls = null;
        sgt.init(0, magic);
        foreach (ref node; nodes) {
            debug write(node.left, "..", node.right, ':', node.distToRoot, '@');
            write(sgt.countLessEqual(node.left, node.right, node.distToRoot), ' ');
        }
        writeln();
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

/+
int myUpperBound(R, T)(R range, T value) if (isRandomAccessRange!R) {
    int left = 0, right = cast(int)range.length;
    while (left != right) {
        int mid = (left + right) >> 1;
        if (value >= range[mid])
            left = mid + 1;
        else
            right = mid;
    }
    return left;
}
+/

struct SegTree {
    //Array!(Array!long) t;
    long[ ][800_000] _t;
    long[ ][ ] t;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void init(int i, const(long)[ ] a) {
        assert(!a.empty);
        if (a.length == 1)
            t[i] = [a[0]];
        else {
            auto mid = a.length >> 1;
            init(lc(i), a[0 .. mid]);
            init(rc(i), a[mid .. $]);
            //t[i] = Array!long(merge(t[lc(i)][ ], t[rc(i)][ ]));
            t[i] = merge(t[lc(i)], t[rc(i)]).array();
        }
    }

    int countLessEqual(int left, int right, long value) const {
        value++;

        int get(int i, int lb, int rb, int left, int right) {
            if (left >= right)
                return 0;
            if (lb == left && rb == right)
                return cast(int)assumeSorted(t[i][ ]).lowerBound(value).length;
                /+return myUpperBound(t[i], value);+/
            int mid = (lb + rb) >> 1;
            int a = get(lc(i), lb, mid, left, min(mid, right));
            int b = get(rc(i), mid, rb, max(left, mid), right);
            return a + b;
        }

        return get(0, 0, n, left, right);
    }
}

int gid;
long[200_000] _magic;
long[ ] magic;

struct Node {
    int value;
    long distToRoot;
    int left, right;
    int parentLen;
    //Array!(Node*) children;
    Node*[ ] children;

    void calcDist(long d) {
        distToRoot = d + parentLen;
        magic[gid++] = distToRoot - value;
        left = gid;
        foreach (node; children)
            node.calcDist(distToRoot);
        right = gid;
    }
}

int n;
Node[200_000] _nodes;
Node[ ] nodes;
SegTree sgt;

void main() {
    _nodes[0].parentLen = 0;
    while (scanf("%d", &n) == 1) {
        nodes = _nodes[0 .. n];
        magic = _magic[0 .. n];
        version (LocalProject)
            foreach (ref node; nodes)
                /+node.children.clear();+/
                node.children = null;
        foreach (ref node; nodes)
            scanf("%d", &node.value);
        foreach (ref node; nodes[1 .. $]) {
            int p, w;
            scanf("%d%d", &p, &w);
            p--;
            node.parentLen = w;
            nodes[p].children ~= &node;
        }
        gid = 0;
        nodes[0].calcDist(0);
        debug writeln(magic);
        //debug foreach (ref node; nodes)
        //    writeln(node);
        //sgt.t.clear();
        //sgt.t.length = n << 2;
        sgt.t = sgt._t[0 .. n << 2];
        version (LocalProject)
            foreach (ref ls; sgt.t)
                ls = null;
        sgt.init(0, magic);
        foreach (ref node; nodes) {
            debug write(node.left, "..", node.right, ':', node.distToRoot, '@');
            printf("%d ", sgt.countLessEqual(node.left, node.right, node.distToRoot));
        }
        putchar('\n');
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct SegTree {
    long[ ][800_000] _t;
    long[ ][ ] t;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void init(int i, const(long)[ ] a) {
        assert(!a.empty);
        if (a.length == 1)
            t[i] = [a[0]];
        else {
            auto mid = a.length >> 1;
            init(lc(i), a[0 .. mid]);
            init(rc(i), a[mid .. $]);
            t[i] = merge(t[lc(i)], t[rc(i)]).array();
        }
    }

    int countLessEqual(int left, int right, long value) const {
        value++;

        int get(int i, int lb, int rb, int left, int right) {
            if (left >= right)
                return 0;
            if (lb == left && rb == right)
                return cast(int)assumeSorted(t[i][ ]).lowerBound(value).length;
            int mid = (lb + rb) >> 1;
            int a = get(lc(i), lb, mid, left, min(mid, right));
            int b = get(rc(i), mid, rb, max(left, mid), right);
            return a + b;
        }

        return get(0, 0, n, left, right);
    }
}

int gid;
long[200_000] _magic;
long[ ] magic;

struct Node {
    int value;
    long distToRoot;
    int left, right;
    int parentLen;
    Node*[ ] children;

    void calcDist(long d) {
        distToRoot = d + parentLen;
        magic[gid++] = distToRoot - value;
        left = gid;
        foreach (node; children)
            node.calcDist(distToRoot);
        right = gid;
    }
}

int n;
Node[200_000] _nodes;
Node[ ] nodes;
int[199_999] _parents;
int[ ] parents;
Node*[199_999] _children;
Node*[ ] children;
SegTree sgt;

void main() {
    _nodes[0].parentLen = 0;
    while (scanf("%d", &n) == 1) {
        nodes = _nodes[0 .. n];
        magic = _magic[0 .. n];
        children = _children[0 .. n - 1];
        parents = _parents[0 .. n - 1];
        version (LocalProject)
            foreach (ref node; nodes)
                node.children = null;
        foreach (ref node; nodes)
            scanf("%d", &node.value);
        foreach (ref node, ref child, ref parent; lockstep(nodes[1 .. $], children, parents)) {
            child = &node;
            scanf("%d%d", &parent, &node.parentLen);
            parent--;
        }
        auto z = zip(parents, children);
        z.sort!`a[0] < b[0]`;
        int last = 0;
        foreach (pc, count; z.group!`a[0] == b[0]`) {
            nodes[pc[0]].children = children[last .. last + count];
            last += count;
        }
        gid = 0;
        nodes[0].calcDist(0);
        debug writeln(magic);
        //debug foreach (ref node; nodes)
        //    writeln(node);
        sgt.t = sgt._t[0 .. n << 2];
        version (LocalProject)
            foreach (ref ls; sgt.t)
                ls = null;
        sgt.init(0, magic);
        foreach (ref node; nodes) {
            debug write(node.left, "..", node.right, ':', node.distToRoot, '@');
            printf("%d ", sgt.countLessEqual(node.left, node.right, node.distToRoot));
        }
        putchar('\n');
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int myUpperBound(R, T)(R range, T value) if (isRandomAccessRange!R) {
    int left = 0, right = cast(int)range.length;
    while (left != right) {
        int mid = (left + right) >> 1;
        if (value >= range[mid])
            left = mid + 1;
        else
            right = mid;
    }
    return left;
}

struct SegTree {
    //Array!(Array!long) t;
    long[ ][800_000] _t;
    long[ ][ ] t;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void init(int i, const(long)[ ] a) {
        assert(!a.empty);
        if (a.length == 1)
            t[i] ~= a[0];
        else {
            auto mid = a.length >> 1;
            init(lc(i), a[0 .. mid]);
            init(rc(i), a[mid .. $]);
            //t[i] = Array!long(merge(t[lc(i)][ ], t[rc(i)][ ]));
            t[i] = merge(t[lc(i)], t[rc(i)]).array();
        }
    }

    int countLessEqual(int left, int right, long value) const {
        //value++;

        int get(int i, int lb, int rb, int left, int right) {
            if (left >= right)
                return 0;
            if (lb == left && rb == right)
                /+return cast(int)assumeSorted(t[i][ ]).lowerBound(value).length;+/
                return myUpperBound(t[i], value);
            int mid = (lb + rb) >> 1;
            int a = get(lc(i), lb, mid, left, min(mid, right));
            int b = get(rc(i), mid, rb, max(left, mid), right);
            return a + b;
        }

        return get(0, 0, n, left, right);
    }
}

int gid;
long[200_000] _magic;
long[ ] magic;

struct Node {
    int value;
    long distToRoot;
    int left, right;
    int parentLen;
    //Array!(Node*) children;
    Node*[ ] children;

    void calcDist(long d) {
        distToRoot = d + parentLen;
        magic[gid++] = distToRoot - value;
        left = gid;
        foreach (node; children)
            node.calcDist(distToRoot);
        right = gid;
    }
}

int n;
Node[200_000] _nodes;
Node[ ] nodes;
SegTree sgt;

void main() {
    _nodes[0].parentLen = 0;
    while (scanf("%d", &n) == 1) {
        nodes = _nodes[0 .. n];
        magic = _magic[0 .. n];
        version (LocalProject)
            foreach (ref node; nodes)
                /+node.children.clear();+/
                node.children = null;
        foreach (ref node; nodes)
            scanf("%d", &node.value);
        foreach (ref node; nodes[1 .. $]) {
            int p, w;
            scanf("%d%d", &p, &w);
            p--;
            node.parentLen = w;
            nodes[p].children ~= &node;
        }
        gid = 0;
        nodes[0].calcDist(0);
        debug writeln(magic);
        //debug foreach (ref node; nodes)
        //    writeln(node);
        //sgt.t.clear();
        //sgt.t.length = n << 2;
        sgt.t = sgt._t[0 .. n << 2];
        version (LocalProject)
            foreach (ref ls; sgt.t)
                ls = null;
        sgt.init(0, magic);
        foreach (ref node; nodes) {
            debug write(node.left, "..", node.right, ':', node.distToRoot, '@');
            printf("%d ", sgt.countLessEqual(node.left, node.right, node.distToRoot));
        }
        putchar('\n');
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int myUpperBound(R, T)(R range, T value) if (isRandomAccessRange!R) {
    int left = 0, right = cast(int)range.length;
    while (left != right) {
        int mid = (left + right) >> 1;
        if (value >= range[mid])
            left = mid + 1;
        else
            right = mid;
    }
    return left;
}

struct SegTree {
    Array!(Array!long) t;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void init(int i, const(long)[ ] a) {
        assert(!a.empty);
        if (a.length == 1)
            t[i] ~= a[0];
        else {
            auto mid = a.length >> 1;
            init(lc(i), a[0 .. mid]);
            init(rc(i), a[mid .. $]);
            t[i] = Array!long(merge(t[lc(i)][ ], t[rc(i)][ ]));
        }
    }

    int countLessEqual(int left, int right, long value) const {
        //value++;

        int get(int i, int lb, int rb, int left, int right) {
            if (left >= right)
                return 0;
            if (lb == left && rb == right)
                /+return cast(int)assumeSorted(t[i][ ]).lowerBound(value).length;+/
                return myUpperBound(t[i][ ], value);
            int mid = (lb + rb) >> 1;
            int a = get(lc(i), lb, mid, left, min(mid, right));
            int b = get(rc(i), mid, rb, max(left, mid), right);
            return a + b;
        }

        return get(0, 0, n, left, right);
    }
}

int gid;
long[200_000] _magic;
long[ ] magic;

struct Node {
    int value;
    long distToRoot;
    int left, right;
    int parentLen;
    Array!(Node*) children;

    void calcDist(long d) {
        distToRoot = d + parentLen;
        magic[gid++] = distToRoot - value;
        left = gid;
        foreach (node; children)
            node.calcDist(distToRoot);
        right = gid;
    }
}

int n;
Node[200_000] _nodes;
Node[ ] nodes;
SegTree sgt;

void main() {
    _nodes[0].parentLen = 0;
    while (scanf("%d", &n) == 1) {
        nodes = _nodes[0 .. n];
        magic = _magic[0 .. n];
        version (LocalProject)
            foreach (ref node; nodes)
                node.children.clear();
        foreach (ref node; nodes)
            scanf("%d", &node.value);
        foreach (ref node; nodes[1 .. $]) {
            int p, w;
            scanf("%d%d", &p, &w);
            p--;
            node.parentLen = w;
            nodes[p].children ~= &node;
        }
        gid = 0;
        nodes[0].calcDist(0);
        debug writeln(magic);
        //debug foreach (ref node; nodes)
        //    writeln(node);
        sgt.t.clear();
        sgt.t.length = n << 2;
        sgt.init(0, magic);
        foreach (ref node; nodes) {
            debug write(node.left, "..", node.right, ':', node.distToRoot, '@');
            printf("%d ", sgt.countLessEqual(node.left, node.right, node.distToRoot));
        }
        putchar('\n');
        debug writeln();
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		alias Edge = Tuple !(int, q{v}, int, q{w});
		immutable int steps = 18;
		immutable int inf = int.max / 2;
		auto p = new Edge [] [steps];
		p[0] = new Edge [n];
		p[0][0] = Edge (-1, inf);
		auto adj = new int [] [n];
		foreach (i; 1..n)
		{
			int v;
			int w;
			readf (" %s %s", &v, &w);
			v--;
			p[0][i] = Edge (v, w);
			adj[v] ~= i;
		}
		debug {writeln (p[0]);}
		foreach (step; 1..steps)
		{
			p[step] = new Edge [n];
			foreach (i; 0..n)
			{
				p[step][i] = p[step - 1][i];
				int cv = p[step][i].v;
				int cw = p[step][i].w;
				if (cw < inf)
				{
					p[step][i] = Edge (p[step - 1][cv].v,
					    p[step - 1][cv].w + cw);
				}
			}
			debug {writeln (p[step]);}
		}

		auto ans = new int [n];
		foreach (i; 0..n)
		{
			int v = i;
			ans[v] += 1;
			foreach_reverse (step; 0..steps)
			{
				if (a[i] >= p[step][v].w)
				{
					a[i] -= p[step][v].w;
					v = p[step][v].v;
				}
			}
			v = p[0][v].v;
			debug {writeln (i, " ", v);}
			if (v != -1)
			{
				ans[v] -= 1;
			}
		}

		int recur (int v)
		{
			debug {writeln (v);}
			int res = ans[v];
			foreach (u; adj[v])
			{
				res += recur (u);
			}
			ans[v] = res;
			return res;
		}

		recur (0);
		ans[] -= 1;
		writefln ("%(%s %)", ans);
	}
}


This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$. Can he succeed?Note that he has to perform this operation exactly once. He has to perform this operation.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal and "No" otherwise. You can print each letter in any case (upper or lower).

4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca

NoteIn the first test case, Ujan can swap characters $$$s_1$$$ and $$$t_4$$$, obtaining the word "house".In the second test case, it is not possible to make the strings equal using exactly one swap of $$$s_i$$$ and $$$t_j$$$.

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

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 k = RD!int;
	auto ans = new bool[](k);
	foreach (i; 0..k)
	{
		auto n = RD!int;
		auto s = RD!string;
		auto t = RD!string;
		int[2] pos;
		int cnt;
		foreach (j; 0..n)
		{
			if (s[j] != t[j])
			{
				++cnt;
				if (cnt >= 3) break;
				pos[cnt-1] = j;
			}
		}
		if (cnt == 2)
		{
			auto p1 = pos[0];
			auto p2 = pos[1];
			if (s[p1] == s[p2] && t[p1] == t[p2])
				ans[i] = true;
		}
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush();
	debug readln();
}

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

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 k = RD!int;
	auto ans = new bool[](k);
	foreach (i; 0..k)
	{
		auto n = RD!int;
		auto s = RD!string;
		auto t = RD!string;
		int[2] pos;
		int cnt;
		foreach (j; 0..n)
		{
			if (s[j] != t[j])
			{
				++cnt;
				if (cnt >= 3) break;
				pos[cnt-1] = j;
			}
		}
		if (cnt == 2)
		{
			auto p1 = pos[0];
			auto p2 = pos[1];
			auto c = new int[](26);
			++c[s[p1]-'a'];
			++c[s[p2]-'a'];
			++c[t[p1]-'a'];
			++c[t[p2]-'a'];
			int c2;
			foreach (e; c)
			{
				if (e == 2)
					++c2;
			}
			if (c2 == 2)
				ans[i] = true;
		}
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush();
	debug readln();
}


You are given an array $$$a$$$ with $$$n$$$ integers. You can perform the following operation at most $$$k$$$ times:  Choose two indices $$$i$$$ and $$$j$$$, in which $$$i \,\bmod\, k = j \,\bmod\, k$$$ ($$$1 \le i < j \le n$$$).  Swap $$$a_i$$$ and $$$a_j$$$. After performing all operations, you have to select $$$k$$$ consecutive elements, and the sum of the $$$k$$$ elements becomes your score. Find the maximum score you can get.Here $$$x \bmod y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 600$$$) — the number of test cases. Each test case consists of two lines.  The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the length of the array and the number in the statement above. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$)  — the array itself.

For each test case, print the maximum score you can get, one per line.

NoteIn the first test case, we can get a score of $$$11$$$ if we select $$$a_1, a_2$$$ without performing any operations.In the third test case, we can get a score of $$$15$$$ if we first swap $$$a_1$$$ with $$$a_4$$$ and then select $$$a_3, a_4, a_5$$$.

import std;

void main()
{
    int w;
    scanf("%d\n", &w);
    foreach(_; 0..w)
    {
        int n,k;
        scanf("%d %d\n", &n, &k);
        auto a = readln.split.to!(long[]);
        if (n == k) {
            writeln(a.sum);
            continue;
        }
        long[] res = new long[k];
        foreach(i; 0 .. n)
            if (res[i % k] < a[i])
                res[i % k] = a[i];
        writeln(res.sum);
    }
}


Polycarp likes arithmetic progressions. A sequence $$$[a_1, a_2, \dots, a_n]$$$ is called an arithmetic progression if for each $$$i$$$ ($$$1 \le i < n$$$) the value $$$a_{i+1} - a_i$$$ is the same. For example, the sequences $$$[42]$$$, $$$[5, 5, 5]$$$, $$$[2, 11, 20, 29]$$$ and $$$[3, 2, 1, 0]$$$ are arithmetic progressions, but $$$[1, 0, 1]$$$, $$$[1, 3, 9]$$$ and $$$[2, 3, 1]$$$ are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers $$$[b_1, b_2, \dots, b_n]$$$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $$$1$$$, an element can be increased by $$$1$$$, an element can be left unchanged.Determine a minimum possible number of elements in $$$b$$$ which can be changed (by exactly one), so that the sequence $$$b$$$ becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals $$$0$$$.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 100\,000)$$$ — the number of elements in $$$b$$$. The second line contains a sequence $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 10^{9})$$$.

If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).

NoteIn the first example Polycarp should increase the first number on $$$1$$$, decrease the second number on $$$1$$$, increase the third number on $$$1$$$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $$$[25, 20, 15, 10]$$$, which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $$$[0, 3, 6, 9, 12]$$$, which is an arithmetic progression.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		if (n < 3)
		{
			writeln (0);
			continue;
		}
		auto d = a[1] - a[0];
		int res = n + 1;
		foreach (long delta; d - 2..d + 3)
		{
			foreach (start; a[0] - 1..a[0] + 2)
			{
				auto v = sequence !((r, k) =>
				    start + k * delta);
				int cur = 0;
				foreach (x, y; zip (a, v))
				{
					if (abs (x - y) > 1)
					{
						cur = n + 1;
					}
					else
					{
						cur += abs (x - y);
					}
				}
				res = min (res, cur);
			}
		}
		if (res > n)
		{
			res = -1;
		}
		writeln (res);
	}
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;
  import std.array, std.math;

  int n; rd(n);
  auto as=readln.split.to!(long[]);

  if(n<=2){
    writeln(0);
    return;
  }

  long[] cand;
  for(long dx=-1; dx<=1; dx++){
    for(long dy=-1; dy<=1; dy++){
      cand~=((as[1]+dx)-(as[0]+dy));
    }
  }
  cand=cand.sort.uniq.array;
  int mn=1_000_000_000;
  foreach(diff; cand)for(long init_diff=-1; init_diff<=1; init_diff++){
    auto pre=as[0]+init_diff;
    int cnt=init_diff.abs.to!(int);
    foreach(i; 1..n){
      bool found=false;
      for(long d=-1; d<=1; d++){
        if((as[i]+d)-(pre)==diff){
          pre=as[i]+d;
          cnt+=d.abs;
          found=true;
          break;
        }
      }
      if(found==false) goto hell;
    }
    mn=min(mn, cnt);
    hell:;
  }

  if(mn<=n) writeln(mn);
  else writeln(-1);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


You are given an array $$$d_1, d_2, \dots, d_n$$$ consisting of $$$n$$$ integer numbers.Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $$$sum_1$$$, the sum of elements of the second part be $$$sum_2$$$ and the sum of elements of the third part be $$$sum_3$$$. Among all possible ways to split the array you have to choose a way such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.More formally, if the first part of the array contains $$$a$$$ elements, the second part of the array contains $$$b$$$ elements and the third part contains $$$c$$$ elements, then:$$$$$$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$$$$$ $$$$$$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$$$$$ $$$$$$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$$$$$The sum of an empty array is $$$0$$$.Your task is to find a way to split the array such that $$$sum_1 = sum_3$$$ and $$$sum_1$$$ is maximum possible.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$d$$$. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$) — the elements of the array $$$d$$$.

Print a single integer — the maximum possible value of $$$sum_1$$$, considering that the condition $$$sum_1 = sum_3$$$ must be met. Obviously, at least one valid way to split the array exists (use $$$a=c=0$$$ and $$$b=n$$$).

NoteIn the first example there is only one possible splitting which maximizes $$$sum_1$$$: $$$[1, 3, 1], [~], [1, 4]$$$.In the second example the only way to have $$$sum_1=4$$$ is: $$$[1, 3], [2, 1], [4]$$$.In the third example there is only one way to split the array: $$$[~], [4, 1, 2], [~]$$$.

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!long).array;

    auto sumr = arr.dup.retro.cumulativeFold!((a, b) => a + b);

    bool [long] r;
    sumr.array.each!(x => r[x] = true);

    debug { sumr.writeln; r.writeln; }

    immutable long mxsum = arr.sum;
    long ans = 0, cursum = 0;
    foreach (e; arr) {
        r.remove(mxsum - cursum);
        cursum += e;

        if (cursum in r) ans = max(ans, cursum);
    }

    ans.writeln;
}


Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.You're given $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. Using each of them exactly at once, you're to make such sequence $$$b_1, b_2, \dots, b_n$$$ that sequence $$$c_1, c_2, \dots, c_n$$$ is lexicographically maximal, where $$$c_i=GCD(b_1,\dots,b_i)$$$ - the greatest common divisor of the first $$$i$$$ elements of $$$b$$$. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$)  — the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\dots,a_n$$$ ($$$1 \le a_i \le 10^3$$$)  — the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case output the answer in a single line  — the desired sequence $$$b$$$. If there are multiple answers, print any.

NoteIn the first test case of the example, there are only two possible permutations $$$b$$$  — $$$[2, 5]$$$ and $$$[5, 2]$$$: for the first one $$$c=[2, 1]$$$, for the second one $$$c=[5, 1]$$$.In the third test case of the example, number $$$9$$$ should be the first in $$$b$$$, and $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, so the second number of $$$b$$$ should be $$$3$$$.In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation $$$b$$$.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] token;
T rd(T = long)() { while(!token.length) token = readln.chomp.split; string res = token[0]; token.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    ll[] ray;
    arr.sort();
    arr.reverse();
    ll maxel = arr[0];
    bool[long] vis;
    int maxi = 0;
    foreach(i; 0..arr.length){
        if(arr[i] >= maxel){
            maxel = arr[i];
            maxi = to!int(i);
        }
        vis[i] = 0;
    }
    ray ~= maxel;
    vis[maxi] = 1;
    ll cnt = 1;
    ll gcdall = maxel;
    while(cnt < n){
        ll maxgcd = 1;
        foreach(j; 0..n){
            if(!vis[j] && gcd(gcdall, arr[j]) >= maxgcd){
                maxgcd = gcd(gcdall, arr[j]);
                maxi = j;
            }
        }
        ray ~= arr[maxi];
        vis[maxi] = 1;
        gcdall = maxgcd;
        ++cnt;
    }
    foreach(el; ray){
        write(el, " ");
    }
    writeln;
}

int main(){
    ll t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

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; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }

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.maxElement;
		auto used = new bool[](n);
		foreach (i; 0..n)
		{
			long best;
			int pos;
			foreach (j; 0..n)
			{
				if (used[j]) continue;
				auto tmp = gcd(x, a[j]);
				debug writeln("tmp:", tmp);
				if (tmp > best)
				{
					best = tmp;
					pos = j;
				}
			}
			debug writeln("a[pos]:", a[pos], " best:", best);
			ans[ti] ~= a[pos];
			used[pos] = true;
			x = best;
		}
	}

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

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; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }

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.maxElement;
		auto c = new long[](n);
		foreach (i; 0..n)
		{
			c[i] = gcd(x, a[i]);
		}

		auto index = c.MAKE_IDX!"a > b";
		ans[ti].length = n;
		foreach (ii, i; index)
			ans[ti][ii] = a[i];
	}

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


It's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over time — its community rating. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by +1 or -1.Consider the following model of Codeforces users' behavior. The i-th user has his own estimated blog post rating denoted by an integer ai. When a user visits a blog post page, he compares his estimated blog post rating to its community rating. If his estimated rating is higher, he rates the blog post with +1 (thus, the blog post's community rating increases by 1). If his estimated rating is lower, he rates the blog post with -1 (decreasing its community rating by 1). If the estimated rating and the community rating are equal, user doesn't rate the blog post at all (in this case we'll say that user rates the blog post for 0). In any case, after this procedure user closes the blog post page and never opens it again.Consider a newly created blog post with the initial community rating of 0. For each of n Codeforces users, numbered from 1 to n, his estimated blog post rating ai is known.For each k from 1 to n, inclusive, the following question is asked. Let users with indices from 1 to k, in some order, visit the blog post page, rate the blog post and close the page. Each user opens the blog post only after the previous user closes it. What could be the maximum possible community rating of the blog post after these k visits?

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of Codeforces users. The second line contains n integers a1, a2, ..., an ( - 5·105 ≤ ai ≤ 5·105) — estimated blog post ratings for users in order from 1 to n.

For each k from 1 to n, output a single integer equal to the maximum possible community rating of the blog post after users with indices from 1 to k, in some order, visit the blog post page, rate the blog post, and close the page.

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 bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

// min pos s.t. pred(sum of [0, pos))
//   assume pred(sum of [0, pos)) is non-decreasing
int bBinarySearch(alias pred, T)(T[] bit) {
  import core.bitop : bsr;
  import std.functional : unaryFun;
  alias predFun = unaryFun!pred;
  if (predFun(0)) return 0;
  int pos = 0;
  T sum = 0;
  foreach_reverse (e; 0 .. bsr(bit.length) + 1) {
    const x = (pos | 1 << e) - 1;
    if (x < bit.length && !predFun(sum + bit[x])) {
      pos |= 1 << e;
      sum += bit[x];
    }
  }
  return pos + 1;
}

// T: monoid
// op: T * T -> T
// query(a, b): returns t_a ... t_{b-1}
class SegmentTree(T, alias op) {
  import std.functional : binaryFun;
  alias opFun = binaryFun!op;
  const(T) idT;

  int n;
  T[] ts;
  this(int n_, const(T) idT) {
    this.idT = idT;
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[] = idT;
  }
  this(inout(T)[] ts_, const(T) idT) {
    this.idT = idT;
    const n_ = cast(int)(ts_.length);
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[0 .. n] = idT;
    ts[n .. n + n_] = ts_[];
    ts[n + n_ .. n << 1] = idT;
    build();
  }
  ref T at(int a) {
    return ts[n + a];
  }
  void build() {
    foreach_reverse (a; 1 .. n) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void set(int a, const(T) val) {
    ts[a += n] = val;
    for (; a >>= 1; ) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void mulL(int a, const(T) val) {
    set(a, opFun(val, ts[a + n]));
  }
  void mulR(int a, const(T) val) {
    set(a, opFun(ts[a + n], val));
  }
  T query(int a, int b) const {
    T prodL = idT, prodR = idT;
    for (a += n, b += n; a < b; a >>= 1, b >>= 1) {
      if (a & 1) prodL = opFun(prodL, ts[a++]);
      if (b & 1) prodR = opFun(ts[--b], prodR);
    }
    return opFun(prodL, prodR);
  }
}

// t -> min(t + p, q);
alias Func = Tuple!(int, "p", int, "q");

enum IDENTITY = Func(0, 10^^9);

// g \circ f
Func mul(const(Func) f, const(Func) g) {
  return Func(f.p + g.p, min(f.q + g.p, g.q));
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }

      alias Entry = Tuple!(int, "a", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(A[i], i);
      }
      es.sort;
      es ~= Entry(int.max, -1);
      auto poss = new int[N];
      foreach (j; 0 .. N) {
        poss[es[j].i] = j;
      }
      debug {
        writeln("es = ", es);
      }

      auto bitNum = new int[N];
      int get(int l) {
        const res = bitNum.bBinarySearch!(sum => (sum >= l + 1));
        return res - 1;
      }

      auto seg = new SegmentTree!(Func, mul)(N, IDENTITY);

      int k;
      foreach (n; 1 .. N + 1) {
        const i = n - 1;
        bitNum.bAdd(poss[i], 1);
        seg.set(poss[i], Func(1, A[i]));
        for (; k < n && -k > es[get(k)].a; ++k) {}
        debug {
          writefln("%s: %s", A[0 .. n].dup.sort, k);
        }
        const res = seg.query(get(k), N);
        const ans = min(-k + res.p, res.q);
        writeln(ans);
      }

      debug {
        auto brt = new int[N + 1];
        brt[] = -N;
        foreach (n; 0 .. N + 1) {
          auto perm = A[0 .. n].dup;
          perm.sort;
          do {
            int x;
            foreach (a; perm) {
              if (x < a) {
                ++x;
              } else if (x > a) {
                --x;
              }
            }
            chmax(brt[n], x);
          } while (perm.nextPermutation);
        }
        foreach (n; 0 .. N + 1) {
          auto perm = A[0 .. n].dup;
          perm.sort;
          do {
            int x;
            int[] ds;
            foreach (a; perm) {
              if (x < a) {
                ++x;
                ds ~= +1;
              } else if (x > a) {
                --x;
                ds ~= -1;
              } else {
                ds ~= 0;
              }
            }
            if (brt[n] == x) {
              // writeln(perm, " ", ds);
            }
          } while (perm.nextPermutation);
        }
        writeln("brt = ", brt);
      }
    }
  } catch (EOFException e) {
  }
}


One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?

The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.

In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new long [n];
		long m = -1;
		long s = 0;
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
			m = max (m, a[i]);
			s += a[i];
		}
		long res = max (m, (s + n - 2) / (n - 1));
		writeln (res);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		int m = -1;
		long s = 0;
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
			m = max (m, a[i]);
			s += a[i];
		}
		int res = m;
		if (n * cast (long) (m - 1) < s)
		{
			res += 1;
		}
		writeln (res);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		int m = -1;
		long s = 0;
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
			m = max (m, a[i]);
			s += a[i];
		}
		int res = m;
		if ((n - 1) * cast (long) m < s)
		{
			res += 1;
		}
		writeln (res);
	}
}


Bob decided to take a break from calculus homework and designed a game for himself. The game is played on a sequence of piles of stones, which can be described with a sequence of integers $$$s_1, \ldots, s_k$$$, where $$$s_i$$$ is the number of stones in the $$$i$$$-th pile. On each turn, Bob picks a pair of non-empty adjacent piles $$$i$$$ and $$$i+1$$$ and takes one stone from each. If a pile becomes empty, its adjacent piles do not become adjacent. The game ends when Bob can't make turns anymore. Bob considers himself a winner if at the end all piles are empty.We consider a sequence of piles winning if Bob can start with it and win with some sequence of moves.You are given a sequence $$$a_1, \ldots, a_n$$$, count the number of subsegments of $$$a$$$ that describe a winning sequence of piles. In other words find the number of segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$), such that the sequence $$$a_l, a_{l+1}, \ldots, a_r$$$ is winning.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

Print a single integer for each test case — the answer to the problem.

NoteIn the first test case, Bob can't win on subsegments of length $$$1$$$, as there is no pair of adjacent piles in an array of length $$$1$$$.In the second test case, every subsegment is not winning.In the fourth test case, the subsegment $$$[1, 4]$$$ is winning, because Bob can make moves with pairs of adjacent piles: $$$(2, 3)$$$, $$$(1, 2)$$$, $$$(3, 4)$$$. Another winning subsegment is $$$[2, 3]$$$.

import std;
void main() {
	foreach (_; 0..readln.strip.to!int) {
		readln;
		int [long] z;
		auto t = redBlackTree!long;
		long m = 1, d, r;
		alias u = x => (x - d) * m, v = x => x * m + d;
		foreach (c; readln.splitter.map!(to!long)) {
			m *= -1, d = c - d;
			while (!t.empty && v(t.front) < 0) z.remove(t.front), t.removeFront;
			while (!t.empty && v(t.back) < 0) z.remove(t.back), t.removeBack;
			t.insert(u(c)), z[u(c)] += 1, r += z.get(u(0), 0);
		}
		r.writeln;
	}
}

import std.algorithm, std.container, std.conv, std.range, std.stdio, std.string;
void main () {
	foreach (test; 0..readln.strip.to !(int)) {
		readln;
		int [long] z;
		auto t = redBlackTree !(long);
		long m = 1, d, r;
		alias u = x => (x - d) * m;
		alias v = x => x * m + d;
		foreach (c; readln.splitter.map !(to !(long))) {
			m *= -1;
			d = c - d;
			while (!t.empty && v (t.front) < 0) z.remove (t.front), t.removeFront ();
			while (!t.empty && v (t.back) < 0) z.remove (t.back), t.removeBack ();
			t.insert (u (c));
			z[u (c)] += 1;
			r += z.get (u (0), 0);
		}
		writeln (r);
	}
}

import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

struct Storage
{
	int [long] num;
	RedBlackTree !(long) t = redBlackTree !(long);
	int mult = +1;
	long delta = 0L;

	long encode (long value)
	{
		return (value - delta) * mult;
	}

	long decode (long value)
	{
		return value * mult + delta;
	}

	void insert (long value)
	{
		value = encode (value);
		t.insert (value);
		num[value] += 1;
	}

	void cleanup ()
	{
		while (!t.empty && decode (t.front) < 0L)
		{
			num.remove (t.front);
			t.removeFront ();
		}

		while (!t.empty && decode (t.back) < 0L)
		{
			num.remove (t.back);
			t.removeBack ();
		}
	}

	int curAnswer ()
	{
		return num.get (encode (0L), 0);
	}

	void invertAll ()
	{
		mult *= -1;
		delta *= -1;
	}

	void addToAll (long value)
	{
		delta += value;
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;

		Storage s;
		long res = 0L;
		foreach (i, ref cur; a)
		{
			s.invertAll ();
			s.addToAll (cur);
			s.cleanup ();
			s.insert (cur);
			res += s.curAnswer ();
		}
		writeln (res);
	}
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = new int[](n+1);
	foreach(i; 1 .. n + 1) a[i] = readInt!int;
	auto cSum = new long[](n+1);
	cSum[0] = 0;
	foreach(i; 1 .. n+1)
	{
		if (i&1) cSum[i] = cSum[i-1] - a[i];
		else cSum[i] = cSum[i-1] + a[i];
	}
	auto only1Max = new long[](n+1); only1Max[] = long.min;
	auto only0Max = new long[](n+1); only0Max[] = long.min;
	auto only1Min = new long[](n+1); only1Min[] = long.max;
	auto only0Min = new long[](n+1); only0Min[] = long.max;
	foreach(i; 0 .. n+1)
	{
		if (i&1)
		{
			only1Max[i] = cSum[i];
			only1Min[i] = cSum[i];
		}
		else
		{
			only0Max[i] = cSum[i];
			only0Min[i] = cSum[i];
		}
	}
	auto queryOnly1Max = Sparse!(long, max, "max")(only1Max);
	auto queryOnly0Max = Sparse!(long, max, "max")(only0Max);
	auto queryOnly1Min = Sparse!(long, min, "min")(only1Min);
	auto queryOnly0Min = Sparse!(long, min, "min")(only0Min);
	debug writeln(cSum);
	debug writeln(only1Max);
	debug writeln(only0Min);
	int getLeft(int r)
	{
		int left = -1;
		int hi = r;
		int lo = 0;
		while (lo <= hi)
		{
			int mi = (hi + lo) / 2;
			// this - same >= 0 this >= max(same)
			// this - other <= 0 this <= min(other)
			if (cSum[r] >= queryOnly1Max[mi .. r+1].max &&
			    cSum[r] <= queryOnly0Min[mi .. r+1].min)
			{
				left = mi;
				hi = mi - 1;
			}
			else
			{
				lo = mi + 1;
			}
		}
		return left;
	}
	debug foreach(i; 1 .. n + 1)
	{
		writeln("left of ", i, " ", getLeft(i));
	}
	int[long] lastWithValue;
	lastWithValue[0] = 0;
	long[] ways = new long[](n+1);
	foreach(i; 1 .. n+1)
	{
		if (auto last = cSum[i] in lastWithValue)
		{
			int left = getLeft(i);
			if (*last >= left)
			{
				ways[i] = 1 + ways[*last];
			}
		}
		lastWithValue[cSum[i]] = i;
	}
	ways.sum.writeln;
}
// sparse table V, f, fName {{{
struct Sparse(V, alias f, string fName = "value")
{
	import std.math : log2;
	V[][] _table;
	int[] maxPow;
	this(V[] values)
	{
		auto n = values.length;
		maxPow = new int[](n + 1);
		maxPow[0] = int.min;
		maxPow[1] = 0;
		foreach(i; 2 .. n + 1)
		{
			int prev = maxPow[i - 1];
			maxPow[i] = prev;
			prev = (1 << prev);
			if (prev * 2 <= i) maxPow[i]++;
		}
		_table = new V[][](maxPow[n] + 1, n);
		_table[0][] = values[];

		foreach(p; 1 .. maxPow[n] + 1)
		foreach(i; 0 .. n - (1<<p) + 1)
			_table[p][i] = f(_table[p-1][i], _table[p-1][i+(1<<(p-1))]);
	}
	int[2] opSlice(size_t i)(size_t start, size_t end) if (i == 0)
	{
		return [cast(int)start, cast(int)end];
	}
	auto opIndex(int[2] slice)
	{
		int sliceLen = slice[1] - slice[0];
		auto x = maxPow[sliceLen];
		auto twoX = (1 << x);
		auto p1 = _table[x][slice[0]];
		auto p2 = _table[x][slice[1] - twoX];
		struct Ans
		{
			mixin(q{V }, fName, q{;});
		}
		return Ans(f(p1, p2));
	}
}

unittest
{
	import std.algorithm;
	import std.stdio;
	alias MinQ = Sparse!(int, min, "min");
	writeln("testing");
	int[] array = [1, 2, 3, 4, -2, -2, -3, 0, 10];
	auto minQ = MinQ(array);
	foreach(i; 0 .. array.length)
	{
		foreach(j; i + 1 .. array.length + 1)
		{
			assert(minQ[i .. j].min == array[i .. j].fold!min);
		}
	}
}
// }}}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.

The first line contains two integers n and k (1 ≤ n ≤ 35000, 1 ≤ k ≤ min(n, 50)) – the number of cakes and the number of boxes, respectively. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) – the types of cakes in the order the oven bakes them.

Print the only integer – the maximum total value of all boxes with cakes.

NoteIn the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.

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

enum INF = 10^^9;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt() - 1;
      }

      auto cnt = new int[N];
      int now;
      void add(int i) {
        if (cnt[A[i]]++ == 0) {
          ++now;
        }
      }
      void rem(int i) {
        if (--cnt[A[i]] == 0) {
          --now;
        }
      }

      auto dp = new int[][](K + 1, N + 1);
      foreach (k; 0 .. K + 1) {
        dp[k][] = -INF;
      }
      dp[0][0] = 0;

      foreach (k; 0 .. K) {
        cnt[] = 0;
        now = 0;
        int l, r;
        void doIt(int iL, int iR, int jL, int jR) {
          if (iR - iL >= 1) {
            debug {
              writeln("doIt ", iL, " ", iR, " ", jL, " ", jR);
            }
            const i = (iL + iR) / 2;
            for (; r < i; ) add(r++);
            for (; r > i; ) rem(--r);
            int jm = -1;
            foreach (j; jL .. min(jR, i)) {
              for (; l < j; ) rem(l++);
              for (; l > j; ) add(--l);
              debug {
                writefln("[%s, %s): %s", l, r, now);
              }
              if (chmax(dp[k + 1][i], dp[k][j] + now)) {
                jm = j;
              }
            }
            doIt(iL, i, jL, jm + 1);
            doIt(i + 1, iR, jm, jR);
          }
        }
        doIt(k + 1, N + 1, 0, N + 1);
        debug {
          writeln(k + 1, ": ", dp[k + 1]);
        }
      }
      writeln(dp[K][N]);
    }
  } catch (EOFException e) {
  }
}


You are given an integer $$$n$$$ ($$$n > 1$$$).Your task is to find a sequence of integers $$$a_1, a_2, \ldots, a_k$$$ such that:  each $$$a_i$$$ is strictly greater than $$$1$$$;  $$$a_1 \cdot a_2 \cdot \ldots \cdot a_k = n$$$ (i. e. the product of this sequence is $$$n$$$);  $$$a_{i + 1}$$$ is divisible by $$$a_i$$$ for each $$$i$$$ from $$$1$$$ to $$$k-1$$$;  $$$k$$$ is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer $$$n > 1$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{10}$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^{10}$$$ ($$$\sum n \le 10^{10}$$$).

For each test case, print the answer: in the first line, print one positive integer $$$k$$$ — the maximum possible length of $$$a$$$. In the second line, print $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ — the sequence of length $$$k$$$ satisfying the conditions from the problem statement. If there are several answers, you can print any. It can be proven that at least one valid sequence always exists for any integer $$$n > 1$$$.

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;

int [2] solve (long n)
{
	int [2] res = [1, 1];
	for (int d = 2; d * 1L * d * d <= n; d++)
	{
		if (n % d == 0)
		{
			int [2] cur = [0, d];
			while (n % d == 0)
			{
				n /= d;
				cur[0] += 1;
			}
			res = max (res, cur);
		}
	}
	auto v = cast (int) (sqrt (n * 1.0));
	if (v * 1L * v == n && res[0] < 2)
	{
		res = [2, v];
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(long);
		auto res = solve (n);
		long [] answer;
		foreach (i; 0..res[0] - 1)
		{
			answer ~= res[1];
			n /= res[1];
		}
		answer ~= n;
		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;

int [2] solve (long n)
{
	int [2] res = [1, 1];
	for (int d = 2; d * 1L * d <= n && d <= 90000; d++)
	{
		if (n % d == 0)
		{
			int [2] cur = [0, d];
			while (n % d == 0)
			{
				n /= d;
				cur[0] += 1;
			}
			res = max (res, cur);
		}
	}
	auto v = cast (int) (sqrt (n * 1.0));
	if (v * 1L * v == n && res[0] < 2)
	{
		res = [2, v];
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(long);
		auto res = solve (n);
		long [] answer;
		foreach (i; 0..res[0] - 1)
		{
			answer ~= res[1];
			n /= res[1];
		}
		answer ~= n;
		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}

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; }
T lcm(T)(T x, T 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 modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

long[2][] primeFact(long x)
{
	long[2][] ans;
	for (long i = 2; i*i <= x; ++i)
	{
		if (x % i != 0) continue;

		long r;
		while (x % i == 0)
		{
			++r;
			x /= i;
		}
		ans ~= [i, r];
	}
	if (x != 1)
		ans ~= [x, 1];
	return ans;
}

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD;

		auto r = primeFact(n);
		while (true)
		{
			long x = 1;
			foreach (ref e; r)
			{
				if (e[1] == 0) continue;
				x *= e[0];
				--e[1];
			}
			if (x == 1) break;
			ans[ti] = x ~ ans[ti];
		}
	}

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


You are given an array $$$a$$$ of $$$n$$$ integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_j - a_i = j - i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_j - a_i = j - i$$$.

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; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad) * vec[0] - sin(rad) * vec[1], sin(rad) * vec[0] + cos(rad) * vec[1]]; }

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 modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA(n);

		foreach (i; 0..n)
			a[i] -= i;

		auto cnt = new long[](2*n);
		foreach (i; 0..n)
			++cnt[a[i]];

		debug writeln(cnt);
		foreach (e; cnt)
			ans[ti] += e * (e-1) / 2;
	}

	foreach (e; ans)
	{
		writeln(e);
	}
	stdout.flush;
	debug readln;
}


You are given a string $$$s$$$ consisting of lowercase letters of the English alphabet. You must perform the following algorithm on $$$s$$$:  Let $$$x$$$ be the length of the longest prefix of $$$s$$$ which occurs somewhere else in $$$s$$$ as a contiguous substring (the other occurrence may also intersect the prefix). If $$$x = 0$$$, break. Otherwise, remove the first $$$x$$$ characters of $$$s$$$, and repeat. A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".For instance, if we perform the algorithm on $$$s =$$$ "abcabdc",   Initially, "ab" is the longest prefix that also appears somewhere else as a substring in $$$s$$$, so $$$s =$$$ "cabdc" after $$$1$$$ operation.  Then, "c" is the longest prefix that also appears somewhere else as a substring in $$$s$$$, so $$$s =$$$ "abdc" after $$$2$$$ operations.  Now $$$x=0$$$ (because there are no non-empty prefixes of "abdc" that also appear somewhere else as a substring in $$$s$$$), so the algorithm terminates. Find the final state of the string after performing the algorithm.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. Each line contains a string $$$s$$$. The given strings consist only of lowercase letters of the English alphabet and have lengths between $$$1$$$ and $$$2 \cdot 10^5$$$ inclusive. It is guaranteed that the sum of the lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single line containing the string $$$s$$$ after executing the algorithm. It can be shown that such string is non-empty.

6
abcabdc
a
bbbbbbbbbb
codeforces
cffcfccffccfcffcfccfcffccffcfccf
zyzyzwxxyyxxyyzzyzzxxwzxwywxwzxxyzzw

NoteThe first test case is explained in the statement.In the second test case, no operations can be performed on $$$s$$$.In the third test case,   Initially, $$$s =$$$ "bbbbbbbbbb".  After $$$1$$$ operation, $$$s =$$$ "b". In the fourth test case,   Initially, $$$s =$$$ "codeforces".  After $$$1$$$ operation, $$$s =$$$ "odeforces".  After $$$2$$$ operations, $$$s =$$$ "deforces".

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto pos = new int [26];
		pos[] = int.max;
		foreach (i, ref c; s)
		{
			pos[c - 'a'] = i;
		}
		writeln (s[pos.minElement..$]);
	}
}


Omkar has a pie tray with $$$k$$$ ($$$2 \leq k \leq 20$$$) spots. Each spot in the tray contains either a chocolate pie or a pumpkin pie. However, Omkar does not like the way that the pies are currently arranged, and has another ideal arrangement that he would prefer instead.To assist Omkar, $$$n$$$ elves have gathered in a line to swap the pies in Omkar's tray. The $$$j$$$-th elf from the left is able to swap the pies at positions $$$a_j$$$ and $$$b_j$$$ in the tray.In order to get as close to his ideal arrangement as possible, Omkar may choose a contiguous subsegment of the elves and then pass his pie tray through the subsegment starting from the left. However, since the elves have gone to so much effort to gather in a line, they request that Omkar's chosen segment contain at least $$$m$$$ ($$$1 \leq m \leq n$$$) elves.Formally, Omkar may choose two integers $$$l$$$ and $$$r$$$ satisfying $$$1 \leq l \leq r \leq n$$$ and $$$r - l + 1 \geq m$$$ so that first the pies in positions $$$a_l$$$ and $$$b_l$$$ will be swapped, then the pies in positions $$$a_{l + 1}$$$ and $$$b_{l + 1}$$$ will be swapped, etc. until finally the pies in positions $$$a_r$$$ and $$$b_r$$$ are swapped.Help Omkar choose a segment of elves such that the amount of positions in Omkar's final arrangement that contain the same type of pie as in his ideal arrangement is the maximum possible. Note that since Omkar has a big imagination, it might be that the amounts of each type of pie in his original arrangement and in his ideal arrangement do not match.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \leq m \leq n \leq 10^6$$$ and $$$2 \leq k \leq 20$$$)  — the number of elves, the minimum subsegment length, and the number of spots in Omkar's tray respectively.  The second and third lines each contain a string of length $$$k$$$ consisting of $$$0$$$s and $$$1$$$s that represent initial arrangement of pies and ideal arrangement of pies; the $$$j$$$-th character in each string is equal to $$$0$$$ if the $$$j$$$-th spot in the arrangement contains a chocolate pie and is equal to $$$1$$$ if the $$$j$$$-th spot in the arrangement contains a pumpkin pie. It is not guaranteed that the two strings have the same amount of $$$0$$$s or the same amount of $$$1$$$s. $$$n$$$ lines follow. The $$$j$$$-th of these lines contains two integers $$$a_j$$$ and $$$b_j$$$ ($$$1 \leq a_j, b_j \leq k$$$, $$$a_j \neq b_j$$$) which indicate that the $$$j$$$-th elf from the left can swap the pies at positions $$$a_j$$$ and $$$b_j$$$ in the tray.

Output two lines.  The first line should contain a single integer $$$s$$$ ($$$0 \leq s \leq k$$$) equal to the amount of positions that contain the same type of pie in Omkar's final arrangement and in Omkar's ideal arrangement; $$$s$$$ should be the maximum possible.  The second line should contain two integers $$$l$$$ and $$$r$$$ satisfying $$$1 \leq l \leq r \leq n$$$ and $$$r - l + 1 \geq m$$$, indicating that Omkar should pass his tray through the subsegment $$$l, l + 1, \dots, r$$$ to achieve a final arrangement with $$$s$$$ positions having the same type of pie as his ideal arrangement. If there are multiple answers you may output any of them.

NoteIn the first test case, the swaps will go like this:   Swap $$$1$$$ and $$$3$$$: 11000 becomes 01100  Swap $$$3$$$ and $$$5$$$: 01100 becomes 01001  Swap $$$4$$$ and $$$2$$$: 01001 becomes 00011  The final arrangement is the same as the ideal arrangement 00011, so there are $$$5$$$ positions with the same type of pie, which is optimal.In the second test case, the swaps will go like this:   Swap $$$1$$$ and $$$3$$$: 11000 becomes 01100  Swap $$$1$$$ and $$$5$$$: 01100 becomes 01100  Swap $$$4$$$ and $$$2$$$: 01100 becomes 00110  Swap $$$1$$$ and $$$5$$$: 00110 becomes 00110  The final arrangement has $$$3$$$ positions with the same type of pie as the ideal arrangement 00011, those being positions $$$1$$$, $$$2$$$, and $$$4$$$. In this case the subsegment of elves $$$(l, r) = (2, 3)$$$ is more optimal, but that subsegment is only length $$$2$$$ and therefore does not satisfy the constraint that the subsegment be of length at least $$$m = 3$$$.

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

enum INF = 10^^9;

/*
  s[r-1] ... s[l] S = T
  S = s[l]^-1 ... s[r-1]^-1 T
  s[0]^-1 ... s[l-1]^-1 S = s[0]^-1 ... s[r-1]^-1 T
*/
void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const K = readInt();
      const S = readToken();
      const T = readToken();
      auto A = new int[N];
      auto B = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      auto dpS = new int[1 << K];
      auto dpT = new int[1 << K];
      dpS[] = +INF;
      dpT[] = -INF;
      auto perm = iota(K).array;
      foreach (i; 0 .. N + 1) {
        debug {
          writeln("perm = ", perm);
        }
        int s, t;
        foreach (k; 0 .. K) {
          s |= (S[k] - '0') << perm[k];
          t |= (T[k] - '0') << perm[k];
        }
        chmin(dpS[s], i);
        chmax(dpT[t], i);
        if (i == N) {
          break;
        }
        swap(perm[A[i]], perm[B[i]]);
      }

      foreach_reverse (p; 0 .. 1 << K) {
        foreach (k; 0 .. K) {
          if (!(p & 1 << k)) {
            chmin(dpS[p], dpS[p | 1 << k]);
            chmax(dpT[p], dpT[p | 1 << k]);
          }
        }
      }

      int mx = -1, lm, rm;
      foreach (p; 0 .. 1 << K) {
        if (dpT[p] - dpS[p] >= M) {
          debug {
            writeln(p, " ", dpS[p], " ", dpT[p]);
          }
          if (chmax(mx, popcnt(p))) {
            lm = dpS[p];
            rm = dpT[p];
          }
        }
      }
      int ans;
      ans += mx;
      ans += K - (S.count('1') + T.count('1') - mx);
      writeln(ans);
      writeln(lm + 1, " ", rm);
    }
  } catch (EOFException e) {
  }
}


Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased:  Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.

The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree.

If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path.

NoteIn the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5.It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.

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

enum INF = 10^^9;

int N;
int[] A, B;

int[][] G;
int[] par;

alias Result = Tuple!(int, "min", int, "max");
enum IDENTITY = Result(INF, -INF);
Result mul(const(Result) a, const(Result) b) {
  return Result(min(a.min, b.min), max(a.max, b.max));
}
Result up(const(Result) a) {
  return (a.min >= INF) ? Result(0, 0) : Result(1 + a.min, 1 + a.max);
}

Result[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  Result prod = IDENTITY;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      prod = mul(prod, dp[v]);
    }
  }
  dp[u] = up(prod);
}

void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  auto ls = new Result[len + 1];
  auto rs = new Result[len + 1];
  ls[0] = (p == -1) ? IDENTITY : DP[u];
  foreach (j; 0 .. len) {
    ls[j + 1] = mul(ls[j], dp[vs[j]]);
  }
  rs[len] = IDENTITY;
  foreach_reverse (j; 0 .. len) {
    rs[j] = mul(dp[vs[j]], rs[j + 1]);
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = up(mul(ls[j], rs[j + 1]));
  }
  foreach (v; vs) {
    DFS(v, u);
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      A = new int[N - 1];
      B = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      dp = new Result[N];
      DP = new Result[N];
      dfs(0, -1);
      DFS(0, -1);
      debug {
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }

      int ans = INF;
      foreach (u; 0 .. N) {
        bool ok = true;
        int[] ms;
        if (par[u] != -1) {
          ok = ok && (DP[u].min == DP[u].max);
          ms ~= DP[u].min;
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (v != par[u]) {
            ok = ok && (dp[v].min == dp[v].max);
            ms ~= dp[v].min;
          }
        }
        ms = ms.sort.uniq.array;
        debug {
          writeln(u, ": ", ok, " ", ms);
        }
        if (ok && ms.length <= 2) {
          const cost = (G[u].length == 1) ? (ms[0] + 1) : (ms[0] + 1 + 1 + ms[$ - 1]);
          chmin(ans, cost >> bsf(cost));
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10^^9;

int N;
int[] A, B;

int[][] G;
int[] par;

alias Result = Tuple!(int, "min", int, "max");
enum IDENTITY = Result(INF, -INF);
Result mul(const(Result) a, const(Result) b) {
  return Result(min(a.min, b.min), max(a.max, b.max));
}
Result up(const(Result) a) {
  return (a.min >= INF) ? Result(0, 0) : Result(1 + a.min, 1 + a.max);
}

Result[] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  Result prod = IDENTITY;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      prod = mul(prod, dp[v]);
    }
  }
  dp[u] = up(prod);
}

void DFS(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  auto ls = new Result[len + 1];
  auto rs = new Result[len + 1];
  ls[0] = (p == -1) ? IDENTITY : DP[u];
  foreach (j; 0 .. len) {
    ls[j + 1] = mul(ls[j], dp[vs[j]]);
  }
  rs[len] = IDENTITY;
  foreach_reverse (j; 0 .. len) {
    rs[j] = mul(dp[vs[j]], rs[j + 1]);
  }
  foreach (j; 0 .. len) {
    DP[vs[j]] = up(mul(ls[j], rs[j + 1]));
  }
  foreach (v; vs) {
    DFS(v, u);
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      A = new int[N - 1];
      B = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      dp = new Result[N];
      DP = new Result[N];
      dfs(0, -1);
      DFS(0, -1);
      debug {
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }

      int ans = INF;
      foreach (u; 0 .. N) {
        bool ok = true;
        int[] ms;
        if (par[u] != -1) {
          ok = ok && (DP[u].min == DP[u].max);
          ms ~= DP[u].min;
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (v != par[u]) {
            ok = ok && (dp[v].min == dp[v].max);
            ms ~= dp[v].min;
          }
        }
        ms = ms.sort.uniq.array;
        debug {
          writeln(u, ": ", ok, " ", ms);
        }
        if (ok && ms.length <= 2) {
          const cost = (G[u].length == 1) ? (ms[0] + 1) : (ms[0] + 1 + 1 + ms[$ - 1]);
          chmin(ans, (cost % 2 == 0) ? 0 : cost);
        }
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}