Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0.

For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order.

NoteThis image illustrates the second sample case.

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

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

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

immutable class SegTree {
    SegTree left, right;
    bool inv;
    int size, count;

    this(bool value) {
        left = right = null;
        inv = false;
        size = 1;
        count = value;
    }

    this(immutable SegTree left, immutable SegTree right, bool inv) {
        this.left = left;
        this.right = right;
        this.inv = inv;
        size = getSize(left) + getSize(right);
        count = getCount(left) + getCount(right);
    }

    static int getSize(immutable SegTree t) {
        return t is null? 0 : t.size;
    }

    static int getCount(immutable SegTree t) {
        return t is null? 0 : t.inv? t.size - t.count : t.count;
    }

    static auto invertOne(immutable SegTree t) {
        if (t is null)
            return null;
        if (t.left is null && t.right is null)
            return new immutable SegTree(!t.count);
        return new immutable SegTree(t.left, t.right, !t.inv);
    }

    auto push() {
        return inv? new immutable SegTree(invertOne(left), invertOne(right), false) : this;
    }

    auto update(int i, bool value) {
        assert(size >= 1, "Size is %s".format(size));
        if (size == 1) {
            assert(!i);
            return new immutable SegTree(value);
        }
        auto t = push();
        if (i < getSize(left))
            return new immutable SegTree(t.left.update(i, value), t.right, false);
        return new immutable SegTree(t.left, t.right.update(i - getSize(left), value), false);
    }

    auto invert(int lb, int rb) {
        if (!lb && rb == size)
            return invertOne(this);
        int mid = getSize(left);
        auto t = push();
        auto newLeft = lb >= mid? t.left : t.left.invert(lb, min(mid, rb));
        auto newRight = rb <= mid? t.right : t.right.invert(max(lb - mid, 0), rb - mid);
        return new immutable SegTree(newLeft, newRight, false);
    }
}

auto construct(int n) {
    assert(n >= 1);
    if (n == 1)
        return new immutable SegTree(false);
    return new immutable SegTree(construct(n >> 1), construct(n - (n >> 1)), false);
}

void main() {
    int n, m, q;
    while (scanf("%d%d%d", &n, &m, &q) == 3) {
        auto roots = [construct(n * m)];
        roots.reserve(q + 1);
        while (q--) {
            char c;
            int a, b;
            scanf(" %c%d", &c, &a);
            final switch (c) {
                case '1': case '2': {
                    scanf("%d", &b);
                    roots ~= roots.back.update((a - 1) * m + b - 1, c == '1');
                    break;
                }
                case '3': {
                    roots ~= roots.back.invert((a - 1) * m, a * m);
                    break;
                }
                case '4': {
                    roots ~= roots[a];
                    break;
                }
            }
            printf("%d\n", SegTree.getCount(roots.back));
        }
        debug putchar('\n');
    }
}

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

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

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

immutable class SegTree {
    SegTree left, right;
    bool inv;
    int size, count;

    this(bool value) {
        left = right = null;
        inv = false;
        size = 1;
        count = value;
    }

    this(immutable SegTree left, immutable SegTree right, bool inv) {
        this.left = left;
        this.right = right;
        this.inv = inv;
        size = getSize(left) + getSize(right);
        count = getCount(left) + getCount(right);
    }

    static int getSize(immutable SegTree t) {
        return t is null? 0 : t.size;
    }

    static int getCount(immutable SegTree t) {
        return t is null? 0 : t.inv? t.size - t.count : t.count;
    }

    static auto invertOne(immutable SegTree t) {
        if (t is null)
            return null;
        if (t.left is null && t.right is null)
            return new immutable SegTree(!t.count);
        return new immutable SegTree(t.left, t.right, !t.inv);
    }

    auto push() {
        return inv? new immutable SegTree(invertOne(left), invertOne(right), false) : this;
    }

    auto update(int i, bool value) {
        assert(size >= 1, "Size is %s".format(size));
        if (size == 1) {
            assert(!i);
            return new immutable SegTree(value);
        }
        auto t = push();
        if (i < getSize(left))
            return new immutable SegTree(t.left.update(i, value), t.right, false);
        return new immutable SegTree(t.left, t.right.update(i - getSize(left), value), false);
    }

    auto invert(int lb, int rb) {
        if (!lb && rb == size)
            return invertOne(this);
        int mid = getSize(left);
        auto t = push();
        auto newLeft = lb >= mid? t.left : t.left.invert(lb, min(mid, rb));
        auto newRight = rb <= mid? t.right : t.right.invert(max(lb - mid, 0), rb - mid);
        return new immutable SegTree(newLeft, newRight, false);
    }
}

auto construct(int n) {
    assert(n >= 1);
    if (n == 1)
        return new immutable SegTree(false);
    return new immutable SegTree(construct(n >> 1), construct(n - (n >> 1)), false);
}

void main() {
    int n, m, q;
    while (read(&n, &m, &q)) {
        auto roots = [construct(n * m)];
        roots.reserve(q + 1);
        while (q--) {
            char c;
            int a, b;
            read(&c, &a);
            final switch (c) {
                case '1': case '2': {
                    read(&b);
                    roots ~= roots.back.update((a - 1) * m + b - 1, c == '1');
                    break;
                }
                case '3': {
                    roots ~= roots.back.invert((a - 1) * m, a * m);
                    break;
                }
                case '4': {
                    roots ~= roots[a];
                    break;
                }
            }
            writeln(SegTree.getCount(roots.back));
        }
        debug writeln();
    }
}

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.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
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;
}

final class SegTree {
    int size;
    int sum;
    bool inv;
    SegTree left, right;

    invariant {
        assert(size > 0);
        assert(sum >= 0);
        assert(sum <= size);
        assert((left is null) == (right is null));
    }

    this(int size, int sum, bool inv) {
        this(size, sum, inv, null, null);
    }

    this(int size, int sum, bool inv, SegTree left, SegTree right) {
        this.size = size;
        this.sum = sum;
        this.inv = inv;
        this.left = left;
        this.right = right;
    }

    static SegTree build(int n) {
        assert(n > 0);
        if (n == 1)
            return new SegTree(1, 0, false);
        return new SegTree(n, 0, false, build(n >>> 1), build(n - (n >>> 1)));
    }

    static int getSum(const SegTree sgt) {
        return sgt is null ? 0 : sgt.inv ? sgt.size - sgt.sum : sgt.sum;
    }

    private void _push() {
        if (inv) {
            if (left !is null) {
                left.inv ^= true;
                right.inv ^= true;
            }
            sum = size - sum;
            inv = false;
        }
    }

    SegTree set(int i, bool value) {
        if (left is null)
            return new SegTree(1, value, false);
        _push();
        if (i < left.size) {
            auto newLeft = left.set(i, value);
            return new SegTree(size, getSum(newLeft) + getSum(right), false, newLeft, right);
        } else {
            auto newRight = right.set(i - left.size, value);
            return new SegTree(size, getSum(left) + getSum(newRight), false, left, newRight);
        }
    }

    SegTree invert(int lb, int rb) {
        if (lb >= rb)
            return this;
        _push();
        if (!lb && rb == size)
            return new SegTree(size, sum, !inv, left, right);
        assert(left !is null);
        auto newLeft = left.invert(lb, min(left.size, rb));
        auto newRight = right.invert(max(lb - left.size, 0), rb - left.size);
        return new SegTree(size, getSum(newLeft) + getSum(newRight), false, newLeft, newRight);
    }
}

void main() {
    int n, m, q;
    while (read(&n, &m, &q)) {
        Array!SegTree roots;
        roots.length = q + 1;
        roots[0] = SegTree.build(n * m);
        foreach (cur; 0 .. q) {
            char cmd;
            int i, j;
            read(&cmd);
            switch (cmd) {
                case '1': {
                    read(&i, &j);
                    i--;
                    j--;
                    roots[cur + 1] = roots[cur].set(i * m + j, true);
                    break;
                }
                case '2': {
                    read(&i, &j);
                    i--;
                    j--;
                    roots[cur + 1] = roots[cur].set(i * m + j, false);
                    break;
                }
                case '3': {
                    read(&i);
                    roots[cur + 1] = roots[cur].invert((i - 1) * m, i * m);
                    break;
                }
                case '4': {
                    read(&i);
                    roots[cur + 1] = roots[i];
                    break;
                }
                default: assert(false);
            }
            writeln(SegTree.getSum(roots[cur + 1]));
        }
        debug writeln();
    }
}

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.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
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;
}

final class SegTree {
    SegTree left, right;
    int size;
    int sum;
    bool inv;

    this(int size, int sum, bool inv) {
        this(size, sum, inv, null, null);
    }

    this(int size, int sum, bool inv, SegTree left, SegTree right) {
        this.size = size;
        this.sum = sum;
        this.inv = inv;
        this.left = left;
        this.right = right;
    }

    static SegTree build(int n) {
        assert(n > 0);
        if (n == 1)
            return new SegTree(1, 0, false);
        return new SegTree(n, 0, false, build(n >>> 1), build(n - (n >>> 1)));
    }

    static int getSum(const SegTree sgt) {
        return sgt is null ? 0 : sgt.sum;
    }

    private void _push() {
        if (inv) {
            if (left) {
                left.sum = left.size - left.sum;
                left.inv ^= true;
            }
            if (right) {
                right.sum = right.size - right.sum;
                right.inv ^= true;
            }
            inv = false;
        }
    }

    SegTree add(int i) {
        if (left is null)
            return new SegTree(1, 1, false);
        _push();
        if (i < left.size) {
            auto newLeft = left.add(i);
            return new SegTree(size, newLeft.sum + right.sum, false, newLeft, right);
        } else {
            auto newRight = right.add(i - left.size);
            return new SegTree(size, left.sum + newRight.sum, false, left, newRight);
        }
    }

    SegTree remove(int i) {
        if (left is null) {
            assert(right is null);
            return new SegTree(1, 0, false);
        }
        _push();
        if (i < left.size) {
            auto newLeft = left.remove(i);
            return new SegTree(size, newLeft.sum + right.sum, false, newLeft, right);
        } else {
            auto newRight = right.remove(i - left.size);
            return new SegTree(size, left.sum + newRight.sum, false, left, newRight);
        }
    }

    SegTree invert(int lb, int rb) {
        if (lb >= rb)
            return this;
        _push();
        if (!lb && rb == size)
            return new SegTree(size, size - sum, !inv, left, right);
        if (left is null)
            writeln(lb, ' ', rb);
        assert(left !is null);
        assert(right !is null);
        auto newLeft = left.invert(lb, min(left.size, rb));
        auto newRight = right.invert(max(lb - left.size, 0), rb - left.size);
        return new SegTree(size, newLeft.sum + newRight.sum, false, newLeft, newRight);
    }
}

void main() {
    int n, m, q;
    while (read(&n, &m, &q)) {
        Array!SegTree roots;
        roots.length = q + 1;
        roots[0] = SegTree.build(n * m);
        foreach (cur; 0 .. q) {
            char cmd;
            int i, j;
            read(&cmd);
            switch (cmd) {
                case '1': {
                    read(&i, &j);
                    i--;
                    j--;
                    roots[cur + 1] = roots[cur].add(i * m + j);
                    break;
                }
                case '2': {
                    read(&i, &j);
                    i--;
                    j--;
                    roots[cur + 1] = roots[cur].remove(i * m + j);
                    break;
                }
                case '3': {
                    read(&i);
                    roots[cur + 1] = roots[cur].invert((i - 1) * m, i * m);
                    break;
                }
                case '4': {
                    read(&i);
                    roots[cur + 1] = roots[i];
                    break;
                }
                default: assert(false);
            }
            writeln(roots[cur + 1].sum);
        }
        debug writeln();
    }
}


You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled:   All pixels in each column are of the same color.  The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.

The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".

In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.

NoteIn the first test sample the picture after changing some colors can looks as follows:  .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows:  .#.#..#.#.

import std.stdio;
import std.array;
import std.algorithm;

const int max_n = 1024;
const int inf = cast(int)(1e9);

int[max_n][max_n][2] dp;

void main() {
    int n, m, x, y;
    readf("%d %d %d %d", &n, &m, &x, &y);
    int[] black = new int[m];
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            char c;
            readf(" %c", &c);
            black[j] += (c == '#');
        }
    }

    foreach (ref a; dp) {
        foreach (ref b; a) {
            b[] = inf;
        }
    }

    int get(int i, int c) {
        return (c == 0) ? black[i] : n - black[i];
    }

    for (int c = 0; c <= 1; ++c) {
        dp[c][0][1] = get(0, c);
    }

    for (int i = 1; i < m; ++i) {
        for (int c = 0; c <= 1; ++c) {
            dp[c][i][1] = get(i, c) + minPos(dp[c ^ 1][i - 1][x .. min($, y + 1)])[0];
            for (int j = 2; j <= i + 1; ++j) {
                dp[c][i][j] = get(i, c) + dp[c][i - 1][j - 1];
            }
        }
    }

    int res = inf;
    for (int c = 0; c <= 1; ++c) {
        res = min(res, minPos(dp[c][m - 1][x .. min($, y + 1)])[0]);
    }

    writeln(res);
}

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

int main() {

    auto tmp = split(strip(readln()), " ");
    auto n = to!int(tmp[0]);
    auto m = to!int(tmp[1]);
    auto x = to!int(tmp[2]);
    auto y = to!int(tmp[3]);
    auto table = new string[n];
    for (int i = 0; i < n; ++i)
        table[i] = strip(readln());

    int cntImpl(int color, int j) {
        int ans = 0;
        for (int i = 0; i < n; ++i)
            ans += table[i][j] == '.' ? color : 1 - color;
        return ans;
    }

    alias memoize!cntImpl cnt;

    int sum(int color, int end) {
        alias memoize!sum msum;
        if (end == 0)
            return cnt(color, end);
        else
            return cnt(color, end) + msum(color, end - 1);
    }

    int sum_of_color(int color, int start, int end) {
        if (start < 0) return 1000000000;
        return sum(color, end) - sum(color, start) + cnt(color, start);
    }

    int dp(int color, int num) {
        alias memoize!dp dpImpl;
        int ans = 1000000000;
        if (num < 0)
            return 0;
        for (int i = x; i <= y; ++i)
            ans = min(ans, dpImpl(1 - color, num - i) + sum_of_color(color, num - i + 1, num));
        return ans;
    }
    writeln(min(dp(0, m - 1), dp(1, m - 1)));
    return 0;
}

import std.stdio;
import std.array;
import std.algorithm;

const int max_n = 10;
const int inf = cast(int)(1e9);

int[max_n][max_n][2] dp;

void main() {
    int n, m, x, y;
    readf("%d %d %d %d", &n, &m, &x, &y);
    int[] black = new int[m];
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            char c;
            readf(" %c", &c);
            black[j] += (c == '#');
        }
    }

    foreach (ref a; dp) {
        foreach (ref b; a) {
            b[] = inf;
        }
    }

    int get(int c) {
        return (c == 0) ? black[c] : n - black[c];
    }

    for (int c = 0; c <= 1; ++c) {
        dp[c][0][1] = get(c);
    }

    for (int i = 1; i < m; ++i) {
        for (int c = 0; c <= 1; ++c) {
            dp[c][i][1] = get(c) + minPos(dp[c ^ 1][i - 1][x .. y + 1])[0];
            for (int j = 2; j <= i + 1; ++j) {
                dp[c][i][j] = get(c) + dp[c][i - 1][j - 1];
            }
        }
    }

    int res = inf;
    for (int c = 0; c <= 1; ++c) {
        for (int j = x; j <= y; ++j) {
            res = min(res, dp[c][m - 1][j]);
        }
    }

    writeln(res);
}

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

int main() {

    auto tmp = split(strip(readln()), " ");
    auto n = to!int(tmp[0]);
    auto m = to!int(tmp[1]);
    auto x = to!int(tmp[2]);
    auto y = to!int(tmp[3]);
    string[] table = [];
    for (int i = 0; i < n; ++i)
        table ~= strip(readln());

    int cntImpl(int color, int j) {
        int ans = 0;
        for (int i = 0; i < n; ++i)
            ans += table[i][j] == '.' ? color : 1 - color;
        return ans;
    }

    alias memoize!cntImpl cnt;

    int sum(int color, int end) {
        alias memoize!sum msum;
        if (end < 0)
            return 1000000000;
        else if (end == 0)
            return cnt(color, end);
        else
            return cnt(color, end) + msum(color, end - 1);
    }

    int sum_of_color(int color, int start, int end) {
        return sum(color, end) - sum(color, start) + cnt(color, start);
    }

    int dp(int color, int num) {
        alias memoize!dp dpImpl;
        int ans = 1000000000;
        if (num == 0)
            return sum_of_color(color, 0, 0);
        for (int i = x; i <= y; ++i)
            if (num - i >= 0)
            	ans = min(ans, dpImpl(1 - color, num - i) + sum_of_color(color, num - i + 1, num));
        return ans;
    }
    writeln(min(dp(0, m - 1), dp(1, m - 1)));
    return 0;
}


Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.A permutation $$$a_1, a_2, \dots, a_n$$$ of $$$1, 2, \dots, n$$$ is said to be almost sorted if the condition $$$a_{i + 1} \ge a_i - 1$$$ holds for all $$$i$$$ between $$$1$$$ and $$$n - 1$$$ inclusive.Maki is considering the list of all almost sorted permutations of $$$1, 2, \dots, n$$$, given in lexicographical order, and he wants to find the $$$k$$$-th permutation in this list. Can you help him to find such permutation?Permutation $$$p$$$ is lexicographically smaller than a permutation $$$q$$$ if and only if the following holds: in the first position where $$$p$$$ and $$$q$$$ differ, the permutation $$$p$$$ has a smaller element than the corresponding element in $$$q$$$.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Each test case consists of a single line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le k \le 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single line containing the $$$k$$$-th almost sorted permutation of length $$$n$$$ in lexicographical order, or $$$-1$$$ if it doesn't exist.

NoteFor the first and second test, the list of almost sorted permutations with $$$n = 1$$$ is $$$\{[1]\}$$$.For the third and fifth test, the list of almost sorted permutations with $$$n = 3$$$ is $$$\{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}$$$.

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)
	{
		int n;
		long k;
		readf !(" %s %s") (n, k);
		readln;
		k -= 1;
		if (n < 62 && k >= (1L << (n - 1)))
		{
			writeln (-1);
		}
		else
		{
			auto s = 0.repeat (n + 1).array;
			foreach_reverse (i; 0..n)
			{
				s[i] = (k & 1);
				k >>= 1;
			}

			auto r = iota (n + 1).filter !(i => s[i] == 0).array;
			auto z = r.length;

			auto p = n.iota.array;
			p[] += 1;
			foreach (i; 0..z - 1)
			{
				reverse (p[r[i]..r[i + 1]]);
			}
			writefln !("%(%s %)") (p);
		}
	}
}


Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to ">", in the opposite case $$$a_{ij}$$$ is equal to "<". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "<", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is ">", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "<", ">" and "=".

The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.

NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = N.iota.map!(_ => readln.chomp).array;

    auto uf = new UnionFind(N+M);
    foreach (i; 0..N) foreach (j; 0..M) if (A[i][j] == '=') uf.unite(i, j+N);

    int p = 0;
    int[int] mp;

    foreach (i; 0..N) if (uf.table[i] < 0) mp[i] = p++;
    foreach (j; 0..M) if (uf.table[j+N] < 0) mp[j+N] = p++;
    foreach (i; 0..N) if (uf.table[i] >= 0) mp[i] = mp[uf.table[i]];
    foreach (j; 0..M) if (uf.table[j+N] >= 0) mp[j+N] = mp[uf.table[j+N]];

    auto G = new int[][](p);
    auto D = new int[](p);

    foreach (i; 0..N) {
        foreach (j; 0..M) {
            if (A[i][j] == '>') {
                G[mp[j+N]] ~= mp[i];
                D[mp[i]] += 1;
            } else if (A[i][j] == '<') {
                G[mp[i]] ~= mp[j+N];
                D[mp[j+N]] += 1;
            }
        }
    }

    auto ans = new int[](p);
    ans[] = 1;

    DList!int q;
    foreach (i; 0..p) if (D[i] == 0) q.insertBack(i);

    while (!q.empty) {
        auto n = q.front;
        q.removeFront;
        foreach (m; G[n]) {
            D[m] -= 1;
            ans[m] = max(ans[m], ans[n] + 1);
            if (D[m] == 0) {
                q.insertBack(m);
            }
        }
    }

    if (p.iota.map!(i => D[i] != 0).any) {
        writeln("No");
        return;
    }

    writeln("Yes");
    N.iota.map!(i => ans[mp[i]].to!string).join(" ").writeln;
    M.iota.map!(i => ans[mp[i+N]].to!string).join(" ").writeln;
}

class UnionFind {
    int N;
    int[] table;

    this(int n) {
        N = n;
        table = new int[](N);
        fill(table, -1);
    }

    int find(int x) {
        return table[x] < 0 ? x : (table[x] = find(table[x]));
    }

    void unite(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        table[x] += table[y];
        table[y] = x;
    }
}


Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it.

The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding.

NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio:freopen;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree set;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
@property pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow @property X binpow(X,Y)(X base,Y exp)
	if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @property auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
	if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
@property void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p)
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(in pair!(X,Y) s_) const pure nothrow @safe
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;
	while(input(&n))
	{
		readln;
		auto s=readln.strip;
		string ans;
		foreach(i;0..s.length)
		{
			if(n&1)
			{
				if((i&1)==0)ans~=s[i];
				else ans=s[i]~ans;
			}
			else
			{
				if((i&1)==0)ans=s[i]~ans;
				else ans~=s[i];
			}
		}
		writeln(ans);
	}
}

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

void main(){
    int n=readln.chomp.to!int;
    auto s=readln.strip;
    char[] a;
    foreach(i;0..s.length){
        if(n&1) a~=s[i];
        else a=s[i]~a;
        n--;
    }
    writeln(a);
}

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

void main(){
    int n=readln.chomp.to!int;
    auto s=readln.strip;
    char[] a;
    foreach(ref c;s){
        if(n&1) a~=c;
        else a=c~a;
        n--;
    }
    writeln(a);
}


You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$).

For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise.

NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        long n = scan!long, k = scan!long;
        if(n % 2 != k % 2) "NO".writeln;
        else if(n < k * k) "NO".writeln;
        else "YES".writeln;
    }
}

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

string FMT_F = "%.10f";

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

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		auto k = RD;
		if (n < k^^2)
			ans[ti] = false;
		else
			ans[ti] = n % 2 == k % 2;
	}

	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.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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		if (n < k^^2)
			ans[ti] = false;
		else
			ans[ti] = n % 2 == k % 2;
	}

	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.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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		ans[ti] = n % 2 == k % 2;
	}

	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.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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		if (k > n)
			ans[ti] = false;
		else
			ans[ti] = n % 2 == k % 2;
	}

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


Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.

The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.

Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".

NoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.

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

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

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

    if (n == 1) {
        writeln("not unique");
        return;
    }

    auto longer = zip(arr, arr.dropOne).map!(t => t[1] - t[0] > arr.front).array;

    debug { longer.writeln; }

    bool isSmaller(Tuple!(int, int) t1, Tuple!(int, int) t2) {
        return t1[0] * t2[1] < t2[0] * t1[1];
    }

    Tuple!(int, int) smaller(Tuple!(int, int) t1, Tuple!(int, int) t2) {
        return isSmaller(t1, t2) ? t1 : t2;
    }

    Tuple!(int, int) bigger(Tuple!(int, int) t1, Tuple!(int, int) t2) {
        return isSmaller(t1, t2) ? t2 : t1;
    }

    bool ok(bool lst) {
        auto lo = tuple(0, 1);
        auto hi = tuple(10, 1);

        int dst = 10;
        foreach (idx, e; longer ~ lst) {
            int stopNr = idx.to!int + 2;
            auto nxt = tuple(dst, stopNr);
            if (e) {
                lo = bigger(lo, nxt);
                dst += 10;
            } else {
                hi = smaller(hi, nxt);
            }
        }

        debug { writeln(lo, ' ', hi); }

        return isSmaller(lo, hi);
    }

    bool ok1 = ok(false);
    bool ok2 = ok(true);

    debug { writeln(ok1, ' ', ok2); }

    if (ok1 && ok2) {
        writeln("not unique");
        return;
    }

    writeln("unique");
    writeln(ok1 ? arr.back + arr.front : arr.back + arr.front + 1);
}

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

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

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

    if (n == 1) {
        writeln("not unique");
        return;
    }

    auto longer = zip(arr, arr.dropOne).map!(t => t[1] - t[0] > arr.front).array;

    debug { longer.writeln; }

    bool ok(bool lst) {
        auto lo = tuple(0, 1);
        auto hi = tuple(10, 1);

        int dst = 10;
        foreach (idx, e; longer ~ lst) {
            int stopNr = idx.to!int + 2;
            auto nxt = tuple(dst, stopNr);
            if (e) {
                lo = nxt;
                dst += 10;
            } else {
                hi = nxt;
            }
        }

        debug { writeln(lo, ' ', hi); }

        return lo[0] * hi[1] < hi[0] * lo[1];
    }

    bool ok1 = ok(false);
    bool ok2 = ok(true);

    debug { writeln(ok1, ' ', ok2); }

    if (ok1 && ok2) {
        writeln("not unique");
        return;
    }

    writeln("unique");
    writeln(ok1 ? arr.back + arr.front : arr.back + arr.front + 1);
}


Suppose you are performing the following algorithm. There is an array $$$v_1, v_2, \dots, v_n$$$ filled with zeroes at start. The following operation is applied to the array several times — at $$$i$$$-th step ($$$0$$$-indexed) you can:   either choose position $$$pos$$$ ($$$1 \le pos \le n$$$) and increase $$$v_{pos}$$$ by $$$k^i$$$;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $$$v$$$ equal to the given array $$$a$$$ ($$$v_j = a_j$$$ for each $$$j$$$) after some step?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 30$$$, $$$2 \le k \le 100$$$) — the size of arrays $$$v$$$ and $$$a$$$ and value $$$k$$$ used in the algorithm. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{16}$$$) — the array you'd like to achieve.

For each test case print YES (case insensitive) if you can achieve the array $$$a$$$ after some step or NO (case insensitive) otherwise.

NoteIn the first test case, you can stop the algorithm before the $$$0$$$-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add $$$k^0$$$ to $$$v_1$$$ and stop the algorithm.In the third test case, you can't make two $$$1$$$ in the array $$$v$$$.In the fifth test case, you can skip $$$9^0$$$ and $$$9^1$$$, then add $$$9^2$$$ and $$$9^3$$$ to $$$v_3$$$, skip $$$9^4$$$ and finally, add $$$9^5$$$ to $$$v_2$$$.

import std.stdio: writeln, readln;
import std.conv: to;
import std.array: split, array;
import std.algorithm: map, filter, any;
import std.string: chomp;

void main() {
	int t = readln.chomp.to!int;
	foreach (int _; 0..t) {
		int k = readln.chomp.split(" ").map!(to!int).array[1];
		long[] a = readln.chomp.split(" ").map!(to!long).array;

		string ans = "YES";
		while (a.any!((long x) => x != 0)) {
			long[] b = a.map!((long x) => x%k).filter!((long x) => x != 0).array;
			if (b > [1L]) {
				ans = "NO";
				break;
			}
			a = a.map!((long x) => x/k).array;
		}
		ans.writeln;
	}
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

bool test (in ulong[] a, uint k) {
  debug stderr.writeln (a);
  bool[int] m;
  foreach (x; a) {
    ulong y = x;
    int o;
    debug stderr.writeln ("x = ", x);
    while (y > 0) {
      uint t = (y % k).to!uint;
      debug stderr.writeln (y, ' ', t);
      if (t > 1) return false;
      if (t == 1) {
        if (o in m) return false;
        m[o] = true;
      }
      y /= k;
      ++o;
    }
  }
  return true;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint;
    const k = r.next!uint;
    auto a = r.nextA!ulong (n);
    writeln (test (a, k) ? "YES" : "NO");
  }
}

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 = 998244353;
//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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD;
		auto a = RDA;
		auto cnt = new int[](60);
		foreach (i; 0..n)
		{
			int j;
			while (a[i] != 0)
			{
				cnt[j] += a[i] % k;
				a[i] /= k;
				++j;
			}
		}
		bool ok = true;
		foreach (e; cnt)
		{
			if (e > 1)
				ok = false;
		}
		ans[ti] = ok;
	}

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


You are given a colored permutation $$$p_1, p_2, \dots, p_n$$$. The $$$i$$$-th element of the permutation has color $$$c_i$$$.Let's define an infinite path as infinite sequence $$$i, p[i], p[p[i]], p[p[p[i]]] \dots$$$ where all elements have same color ($$$c[i] = c[p[i]] = c[p[p[i]]] = \dots$$$).We can also define a multiplication of permutations $$$a$$$ and $$$b$$$ as permutation $$$c = a \times b$$$ where $$$c[i] = b[a[i]]$$$. Moreover, we can define a power $$$k$$$ of permutation $$$p$$$ as $$$p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$$$.Find the minimum $$$k > 0$$$ such that $$$p^k$$$ has at least one infinite path (i.e. there is a position $$$i$$$ in $$$p^k$$$ such that the sequence starting from $$$i$$$ is an infinite path).It can be proved that the answer always exists.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Next $$$3T$$$ lines contain test cases — one per three lines. The first line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the permutation. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, $$$p_i \neq p_j$$$ for $$$i \neq j$$$) — the permutation $$$p$$$. The third line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le n$$$) — the colors of elements of the permutation. It is guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print minimum $$$k > 0$$$ such that $$$p^k$$$ has at least one infinite path.

NoteIn the first test case, $$$p^1 = p = [1, 3, 4, 2]$$$ and the sequence starting from $$$1$$$: $$$1, p[1] = 1, \dots$$$ is an infinite path.In the second test case, $$$p^5 = [1, 2, 3, 4, 5]$$$ and it obviously contains several infinite paths.In the third test case, $$$p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$$$ and the sequence starting from $$$4$$$: $$$4, p^2[4]=8, p^2[8]=4, \dots$$$ is an infinite path since $$$c_4 = c_8 = 4$$$.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int;
        int[] ps = scan!int(n).map!(x => x - 1).array;
        int[] cs = scan!int(n);
        log("ps:", ps);
        log("cs:", cs);

        int[][] px;
        foreach(k; 0 .. 20){
            if(k == 0){
                int[] pq = [];
                foreach(i; 0 .. n) pq ~= ps[i];
                px ~= pq;
            }
            else{
                int[] pq = [];
                foreach(p; px[$ - 1]) pq ~= px[$ - 1][p];
                px ~= pq;
            }
        }
        int getP(int u, int t){
            int i = 0;
            while(t > 0){
                if(t % 2) u = px[i][u];
                i += 1;
                t /= 2;
            }
            return u;
        }

        auto uq = new Queue!int;
        foreach(i; 0 .. n) uq.enq(i);

        int ans = n + 1;

        bool[] visited = new bool[](n);
        while(uq.length){
            log("uq:", uq);
            int u = uq.deq;
            log("u:", u);
            if(visited[u]) continue;

            // うさぎとかめ法
            int v = u;
            while(1){
                visited[u] = 1;
                u = ps[u];
                v = ps[ps[v]];
                log("u:", u, "v:", v);
                if(u == v) break;
            }
            // 今、u, v はループ上の点
            int cnt = 0;
            while(1){
                cnt += 1;
                u = ps[u];
                if(u == v) break;
            }
            log("u:", u, "v:", v, "cnt:", cnt);
            // cnt の約数について試す
            int[] ds = cnt.divisors.to!(int[]);
            log("ds:", ds);
            B: foreach(d; ds){
                log("d:", d);
                if(d > ans) break;
                foreach(j; 0 .. d){
                    bool f = 1;
                    u = ps[u];
                    v = u;
                    while(1){
                        log("u:", u, "v:", v, "cs[u]:", cs[u], "cs[v]:", cs[v]);
                        if(cs[v] != cs[u]){
                            f = 0;
                            break;
                        }
                        v = getP(v, d);
                        if(u == v) break;
                    }
                    log("d:", d, "f:", f);
                    if(f){
                        ans.lowerTo(d);
                        break B;
                    }
                }
            }
        }

        ans.print;
    }
}

/// 約数の集合
/// 1とその数自身も含む、正の約数の集合。
/// 例 divisors(48) = [1, 2, 3, 4, 6, 8, 12, 16, 24, 48]
/// O(√N)
long[] divisors(long a){
	long[] res, res2;
	for(long d = 1; d * d <= a; d ++){
		if(a % d == 0) res ~= d, res2 ~=  a / d;
	}
	foreach_reverse(d; res2) if(res[$ - 1] < d) res ~= d;
	return res;
}

class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}


Recently, Vlad has been carried away by spanning trees, so his friends, without hesitation, gave him a connected weighted undirected graph of $$$n$$$ vertices and $$$m$$$ edges for his birthday.Vlad defined the ority of a spanning tree as the bitwise OR of all its weights, and now he is interested in what is the minimum possible ority that can be achieved by choosing a certain spanning tree. A spanning tree is a connected subgraph of a given graph that does not contain cycles.In other words, you want to keep $$$n-1$$$ edges so that the graph remains connected and the bitwise OR weights of the edges are as small as possible. You have to find the minimum bitwise OR itself.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. An empty line is written in front of each test case. This is followed by two numbers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and edges of the graph, respectively. The next $$$m$$$ lines contain the description of the edges. Line $$$i$$$ contains three numbers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$1 \le w_i \le 10^9$$$, $$$v_i \neq u_i$$$) — the vertices that the edge connects and its weight. It is guaranteed that the sum $$$m$$$ and the sum $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ and each test case contains a connected graph.

Print $$$t$$$ lines, each of which contains the answer to the corresponding set of input data — the minimum possible spanning tree ority.

Note  Graph from the first test case.   Ority of this tree equals to 2 or 2 = 2 and it's minimal.   Without excluding edge with weight $$$1$$$ ority is 1 or 2 = 3.

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

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

alias Edge = Tuple!(int, "to", long, "cost");

void solve() {
    readln;
    int N, M; readf("%d %d\n", &N, &M);
    auto G = new Edge[][N];
    foreach (i; 0 .. M) {
        int u, v; long w; readf("%d %d %d\n", &u, &v, &w);
        u--; v--;
        G[u] ~= Edge(v, w);
        G[v] ~= Edge(u, w);
    }

    long ans = 0;
    for (int k = 31; k >= 0; k--) {
        long mask = ans | ((1L<<k) - 1);
        //writefln("k = %s, mask = %s", k, mask);
        bool C() {
            auto uf = UnionFind(N);
            foreach (u; 0 .. N) {
                foreach (e; G[u]) {
                    if ((e.cost & mask) == e.cost) {
                        uf.merge(u, e.to);
                    }
                }
            }
            return uf.ngroups == 1;
        }
        if (C()) {
            // k-th bit can be zero.
        } else {
            // k-th bit cannot be zero.
            ans |= (1L<<k);
        }
    }
    writeln(ans);
}

struct UnionFind {
    int N;
    int[] parent;
    int[] size;
    int ngroups;
    this(int N) {
        this.N = N;
        this.parent = new int[N];
        this.parent[] = -1;
        this.size = new int[N];
        this.size[] = 1;
        this.ngroups = N;
    }
    int root(int x) {
        if (parent[x] < 0) return x;
        return parent[x] = root(parent[x]);
    }
    void merge(int x, int y) {
        x = root(x);
        y = root(y);
        if (x == y) return;
        if (size[x] < size[y]) {
            parent[x] = y;
            size[x] += size[y];
        } else {
            parent[y] = x;
            size[y] += size[x];
        }
        ngroups--;
    }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

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

alias Edge = Tuple!(int, "to", long, "cost");

void solve() {
    readln;
    int N, M; readf("%d %d\n", &N, &M);
    auto G = new Edge[][N];
    foreach (i; 0 .. M) {
        int u, v; long w; readf("%d %d %d\n", &u, &v, &w);
        u--; v--;
        G[u] ~= Edge(v, w);
        G[v] ~= Edge(u, w);
    }

    long ans = 0;
    for (int k = 31; k >= 0; k--) {
        auto sG = new Edge[][N];
        long mask = ans | ((1L<<k) - 1);
        //writefln("k = %s, mask = %s", k, mask);
        bool C() {
            auto uf = UnionFind(N);
            foreach (u; 0 .. N) {
                foreach (e; G[u]) {
                    if ((e.cost & mask) == e.cost) {
                        uf.merge(u, e.to);
                    }
                }
            }
            return uf.ngroups == 1;
        }
        if (C()) {
            // k-th bit can be zero.
        } else {
            // k-th bit cannot be zero.
            ans |= (1L<<k);
        }
    }
    writeln(ans);
}

struct UnionFind {
    int N;
    int[] parent;
    int[] size;
    int ngroups;
    this(int N) {
        this.N = N;
        this.parent = new int[N];
        this.parent[] = -1;
        this.size = new int[N];
        this.size[] = 1;
        this.ngroups = N;
    }
    int root(int x) {
        if (parent[x] < 0) return x;
        return parent[x] = root(parent[x]);
    }
    void merge(int x, int y) {
        x = root(x);
        y = root(y);
        if (x == y) return;
        if (size[x] < size[y]) {
            parent[x] = y;
            size[x] += size[y];
        } else {
            parent[y] = x;
            size[y] += size[x];
        }
        ngroups--;
    }
}

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

bool solve(int n, Tuple!(int, int, int)[] edges, int mask, ref int ans)
{
  auto uf = Dsu(n);
  foreach (e ; edges) {
    if (!uf.same(e[0], e[1]) && !(e[2] & mask)) {
      uf.merge(e[0], e[1]);
      ans |= e[2];
    }
  }
  return uf.size(0) == n;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, m;
    readf!" %d %d "(n, m);
    Tuple!(int, int, int)[] edges;
    foreach (i ; 0 .. m) {
      int u, v, w;
      readf!" %d %d %d "(v, u, w);
      v--;
      u--;
      edges ~= tuple(v, u, w);
    }
    edges.sort!((x, y) => x[2] < y[2]);
    int mask = 0;
    int best_ans = int.max;
    foreach_reverse(maskbit ; 0 .. 31) {
      int ans = 0;
      if (solve(n, edges, mask | (1 << maskbit), ans)) {
        best_ans = min(best_ans, ans);
        mask |= (1 << maskbit);
      }
    }

    writeln(best_ans);
  }
}

// Code from: https://github.com/kotet/atcoder-library-d

struct Dsu
{
public:
    this(long n) @safe nothrow
    {
        _n = cast(int) n, parent_or_size = new int[](cast(int)n);
        parent_or_size[] = -1;
    }

    int merge(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        int x = leader(a), y = leader(b);
        if (x == y)
            return x;
        if (-parent_or_size[x] < -parent_or_size[y])
        {
            auto tmp = x;
            x = y;
            y = tmp;
        }
        parent_or_size[x] += parent_or_size[y];
        parent_or_size[y] = x;
        return x;
    }

    bool same(long a, long b) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        assert(0 <= b && b < _n);
        return leader(a) == leader(b);
    }

    int leader(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        if (parent_or_size[cast(int)a] < 0)
            return cast(int) a;
        return parent_or_size[cast(int)a] = leader(parent_or_size[cast(int)a]);
    }

    int size(long a) @safe nothrow @nogc
    {
        assert(0 <= a && a < _n);
        return -parent_or_size[leader(a)];
    }

    int[][] groups() @safe nothrow
    {
        auto leader_buf = new int[](_n), group_size = new int[](_n);
        foreach (i; 0 .. _n)
        {
            leader_buf[i] = leader(i);
            group_size[leader_buf[i]]++;
        }
        auto result = new int[][](_n);
        foreach (i; 0 .. _n)
            result[i].reserve(group_size[i]);
        foreach (i; 0 .. _n)
            result[leader_buf[i]] ~= i;
        int[][] filtered;
        foreach (r; result)
            if (r.length != 0)
                filtered ~= r;
        return filtered;
    }

private:
    int _n;
    int[] parent_or_size;
}


Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day — exactly $$$2$$$ problems, during the third day — exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — the number of problems in the $$$i$$$-th contest.

Print one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    A.sort();
    int ans = 0;

    for (int i = 1, p = 0; i <= N && p < N; ++i, ++p) {
        while (p < N && A[p] < i) ++p;
        if (p >= N) break;
        ans += 1;
    }

    ans.writeln;
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;

	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;

	as.sort!();

	int ans = 0;
	for(int i = 0, j = 0; i < n && j < n; ){
		if(as[j] < i + 1){
			j += 1;
		}
		else{
			ans += 1;
			i += 1, j += 1;
		}
	}
	ans.writeln;

}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
    GC.disable();

    uint n;
    readf(" %s", n);
    auto a = new long[n];
    iota(0, n).each!(i => readf(" %s", a[i]));

    sort(a);
    uint s = 0;
    long k = 1;
    long d = 0;
    // writeln(a);
    while(s < n) {
      while(s < n && a[s] < k) s++;
      if (s >= n) break;
      // writeln(k, " " , s, " ", a[s]);
      if (k <= a[s]) { d++; }
      k += 1;
      s++;
    }

    writeln(d);
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!int;
	auto a = RDR.ARR;
	a.sort();

	long ans;
	foreach (i; 0..N)
	{
		if (a[i] > ans)
			++ans;
	}

	writeln(ans);
	stdout.flush();
	debug readln();
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
    GC.disable();

    uint n;
    readf(" %s", n);
    auto a = new long[n];
    iota(0, n).each!(i => readf(" %s", a[i]));

    sort(a);
    uint s = 0;
    long k = 1;
    long d = 0;
    // writeln(a);
    while(s < n) {
      while(s < n && a[s] < k) s++;
      if (s >= n) break;
      // writeln(k, " " , s, " ", a[s]);
      if (k <= a[s]) { d++; }
      k *= 2;
      s++;
    }

    writeln(d);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
    GC.disable();

    uint n;
    readf(" %s", n);
    auto a = new int[n];
    iota(0, n).each!(i => readf(" %s", a[i]));

    sort(a);
    uint s = 0;
    uint k = 1;
    uint d = 1;
    while(true) {
      while(s < n && a[s] < k) s++;
      if (s >= n) {writeln(d); return;}
      // writeln(s, " " , a[s], " ",  k);
      d ++;
      k *= 2;
      s++;
      if (s >= n) {writeln(d-1); return ; }
    }

    assert(false);
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!int;
	auto a = RDR.ARR;
	a.sort();

	debug writeln(a.uniq);
	writeln(a.uniq.array.length);
	stdout.flush();
	debug readln();
}


In the year of $$$30XX$$$ participants of some world programming championship live in a single large hotel. The hotel has $$$n$$$ floors. Each floor has $$$m$$$ sections with a single corridor connecting all of them. The sections are enumerated from $$$1$$$ to $$$m$$$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $$$n$$$ and width $$$m$$$. We can denote sections with pairs of integers $$$(i, j)$$$, where $$$i$$$ is the floor, and $$$j$$$ is the section number on the floor.The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $$$(1, x)$$$, $$$(2, x)$$$, $$$\ldots$$$, $$$(n, x)$$$ for some $$$x$$$ between $$$1$$$ and $$$m$$$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $$$v$$$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.You are to process $$$q$$$ queries. Each query is a question "what is the minimum time needed to go from a room in section $$$(x_1, y_1)$$$ to a room in section $$$(x_2, y_2)$$$?"

The first line contains five integers $$$n, m, c_l, c_e, v$$$ ($$$2 \leq n, m \leq 10^8$$$, $$$0 \leq c_l, c_e \leq 10^5$$$, $$$1 \leq c_l + c_e \leq m - 1$$$, $$$1 \leq v \leq n - 1$$$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains $$$c_l$$$ integers $$$l_1, \ldots, l_{c_l}$$$ in increasing order ($$$1 \leq l_i \leq m$$$), denoting the positions of the stairs. If $$$c_l = 0$$$, the second line is empty. The third line contains $$$c_e$$$ integers $$$e_1, \ldots, e_{c_e}$$$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $$$l_i$$$ and $$$e_i$$$ are distinct. The fourth line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — the number of queries. The next $$$q$$$ lines describe queries. Each of these lines contains four integers $$$x_1, y_1, x_2, y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1 \leq y_1, y_2 \leq m$$$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $$$y_1$$$ and $$$y_2$$$ are not among $$$l_i$$$ and $$$e_i$$$.

Print $$$q$$$ integers, one per line — the answers for the queries.

NoteIn the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

const inf = 10^^9;

void main()
{
  int n, m, cl, ce, v; readV(n, m, cl, ce, v);
  int[] l; readA(cl, l);
  int[] e; readA(ce, e);

  auto ls = l.assumeSorted, es = e.assumeSorted;

  auto calcWalk(R)(int yi, int ya, R s)
  {
    auto c = s.upperBound(yi).lowerBound(ya);
    if (!c.empty) return ya-yi;

    auto ci = s.lowerBound(yi), ca = s.upperBound(ya);
    return min(ci.empty ? inf : yi-ci.back, ca.empty ? inf : ca.front-ya)*2 + ya-yi;
  }

  int q; readV(q);
  foreach (_; 0..q) {
    int x1, y1, x2, y2; readV(x1, y1, x2, y2);
    auto yi = min(y1, y2), ya = max(y1, y2);

    auto calcTime()
    {
      if (x1 == x2) return (y1-y2).abs;

      auto tl = ls.empty ? inf : calcWalk(yi, ya, ls) + (x1-x2).abs;
      auto te = es.empty ? inf : calcWalk(yi, ya, es) + ((x1-x2).abs+v-1)/v;

      return min(tl, te);
    }

    writeln(calcTime);
  }
}


Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:  Remove a single cow from a chosen non-empty pile.  Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109). The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.

Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).

NoteIn the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.

import std.algorithm, std.conv, std.range, std.stdio;
int g (int x) {return (x < 2) ? x : (x < 5) ? (x - 2) : (x & 1) ? 0 : (1 + (g (x / 2) == 1));}
int h (int x) {return (x < 3) ? x : !(x & 1);}
void main () {
	int n, k;
	readf (" %s %s", &n, &k);
	k %= 2;
	readln;
	writeln (readln.split.map !(to !(int)).map !(x => k ? g (x) : h (x)).reduce !(q{a ^ b}) ? "Kevin" : "Nicky");
}

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;

pure int g (int x)
{
	if (x < 5)
	{
		return [0, 1, 0, 1, 2][x];
	}
	if (x % 2 != 0)
	{
		return 0;
	}
	int v = g (x / 2);
	return 1 + (v == 1);
}

pure int h (int x)
{
	if (x < 3)
	{
		return [0, 1, 2][x];
	}
	if (x % 2 != 0)
	{
		return 0;
	}
	return 1;
}

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		k %= 2;
		int res;
		if (k)
		{
			res = a.map !(x => g (x)).reduce !(q{a ^ b});
		}
		else
		{
			res = a.map !(x => h (x)).reduce !(q{a ^ b});
		}
		debug {writeln (n, ' ', k, ' ', a[0], ' ', res);}
		writeln (res ? "Kevin" : "Nicky");
	}
}

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;

pure int g (int x)
{
	if (x < 5)
	{
		return [0, 1, 0, 1, 2][x];
	}
	if (x % 2 != 0)
	{
		return 0;
	}
	return 3 ^ g (x / 2);
}

pure int h (int x)
{
	if (x < 3)
	{
		return [0, 1, 2][x];
	}
	if (x % 2 != 0)
	{
		return 0;
	}
	return 1;
}

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		k %= 2;
		int res;
		if (k)
		{
			res = a.map !(x => g (x)).reduce !(q{a ^ b});
		}
		else
		{
			res = a.map !(x => h (x)).reduce !(q{a ^ b});
		}
		writeln (res ? "Kevin" : "Nicky");
	}
}


Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following:  For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.

For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.

NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.

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)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = new long [] [n];
		auto w = new long [n];
		foreach (i; 0..n)
		{
			c[i] = readln.splitter.map !(to !(long)).array;
			foreach (j; 0..m)
			{
				w[i] += c[i][j] * j;
			}
		}
		auto p = w.length - w.maxPos.length;
		writeln (p + 1, " ", w[p] - w[!p]);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readInt;
        auto C = new long[][](N, M);
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            C[i][j] = readLong;
          }
        }

        auto fs = new long[N];
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            fs[i] += j * C[i][j];
          }
        }
        debug {
          writeln("fs = ", fs);
        }
        const minF = fs.minElement;
        const maxF = fs.maxElement;

        int im = -1;
        foreach (i; 0 .. N) {
          if (maxF == fs[i]) {
            im = i;
            break;
          }
        }
        writeln(im + 1, " ", maxF - minF);
      }
    }
  } catch (EOFException e) {
  }
}

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)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = new int [] [n];
		auto w = new long [n];
		foreach (i; 0..n)
		{
			c[i] = readln.splitter.map !(to !(int)).array;
			foreach (j; 0..m)
			{
				w[i] += c[i][j] * j;
			}
		}
		auto p = w.length - w.maxPos.length;
		writeln (p + 1, " ", w[p] - w[!p]);
	}
}