You're given an undirected graph with $$$n$$$ nodes and $$$m$$$ edges. Nodes are numbered from $$$1$$$ to $$$n$$$.The graph is considered harmonious if and only if the following property holds:  For every triple of integers $$$(l, m, r)$$$ such that $$$1 \le l < m < r \le n$$$, if there exists a path going from node $$$l$$$ to node $$$r$$$, then there exists a path going from node $$$l$$$ to node $$$m$$$. In other words, in a harmonious graph, if from a node $$$l$$$ we can reach a node $$$r$$$ through edges ($$$l < r$$$), then we should able to reach nodes $$$(l+1), (l+2), \ldots, (r-1)$$$ too.What is the minimum number of edges we need to add to make the graph harmonious?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 200\ 000$$$ and $$$1 \le m \le 200\ 000$$$). The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$), that mean that there's an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).

Print the minimum number of edges we have to add to the graph to make it harmonious.

NoteIn the first example, the given graph is not harmonious (for instance, $$$1 < 6 < 7$$$, node $$$1$$$ can reach node $$$7$$$ through the path $$$1 \rightarrow 2 \rightarrow 7$$$, but node $$$1$$$ can't reach node $$$6$$$). However adding the edge $$$(2, 4)$$$ is sufficient to make it harmonious.In the second example, the given graph is already harmonious.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new int[][](N);
    auto uf = new UnionFind(N);

    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        G[a] ~= b;
        G[b] ~= a;
        uf.unite(a, b);
    }

    Tuple!(int, int)[] A;
    foreach (i; 0..N) if (uf.table[i] < 0) A ~= tuple(uf.mn[i], uf.mx[i]);

    A.sort!"a[0] < b[0]";
    auto t = A.front;
    int ans = 0;

    foreach (i; 1..A.length.to!int) {
        if (A[i][0] > t[1]) {
            t = A[i];
        } else {
            ans += 1;
            t[1] = max(t[1], A[i][1]);
        }
    }

    ans.writeln;
}

class UnionFind {
    import std.algorithm : swap;

    int n;
    int[] table;
    int[] mn;
    int[] mx;

    this(int n) {
        this.n = n;
        table = new int[](n);
        table[] = -1;
        mn = n.iota.array;
        mx = n.iota.array;
    }

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

    void unite(int x, int y) {
        int ox = x;
        int oy = y;
        x = find(x);
        y = find(y);
        mn[x] = min(mn[x], mn[y], ox, oy);
        mx[x] = max(mx[x], mx[y], ox, oy);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        mn[x] = min(mn[x], mn[y], ox, oy);
        mx[x] = max(mx[x], mx[y], ox, oy);
        table[x] += table[y];
        table[y] = x;
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }
}

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional, std.meta;
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.ascii, std.typecons;

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

    auto mx = new int[] (n+1);
    foreach (i; 1 .. n+1) { mx[i] = i; }

    struct UF {
        int[] p, r;

        this (int n) {
            p = new int[] (n+1);
            r = new int[] (n+1);
            foreach (i; 1 .. n+1) {
                p[i] = i;
                r[i] = 1;
            }
        }

        int fnd(int v) {
            if (p[v] != v) {
                p[v] = fnd(p[v]);
            }

            return p[v];
        }

        void uni(int a, int b) {
            a = fnd(a);
            b = fnd(b);

            if (a == b) { return; }

            if (r[a] > r[b]) { swap(a, b); }

            p[a] = b;

            if (r[a] == r[b]) { ++r[b]; }
        }
    }

    auto uf = UF(n);

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        mx[u] = max(mx[u], v);
        mx[v] = max(mx[v], u);

        uf.uni(u, v);
    }

    int ans = 0;
    int le = 1;
    while (le <= n) {
        int r = mx[le];
        int p = le+1;
        while (p <= r) {
            if (uf.fnd(le) != uf.fnd(p)) {
                ans += 1;
                uf.uni(le, p);
            }
            r = max(r, mx[p]);
            ++p;
        }

        le = r + 1;
    }

    ans.writeln;
}

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

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

void solve(){
	int n = rint, m = rint;
	Node[] nodes;
	foreach(i; 0 .. n) nodes ~= new Node(i, 0);

	X[] xs;
	foreach(j; 0 .. m){
		int a = rint - 1, b = rint - 1;
		if(a < b) xs ~= X(a, b);
		else xs ~= X(b, a);
	}
	log("xs:", xs);

	int[] us = new int[](n + 9);
	foreach(x; xs) us[x.a] += 1, us[x.b] -= 1;
	log("us:", us);

	int rangecount;
	int sum;
	foreach(i; 0 .. n){
		if(sum == 0 && us[i] > 0) rangecount += 1;
		if(sum > 0 || sum + us[i] > 0) nodes[i].value = 1;
		sum += us[i];
	}
	log("rangecount:", rangecount);

	foreach(x; xs) nodes[x.a].group.eat(nodes[x.b].group);
	int groupcount;
	foreach(nd; nodes){
		if(nd.value > 0 && nd.group.id == nd.id) groupcount += 1;
	}
	log("groupcount:", groupcount);

	int ans = groupcount - rangecount;
	ans.writeln;

}
struct X{
	int a, b;
}
/*

count how many distinct segment unions.
count how many connected subgraphs.

*/

// Union-Find 整理されているもの ※Edgeは使わなくてもよい
// 使い方は nd1.group.eat(nd2.group);
class Edge{
	Node node1;
	Node node2;
	long value;
	this(Node node1, Node node2, long value){
		this.node1 = node1, this.node2 = node2;
		this.value = value;
	}
}

class Node{
	long id;
	long value;
	Group group;
	this(long id, long value){
		this.id = id;
		this.value = value;
		this.group = new Group(this);
	}
}

class Group{
	long value;
	long id;
	Node[] nodes;
	this(Node node){
		this.id = node.id;
		this.nodes = [node];
		this.value = node.value;
	}
	void eat(Group gp){
		if(this.id == gp.id) return;
		if(gp.nodes.length > this.nodes.length) gp.eat(this);
		else{
			foreach(nd; gp.nodes){
				this.nodes ~= nd;
				nd.group = this;
				this.value += nd.value;
			}
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

struct UnionFind
{
	void init(int n) { par = new int[](n); foreach (i; 0..n) par[i] = i; cnt = new int[](n); fill(cnt, 1); }
	int root(int i) { return par[i] == i ? i : (par[i] = root(par[i])); }
	bool same(int i, int j) { return root(i) == root(j); }
	void unite(int i, int j) { i = root(i); j = root(j); if (i == j) return; par[i] = j; cnt[j] += cnt[i]; }
	int size(int i) { return cnt[root(i)]; }
	int[] par, cnt;
}

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	UnionFind uf;
	uf.init(n);
	foreach (i; 0..m)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		uf.unite(u, v);
	}

	auto r = new int[](n);
	auto lr = new int[][](n, 2);
	foreach (i; 0..n)
		lr[i][0] = int.max;

	foreach (i; 0..n)
	{
		auto p = uf.root(i);
		r[i] = p;
		lr[p][0] = min(lr[p][0], i);
		lr[p][1] = max(lr[p][1], i);
	}

	auto index = lr.MAKE_IDX!"a[0] < b[0]";
	auto rMax = new int[](n+1);
	foreach (i; 0..n)
	{
		rMax[i+1] = max(rMax[i], lr[index[i]][1]);
	}
	long ans;
	foreach (ii, i; index)
	{
		if (lr[i][0] == int.max) break;
		if (lr[i][0] < rMax[ii])
			++ans;
	}

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

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new int[][](N);
    auto uf = new UnionFind(N);

    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        G[a] ~= b;
        G[b] ~= a;
        uf.unite(a, b);
    }

    Tuple!(int, int)[] A;
    foreach (i; 0..N) if (uf.table[i] < 0) A ~= tuple(uf.mn[i], uf.mx[i]);

    A.sort!"a[0] < b[0]";
    auto t = A.front;
    int ans = 0;

    foreach (i; 1..A.length.to!int) {
        if (A[i][0] > t[1]) {
            t = A[i];
        } else {
            ans += 1;
            t[1] = max(t[1], A[i][1]);
        }
    }

    ans.writeln;
}

class UnionFind {
    import std.algorithm : swap;

    int n;
    int[] table;
    int[] mn;
    int[] mx;

    this(int n) {
        this.n = n;
        table = new int[](n);
        table[] = -1;
        mn = n.iota.array;
        mx = n.iota.array;
    }

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

    void unite(int x, int y) {
        int ox = x;
        int oy = y;
        x = find(x);
        y = find(y);
        mn[x] = min(mn[x], ox, oy);
        mx[x] = max(mx[x], ox, oy);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        table[x] += table[y];
        table[y] = x;
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new int[][](N);
    auto uf = new UnionFind(N);

    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        G[a] ~= b;
        G[b] ~= a;
        uf.unite(a, b);
    }

    Tuple!(int, int)[] A;
    foreach (i; 0..N) if (uf.table[i] < 0) A ~= tuple(uf.mn[i], uf.mx[i]);

    A.sort!"a[0] < b[0]";
    auto t = A.front;
    int ans = 0;

    foreach (i; 1..A.length.to!int) {
        if (A[i][0] > t[1]) {
            t = A[i];
        } else {
            ans += 1;
            t[1] = A[i][1];
        }
    }

    ans.writeln;
}

class UnionFind {
    import std.algorithm : swap;

    int n;
    int[] table;
    int[] mn;
    int[] mx;

    this(int n) {
        this.n = n;
        table = new int[](n);
        table[] = -1;
        mn = n.iota.array;
        mx = n.iota.array;
    }

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

    void unite(int x, int y) {
        int ox = x;
        int oy = y;
        x = find(x);
        y = find(y);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        mn[x] = min(mn[x], ox, oy);
        mx[x] = max(mx[x], ox, oy);
        table[x] += table[y];
        table[y] = x;
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new int[][](N);
    auto uf = new UnionFind(N);

    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        G[a] ~= b;
        G[b] ~= a;
        uf.unite(a, b);
    }

    Tuple!(int, int)[] A;
    foreach (i; 0..N) if (uf.table[i] < 0) A ~= tuple(uf.mn[i], uf.mx[i]);

    A.sort!"a[0] < b[0]";
    auto t = A.front;
    int ans = 0;

    foreach (i; 1..A.length.to!int) {
        if (A[i][0] > t[1]) {
            t = A[i];
        } else {
            ans += 1;
            t[1] = max(t[1], A[i][1]);
        }
    }

    ans.writeln;
}

class UnionFind {
    import std.algorithm : swap;

    int n;
    int[] table;
    int[] mn;
    int[] mx;

    this(int n) {
        this.n = n;
        table = new int[](n);
        table[] = -1;
        mn = n.iota.array;
        mx = n.iota.array;
    }

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

    void unite(int x, int y) {
        int ox = x;
        int oy = y;
        x = find(x);
        y = find(y);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        mn[x] = min(mn[x], ox, oy);
        mx[x] = max(mx[x], ox, oy);
        table[x] += table[y];
        table[y] = x;
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new int[][](N);
    auto uf = new UnionFind(N);

    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        G[a] ~= b;
        G[b] ~= a;
        uf.unite(a, b);
    }

    Tuple!(int, int)[] A;
    foreach (i; 0..N) if (uf.table[i] < 0) A ~= tuple(uf.mn[i], uf.mx[i]);

    A.sort!"a[0] < b[0]";
    auto t = A.front;
    int ans = 0;

    foreach (i; 1..A.length.to!int) {
        if (A[i][0] > t[1]) {
            t = A[i];
        } else {
            ans += 1;
            t[1] = max(t[1], A[i][1]);
        }
    }

    ans.writeln;
}

class UnionFind {
    import std.algorithm : swap;

    int n;
    int[] table;
    int[] mn;
    int[] mx;

    this(int n) {
        this.n = n;
        table = new int[](n);
        table[] = -1;
        mn = n.iota.array;
        mx = n.iota.array;
    }

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

    void unite(int x, int y) {
        int ox = x;
        int oy = y;
        x = find(x);
        y = find(y);
        mn[x] = min(mn[x], ox, oy);
        mx[x] = max(mx[x], ox, oy);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        mn[x] = min(mn[x], ox, oy);
        mx[x] = max(mx[x], ox, oy);
        table[x] += table[y];
        table[y] = x;
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }
}

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

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

void solve(){
	int n = rint, m = rint;
	Node[] nodes;
	foreach(i; 0 .. n) nodes ~= new Node(i, 0);

	X[] xs;
	foreach(j; 0 .. m){
		xs ~= X(rint - 1, rint - 1);
	}
	log("xs:", xs);

	foreach(x; xs){
		nodes[x.a].value = 1;
		nodes[x.b].value = 1;
		nodes[x.a].group.eat(nodes[x.b].group);
	}
	int groupcount;
	foreach(nd; nodes){
		if(nd.value > 0 && nd.group.id == nd.id) groupcount += 1;
	}
	log("groupcount:", groupcount);

	int[] us = new int[](n + 9);
	foreach(x; xs) us[x.a] += 1, us[x.b] -= 1;
	log("us:", us);

	int rangecount;
	int sum;
	foreach(i; 0 .. n){
		if(sum == 0 && us[i] > 0) rangecount += 1;
		sum += us[i];
	}
	log("rangecount:", rangecount);

	int ans = groupcount - rangecount;
	ans.writeln;

}
struct X{
	int a, b;
}
/*

count how many distinct segment unions.
count how many connected subgraphs.

*/

// Union-Find 整理されているもの ※Edgeは使わなくてもよい
// 使い方は nd1.group.eat(nd2.group);
class Edge{
	Node node1;
	Node node2;
	long value;
	this(Node node1, Node node2, long value){
		this.node1 = node1, this.node2 = node2;
		this.value = value;
	}
}

class Node{
	long id;
	long value;
	Group group;
	this(long id, long value){
		this.id = id;
		this.value = value;
		this.group = new Group(this);
	}
}

class Group{
	long value;
	long id;
	Node[] nodes;
	this(Node node){
		this.id = node.id;
		this.nodes = [node];
		this.value = node.value;
	}
	void eat(Group gp){
		if(this.id == gp.id) return;
		if(gp.nodes.length > this.nodes.length) gp.eat(this);
		else{
			foreach(nd; gp.nodes){
				this.nodes ~= nd;
				nd.group = this;
				this.value += nd.value;
			}
		}
	}
}

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

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

void solve(){
	int n = rint, m = rint;
	Node[] nodes;
	foreach(i; 0 .. n) nodes ~= new Node(i, 0);

	X[] xs;
	foreach(j; 0 .. m){
		xs ~= X(rint - 1, rint - 1);
	}
	log("xs:", xs);

	int[] us = new int[](n + 9);
	foreach(x; xs) us[x.a] += 1, us[x.b] -= 1;
	log("us:", us);

	int rangecount;
	int sum;
	foreach(i; 0 .. n){
		if(sum == 0 && us[i] > 0) rangecount += 1;
		if(sum > 0 || sum + us[i] > 0) nodes[i].value = 1;
		sum += us[i];
	}
	log("rangecount:", rangecount);

	foreach(x; xs) nodes[x.a].group.eat(nodes[x.b].group);
	int groupcount;
	foreach(nd; nodes){
		if(nd.value > 0 && nd.group.id == nd.id) groupcount += 1;
	}
	log("groupcount:", groupcount);

	int ans = groupcount - rangecount;
	ans.writeln;

}
struct X{
	int a, b;
}
/*

count how many distinct segment unions.
count how many connected subgraphs.

*/

// Union-Find 整理されているもの ※Edgeは使わなくてもよい
// 使い方は nd1.group.eat(nd2.group);
class Edge{
	Node node1;
	Node node2;
	long value;
	this(Node node1, Node node2, long value){
		this.node1 = node1, this.node2 = node2;
		this.value = value;
	}
}

class Node{
	long id;
	long value;
	Group group;
	this(long id, long value){
		this.id = id;
		this.value = value;
		this.group = new Group(this);
	}
}

class Group{
	long value;
	long id;
	Node[] nodes;
	this(Node node){
		this.id = node.id;
		this.nodes = [node];
		this.value = node.value;
	}
	void eat(Group gp){
		if(this.id == gp.id) return;
		if(gp.nodes.length > this.nodes.length) gp.eat(this);
		else{
			foreach(nd; gp.nodes){
				this.nodes ~= nd;
				nd.group = this;
				this.value += nd.value;
			}
		}
	}
}


Alice and Bob are playing a game on a sequence $$$a_1, a_2, \dots, a_n$$$ of length $$$n$$$. They move in turns and Alice moves first.In the turn of each player, he or she should select an integer and remove it from the sequence. The game ends when there is no integer left in the sequence. Alice wins if the sum of her selected integers is even; otherwise, Bob wins. Your task is to determine who will win the game, if both players play optimally.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$), indicating the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$), indicating the elements of the sequence.

For each test case, output "Alice" (without quotes) if Alice wins and "Bob" (without quotes) otherwise.

NoteIn the first and second test cases, Alice always selects two odd numbers, so the sum of her selected numbers is always even. Therefore, Alice always wins.In the third test case, Bob has a winning strategy that he always selects a number with the same parity as Alice selects in her last turn. Therefore, Bob always wins.In the fourth test case, Alice always selects two even numbers, so the sum of her selected numbers is always even. Therefore, Alice always wins.

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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto x = a.count !(v => v % 2 == 0).to !(int);
		auto y = n - x;
		debug {writeln (x, " ", y);}
		auto f = new int [2] [] [] (x + 1, y + 1);
		foreach (ref g; f)
		{
			foreach (ref h; g)
			{
				h[] = NA;
			}
		}

		int go (int i, int j, int b)
		{
			if (f[i][j][b] == NA)
			{
				if (i == x && j == y)
				{
					return !b ^ ((i + j) & 1);
				}
				int res = 0;
				if (i < x)
				{
					res |= !go (i + 1, j, b);
				}
				if (j < y)
				{
					res |= !go (i, j + 1,
					    !b ^ ((i + j) & 1));
				}
				f[i][j][b] = res;
			}
			return f[i][j][b];
		}

		writeln (go (0, 0, 0) ? "Alice" : "Bob");
	}
}

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

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;

    auto init = tuple(0, 0);
    foreach (a; A) {
        if (a % 2 == 0) {
            init[0]++;
        } else {
            init[1]++;
        }
    }

    bool[Tuple!(int,int,int,int)] cache;
    int f(int p, int s, int e, int o) {
        // p: 0:alice, 1:bob
        // s: alice's hand
        auto key = tuple(p, s, e, o);
        if (key in cache) return cache[key];
        if (e == 0 && o == 0) {
            return (p == 0 && s == 0) || (p == 1 && s == 1);
        }
        if (p == 0) {
            bool a_win = false;
            // alice's turn
            if (e >= 1) { a_win = a_win || !f(!p, s, e-1, o); }
            if (o >= 1) { a_win = a_win || !f(!p, !s, e, o-1); }
            return cache[key] = a_win;
        } else {
            bool b_win = false;
            if (e >= 1) { b_win = b_win || !f(!p, s, e-1, o); }
            if (o >= 1) { b_win = b_win || !f(!p, s, e, o-1); }
            return cache[key] = b_win;
        }
    }
    writeln(f(0, 0, init[0], init[1]) ? "Alice" : "Bob");
}

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

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

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

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

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

enum LIM = 105;

void main() {
  auto ali = new bool[][][](LIM, LIM, 2);
  auto bob = new bool[][][](LIM, LIM, 2);
  foreach (m; 0 .. LIM) foreach (n; 0 .. LIM) foreach (s; 0 .. 2) {
    if (m == 0 && n == 0) {
      ali[m][n][s] = (s == 0);
      bob[m][n][s] = (s != 0);
    } else {
      if (m > 0 && !bob[m - 1][n][s ^ 0]) ali[m][n][s] = true;
      if (n > 0 && !bob[m][n - 1][s ^ 1]) ali[m][n][s] = true;
      if (m > 0 && !ali[m - 1][n][s]) bob[m][n][s] = true;
      if (n > 0 && !ali[m][n - 1][s]) bob[m][n][s] = true;
    }
  }
  debug {
    foreach (m; 0 .. 10) write(m, ": ", ali[m]);
    foreach (m; 0 .. 10) write(m, ": ", bob[m]);
  }

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

        int[2] cnt;
        foreach (i; 0 .. N) {
          ++cnt[A[i] & 1];
        }
        const ans = ali[cnt[0]][cnt[1]][0];
        writeln(ans ? "Alice" : "Bob");
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto x = a.count !(v => v % 2 == 0).to !(int);
		auto y = n - x;
		debug {writeln (x, " ", y);}
		auto f = new bool [2] [] [] (x + 1, y + 1);
		f[x][y][0] = true;
		foreach_reverse (t; 0..x + y)
		{
			foreach (i; 0..x + 1)
			{
				int j = t - x;
				if (!(0 <= j && j <= y))
				{
					continue;
				}
				foreach (b; 0..2)
				{
					if (t & 1) // Bob moves
					{
						f[i][j][b] = true;
						if (i < x)
						{
							f[i][j][b] &= f[i + 1][j][b ^ 0];
						}
						if (j < y)
						{
							f[i][j][b] &= f[i][j + 1][b ^ 0];
						}
					}
					else // Alice moves
					{
						f[i][j][b] = false;
						if (i < x)
						{
							f[i][j][b] |= f[i + 1][j][b ^ 0];
						}
						if (j < y)
						{
							f[i][j][b] |= f[i][j + 1][b ^ 1];
						}
					}
				}
			}
		}
		debug {writefln !("%(%(%(%d%) %)\n%)") (f);}
		writeln (f[0][0][0] ? "Alice" : "Bob");
	}
}


There are $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$. For the one move you can choose any even value $$$c$$$ and divide by two all elements that equal $$$c$$$.For example, if $$$a=[6,8,12,6,3,12]$$$ and you choose $$$c=6$$$, and $$$a$$$ is transformed into $$$a=[3,8,12,3,3,12]$$$ after the move.You need to find the minimal number of moves for transforming $$$a$$$ to an array of only odd integers (each element shouldn't be divisible by $$$2$$$).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of integers in the sequence $$$a$$$. The second line contains positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$.

For $$$t$$$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $$$2$$$).

NoteIn the first test case of the example, the optimal sequence of moves can be as follows:  before making moves $$$a=[40, 6, 40, 3, 20, 1]$$$;  choose $$$c=6$$$;  now $$$a=[40, 3, 40, 3, 20, 1]$$$;  choose $$$c=40$$$;  now $$$a=[20, 3, 20, 3, 20, 1]$$$;  choose $$$c=20$$$;  now $$$a=[10, 3, 10, 3, 10, 1]$$$;  choose $$$c=10$$$;  now $$$a=[5, 3, 5, 3, 5, 1]$$$ — all numbers are odd. Thus, all numbers became odd after $$$4$$$ moves. In $$$3$$$ or fewer moves, you cannot make them all odd.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!uint;
		bool[uint] set;
		foreach (e; a)
		{
			if (e % 2 == 0)
				set[e] = true;
		}
		foreach (key; set.keys)
		{
			while (key % 2 == 0)
			{
				++ans[i];
				key >>= 1;
				if (set.get(key, false))
					break;
			}
		}
	}

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


Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?

The first line contains string a, the second line contains string b, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where |s| denotes the length of string s). All three strings consist only of lowercase English letters.  It is possible that b and c coincide.

Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.

NoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc.

import std.stdio,std.range,std.string,std.algorithm;
void main(){
	string[3] s;
	foreach(ref x;s) x=readln.strip;
	auto x=s[].map!(p=>iota('a','z'+1).map!(c=>p.count(c)).array).array;
	size_t[3] r;
	foreach(b;0..s[0].length){
		if(zip(x[0],x[1]).any!(x=>x[0]<b*x[1])) break;
		auto c=zip(x[0],x[1],x[2]).map!(x=>x[2]?(x[0]-b*x[1])/x[2]:size_t.max).reduce!min;
		if(b+c>r[0]) r=[b+c,b,c];
	}
	string t;
	foreach(i;1..3) foreach(j;0..r[i]) t~=s[i];
	x[0][]-=r[1]*x[1][]+r[2]*x[2][];
	foreach(i;0..26) foreach(j;0..x[0][i]) t~=i+'a';
	writeln(t);
}

import std.stdio,std.range,std.string,std.algorithm;
void main(){
	string[4] s;
	foreach(ref x;s) x=readln.strip;
	auto x=s[].map!(p=>iota('a','z'+1).map!(c=>p.count(c)).array).array;
	size_t[3] r;
	foreach(b;0..s[0].length){
		if(zip(x[0],x[1]).any!(x=>x[0]<b*x[1])) break;
		auto c=zip(x[0],x[1],x[2]).map!(x=>x[2]?(x[0]-b*x[1])/x[2]:size_t.max).reduce!min;
		r=max(r,[b+c,b,c]);
	}
	foreach(i;1..3) foreach(j;0..r[1]) s[3]~=s[1];
	x[0][]-=r[1]*x[1][]+r[2]*x[2][];
	foreach(i;0..26) foreach(j;0..x[0][i]) s[3]~=i+'a';
	writeln(s[3]);}


Let's say you are standing on the $$$XY$$$-plane at point $$$(0, 0)$$$ and you want to reach point $$$(n, n)$$$.You can move only in two directions:   to the right, i. e. horizontally and in the direction that increase your $$$x$$$ coordinate,  or up, i. e. vertically and in the direction that increase your $$$y$$$ coordinate. In other words, your path will have the following structure:   initially, you choose to go to the right or up;  then you go some positive integer distance in the chosen direction (distances can be chosen independently);  after that you change your direction (from right to up, or from up to right) and repeat the process. You don't like to change your direction too much, so you will make no more than $$$n - 1$$$ direction changes.As a result, your path will be a polygonal chain from $$$(0, 0)$$$ to $$$(n, n)$$$, consisting of at most $$$n$$$ line segments where each segment has positive integer length and vertical and horizontal segments alternate.Not all paths are equal. You have $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the cost of the $$$i$$$-th segment.Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $$$k$$$ segments ($$$k \le n$$$), then the cost of the path is equal to $$$\sum\limits_{i=1}^{k}{c_i \cdot length_i}$$$ (segments are numbered from $$$1$$$ to $$$k$$$ in the order they are in the path).Find the path of the minimum cost and print its cost.

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^9$$$) — the costs of each segment. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

For each test case, print the minimum possible cost of the path from $$$(0, 0)$$$ to $$$(n, n)$$$ consisting of at most $$$n$$$ alternating segments.

NoteIn the first test case, to reach $$$(2, 2)$$$ you need to make at least one turn, so your path will consist of exactly $$$2$$$ segments: one horizontal of length $$$2$$$ and one vertical of length $$$2$$$. The cost of the path will be equal to $$$2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$$$.In the second test case, one of the optimal paths consists of $$$3$$$ segments: the first segment of length $$$1$$$, the second segment of length $$$3$$$ and the third segment of length $$$2$$$.The cost of the path is $$$1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$$$.In the third test case, one of the optimal paths consists of $$$4$$$ segments: the first segment of length $$$1$$$, the second one — $$$1$$$, the third one — $$$4$$$, the fourth one — $$$4$$$. The cost of the path is $$$1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$$$.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

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

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

		long tot1 = c[0], tot2 = c[1];
		long x = c[0], y = c[1];
		ans[ti] = x*n + y*n;
		foreach (i; 2..n)
		{
			if (i % 2 == 0)
			{
				tot1 += c[i];
				x.chmin(c[i]);
			}
			else
			{
				tot2 += c[i];
				y.chmin(c[i]);
			}
			auto rem1 = n - (i+2) / 2;
			auto rem2 = n - (i+1) / 2;
			ans[ti].chmin(tot1 + tot2 + rem1*x + rem2*y);
		}
	}

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


You are both a shop keeper and a shop assistant at a small nearby shop. You have $$$n$$$ goods, the $$$i$$$-th good costs $$$a_i$$$ coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $$$n$$$ goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $$$n$$$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100)$$$ — the number of goods. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^7$$$), where $$$a_i$$$ is the price of the $$$i$$$-th good.

For each query, print the answer for it — the minimum possible equal price of all $$$n$$$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		int sum=0;
		for (int j=0; j<a; j++)
		{
			int b=0;
			readf(" %d", &b);
			sum=sum+b;
		}
		if (sum%a==0)
		{
			writeln(sum/a);
		}
		else
		{
			writeln(sum/a+1);
		}
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto a = RDA;
		auto s = a.sum;
		ans[i] = s / n + (s % n != 0 ? 1 : 0);
	}

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


You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print "YES" if it is possible to make all elements zero, otherwise print "NO".

NoteIn the first example, you can make all elements equal to zero in $$$3$$$ operations:   Decrease $$$a_1$$$ and $$$a_2$$$,  Decrease $$$a_3$$$ and $$$a_4$$$,  Decrease $$$a_3$$$ and $$$a_4$$$ In the second example, one can show that it is impossible to make all elements equal to zero.

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

const int MAX_N = 100000;
int n;

void main() {
  readln.strip.formattedRead(" %s", n);

  auto a = readln.strip.split.map!(a => parse!long(a));

  long total = a.sum;

  bool ok = total % 2 == 0;

  ok &= a.all!(v => v*2 <= total);

  if (ok) {
    writeln("YES");
  } else {
    writeln("NO");
  }
}

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

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

    if (A.sum % 2 == 1) {
        writeln("NO");
        return;
    }

    if (A.reduce!max > A.sum - A.reduce!max) {
        writeln("NO");
    } else {
        writeln("YES");
    }
}


Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions:  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n).  Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.

A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

module sigod.codeforces.p289C;

import std.array;
import std.stdio;

void main()
{
	int n, k;
	stdin.readf("%s %s", &n, &k);

	stdout.writeln(solve(n, k));
}

string solve(int n, int k)
{
	if (n < k) return "-1";
	if (k == 1) {
		if (n == 1) return "a";
		else return "-1";
	}

	auto result = appender!string();
	result.reserve(n);

	int g = n - max(k - 2, 0);

	foreach (i; 0 .. g / 2) {
		result.put("ab");
	}

	if (g % 2 != 0) result.put('a');

	foreach (i; 99 .. 99 + max(k - 2, 0)) {
		result.put(cast(char) i);
	}

	return result.data();
}

unittest {
	assert(solve(7, 4) == "ababacd");
	assert(solve(4, 7) == "-1");
}

pure int max(int a, int b)
{
	if (a > b) return a;
	else return b;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto s = new char [n];
		if (k > n)
		{
			s = cast (char []) "-1";
		}
		else if (k == 1)
		{
			if (n == 1)
			{
				s = cast (char []) "a";
			}
			else
			{
				s = cast (char []) "-1";
			}
		}
		else
		{
			foreach (i; 0..n)
			{
				s[i] = 'a' + (i & 1);
			}
			foreach (i; 0..k - 2)
			{
				s[$ - 1 - i] = cast (char) ('a' + (k - 1 - i));
			}
		}
		writeln (s);
	}
}


Let's define the cost of a string $$$s$$$ as the number of index pairs $$$i$$$ and $$$j$$$ ($$$1 \le i < j < |s|$$$) such that $$$s_i = s_j$$$ and $$$s_{i+1} = s_{j+1}$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Among all strings with length $$$n$$$ that contain only the first $$$k$$$ characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.

The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 26$$$).

Print the string $$$s$$$ such that it consists of $$$n$$$ characters, each its character is one of the $$$k$$$ first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings — print any of them.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto n = RD!int;
	auto k = RD!int;

	string pat = "a";
	foreach (i; 1..k)
	{
		pat ~= 'a';
		foreach (_; 0..2)
			pat ~= cast(char)(i+'a');
	}
	foreach (i; 1..k)
	{
		foreach (j; i+1..k)
		{
			pat ~= cast(char)(i+'a');
			pat ~= cast(char)(j+'a');
		}
	}
	string ans;
	while (ans.length < n)
	{
		ans ~= pat;
	}
	ans.length = n;

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

void main()
{
	auto n = RD!int;
	auto k = RD!int;

	string pat;
	foreach (i; 0..k)
	{
		foreach (_; 0..2)
			pat ~= cast(char)(i+'a');
	}
	foreach (i; 0..k)
	{
		foreach (j; i+2..k)
		{
			pat ~= cast(char)(i+'a');
			pat ~= cast(char)(j+'a');
		}
	}
	string ans;
	while (ans.length < n)
	{
		ans ~= pat;
	}
	ans.length = n;

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


Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$)— the number of test cases. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, print a single value — the maximum value that Ezzat can achieve. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

immutable multi = true;

void solve(int tc)
{
	auto a = ra!long;
	sort(a);
	auto sp = a.sum;
	double ans = -1e11;
	long ss = 0;
	int pl = cast(int)a.length;
	foreach_reverse(ai; a)
	{
		sp -= ai;
		ss += ai;
		pl--;
		if (pl > 0)
		ans = max(ans, sp/(cast(double)pl) + ss/(cast(double)(a.length - pl)));
	}
	writef!"%.12s\n"(ans);
}

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

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

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

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

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		ans[ti] = cast(double)(a[0..$-1].sum) / (n-1);
		ans[ti] += a[$-1];
	}

	foreach (e; ans)
		writefln(FMT_F, e);
	stdout.flush;
	debug readln;
}

immutable multi = true;

void solve(int tc)
{
	auto a = ra!long;
	sort(a);
	auto sp = a.sum;
	double ans = -1e11;
	long ss = 0;
	int pl = cast(int)a.length;
	foreach_reverse(ai; a)
	{
		sp -= ai;
		ss += ai;
		pl--;
		if (pl > 0)
		ans = max(ans, sp/(cast(double)pl) + ss/(cast(double)(a.length - pl)));
	}
	ans.writeln;
}

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

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

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

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

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


Suppose you are living with two cats: A and B. There are $$$n$$$ napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:   Cat A changes its napping place in order: $$$n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$$$ In other words, at the first hour it's on the spot $$$n$$$ and then goes in decreasing order cyclically;  Cat B changes its napping place in order: $$$1, 2, 3, \dots, n - 1, n, 1, 2, \dots$$$ In other words, at the first hour it's on the spot $$$1$$$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $$$x$$$ then the A takes this place and B moves to the next place in its order (if $$$x < n$$$ then to $$$x + 1$$$, but if $$$x = n$$$ then to $$$1$$$). Cat B follows his order, so it won't return to the skipped spot $$$x$$$ after A frees it, but will move to the spot $$$x + 2$$$ and so on.Calculate, where cat B will be at hour $$$k$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$) — the number of spots and hour $$$k$$$.

For each test case, print one integer — the index of the spot where cat B will sleep at hour $$$k$$$.

NoteIn the first and second test cases $$$n = 2$$$, so:   at the $$$1$$$-st hour, A is on spot $$$2$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$1$$$ and B — to $$$2$$$.  If $$$n = 3$$$ then:   at the $$$1$$$-st hour, A is on spot $$$3$$$ and B is on $$$1$$$;  at the $$$2$$$-nd hour, A moves to spot $$$2$$$; B'd like to move from $$$1$$$ to $$$2$$$, but this spot is occupied, so it moves to $$$3$$$;  at the $$$3$$$-rd hour, A moves to spot $$$1$$$; B also would like to move from $$$3$$$ to $$$1$$$, but this spot is occupied, so it moves to $$$2$$$. In the sixth test case:   A's spots at each hour are $$$[5, 4, 3, 2, 1]$$$;  B's spots at each hour are $$$[1, 2, 4, 5, 2]$$$.

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int n, k; get(n, k);
        if (n % 2 == 0) {
            writeln((k - 1) % n + 1);
        } else if (k <= n) {
            writeln(k == n ? 2 : k + (k >= (n+1)/2 ? 1 : 0));
        } else {
            --k;
            auto p = (k / n) % (n / 2) * 2;
            k %= n;
            auto d = (n - p - 1) / 2;
            writeln((p + k + (k >= d + n/2 ? 2 : k >= d ? 1 : 0)) % n + 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, k;
		readf !(" %s %s") (n, k);
		writeln ((k - 1 + ((n & 1) ? (k - 1) / (n / 2) : 0)) % n + 1);
	}
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

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

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

		if (n % 2)
		{
			auto loop = n / 2;
			auto x = (k-1) / loop;
			ans[ti] = (k-1+x) % n + 1;
		}
		else
		{
			ans[ti] = (k-1) % n + 1;
		}
	}

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

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int n, k; get(n, k);
        if (n % 2 == 0) {
            writeln((k - 1) % n + 1);
        } else if (k <= n) {
            writeln(k == n ? 2 : k + (k >= (n+1)/2 ? 1 : 0));
        } else {
            --k;
            auto p = (k / n) % (n / 2) * 2;
            k %= n;
            auto d = (n - p - 1) / 2;
            writeln((p + k + (k >= n-1 ? 2 : k >= d ? 1 : 0)) % n + 1);
        }
    }
}

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int n, k; get(n, k);
        if (n % 2 == 0) {
            writeln((k - 1) % n + 1);
        } else if (k <= n) {
            writeln(k == n ? 2 : k + (k >= (n+1)/2 ? 1 : 0));
        } else {
            --k;
            auto p = (k / n) % (n / 2) * 2;
            k %= n;
            auto d = (n - p) / 2;
            writeln((p + k + (k >= n-1 ? 2 : k >= d ? 1 : 0)) % n + 1);
        }
    }
}


Suppose $$$a_1, a_2, \dots, a_n$$$ is a sorted integer sequence of length $$$n$$$ such that $$$a_1 \leq a_2 \leq \dots \leq a_n$$$. For every $$$1 \leq i \leq n$$$, the prefix sum $$$s_i$$$ of the first $$$i$$$ terms $$$a_1, a_2, \dots, a_i$$$ is defined by $$$$$$ s_i = \sum_{k=1}^i a_k = a_1 + a_2 + \dots + a_i. $$$$$$Now you are given the last $$$k$$$ terms of the prefix sums, which are $$$s_{n-k+1}, \dots, s_{n-1}, s_{n}$$$. Your task is to determine whether this is possible. Formally, given $$$k$$$ integers $$$s_{n-k+1}, \dots, s_{n-1}, s_{n}$$$, the task is to check whether there is a sequence $$$a_1, a_2, \dots, a_n$$$ such that   $$$a_1 \leq a_2 \leq \dots \leq a_n$$$, and  $$$s_i = a_1 + a_2 + \dots + a_i$$$ for all $$$n-k+1 \leq i \leq n$$$.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains two integers $$$n$$$ ($$$1 \leq n \leq 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq n$$$), indicating the length of the sequence $$$a$$$ and the number of terms of prefix sums, respectively. The second line of each test case contains $$$k$$$ integers $$$s_{n-k+1}, \dots, s_{n-1}, s_{n}$$$ ($$$-10^9 \leq s_i \leq 10^9$$$ for every $$$n-k+1 \leq i \leq n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output "YES" (without quotes) if it is possible and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we have the only sequence $$$a = [1, 1, 1, 1, 1]$$$.In the second test case, we can choose, for example, $$$a = [-3, -2, -1, 0, 1, 2, 3]$$$.In the third test case, the prefix sums define the only sequence $$$a = [2, 1, 1]$$$, but it is not sorted. In the fourth test case, it can be shown that there is no sequence with the given prefix sums.

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

bool solve (int n, int k, int [] s)
{
	if (k == 1)
	{
		return true;
	}
	if (k == n)
	{
		s = [0] ~ s;
		k += 1;
	}
	auto a = new long [n];
	foreach (i; 1..k)
	{
		a[n - i] = s[k - i] - s[k - i - 1];
	}
	foreach (i; k..n + 1)
	{
		a[n - i] = a[n - i + 1];
	}
	auto total = sum (a);
	debug {writeln (a, " ", total);}
	if (k == n && total != s.back)
	{
		return false;
	}
	return (total >= s.back && isSorted (a));
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.splitter.map !(to !(int)).array;
		writeln (solve (n, k, s) ? "YES" : "NO");
	}
}

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

int N, K;
long[] S;

bool solve() {
  if (K == 1) {
    return true;
  }
  auto as = new long[N + 1];
  foreach_reverse (i; N - K + 1 .. N) {
    as[i] = S[i + 1] - S[i];
  }
  foreach_reverse (i; 0 .. N - K + 1) {
    as[i] = as[i + 1];
  }
  debug {
    writeln("K = ", K);
    writeln("S = ", S);
    writeln("as = ", as);
  }
  foreach (i; 0 .. N - 1) {
    if (!(as[i] <= as[i + 1])) {
      return false;
    }
  }
  const S0 = S[N] - as.sum;
  return (S0 <= 0);
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        K = readInt;
        S = new long[N + 1];
        foreach (i; N - K + 1 .. N + 1) {
          S[i] = readLong;
        }

        const ans = solve;
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

bool solve (int n, int k, int [] s)
{
	if (k == 1)
	{
		return true;
	}
	auto a = new long [n];
	foreach (i; 1..k)
	{
		a[n - i] = s[k - i] - s[k - i - 1];
	}
	foreach (i; k..n + 1)
	{
		a[n - i] = a[n - i + 1];
	}
	auto total = sum (a);
	debug {writeln (a, " ", total);}
	if (k == n && total != s.back)
	{
		return false;
	}
	return (total >= s.back && isSorted (a));
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.splitter.map !(to !(int)).array;
		writeln (solve (n, k, s) ? "YES" : "NO");
	}
}

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

int N, K;
long[] S;

bool solve() {
  if (K == 1) {
    return true;
  }
  auto as = new long[N + 1];
  foreach_reverse (i; N - K + 1 .. N) {
    as[i] = S[i + 1] - S[i];
  }
  foreach_reverse (i; 0 .. N - K + 1) {
    as[i] = as[i + 1];
  }
  debug {
    writeln("K = ", K);
    writeln("S = ", S);
    writeln("as = ", as);
  }
  const S0 = S[N] - as.sum;
  return (S0 <= 0);
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        K = readInt;
        S = new long[N + 1];
        foreach (i; N - K + 1 .. N + 1) {
          S[i] = readLong;
        }

        const ans = solve;
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}


You are given a string $$$s[1 \dots n]$$$ consisting of lowercase Latin letters. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$.The string $$$s[1 \dots n]$$$ is called $$$c$$$-good if at least one of the following three conditions is satisfied:  The length of $$$s$$$ is $$$1$$$, and it consists of the character $$$c$$$ (i.e. $$$s_1=c$$$); The length of $$$s$$$ is greater than $$$1$$$, the first half of the string consists of only the character $$$c$$$ (i.e. $$$s_1=s_2=\dots=s_{\frac{n}{2}}=c$$$) and the second half of the string (i.e. the string $$$s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$$$) is a $$$(c+1)$$$-good string;  The length of $$$s$$$ is greater than $$$1$$$, the second half of the string consists of only the character $$$c$$$ (i.e. $$$s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$$$) and the first half of the string (i.e. the string $$$s_1s_2 \dots s_{\frac{n}{2}}$$$) is a $$$(c+1)$$$-good string. For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.In one move, you can choose one index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$s_i$$$ with any lowercase Latin letter (any character from 'a' to 'z').Your task is to find the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string for $$$c=$$$ 'a'). It is guaranteed that the answer always exists.You have to answer $$$t$$$ independent test cases.Another example of an 'a'-good string is as follows. Consider the string $$$s = $$$"cdbbaaaa". It is an 'a'-good string, because:  the second half of the string ("aaaa") consists of only the character 'a';  the first half of the string ("cdbb") is 'b'-good string, because:   the second half of the string ("bb") consists of only the character 'b';  the first half of the string ("cd") is 'c'-good string, because:   the first half of the string ("c") consists of only the character 'c';  the second half of the string ("d") is 'd'-good string.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 131~072$$$) — the length of $$$s$$$. It is guaranteed that $$$n = 2^k$$$ for some integer $$$k \ge 0$$$. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain an 'a'-good string from $$$s$$$ (i.e. $$$c$$$-good string with $$$c =$$$ 'a'). It is guaranteed that the answer exists.

6
8
bbdcaaaa
8
asdfghjk
8
ceaaaabb
8
bbaaddcc
1
z
2
ac

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto k = bsr (n);
		auto s = readln.strip;
		auto f = new int [n];
		foreach (i; 0..n)
		{
			f[i] = (s[i] != k + 'a');
		}
		foreach (j; 0..k)
		{
			auto len = 1 << j;
			auto c = cast (char) (k + 'a' - j - 1);
			for (int i = 0; i < n; i += len * 2)
			{
				f[i] = min (len - s[i..i + len].count (c) +
				    f[i + len],
				    len - s[i + len..i + len * 2].count (c) +
				    f[i]).to !(int);
			}
		}
		writeln (f[0]);
	}
}


The new generation external memory contains an array of integers $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions:   You may select arbitrary indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) as the boundaries of the segment.  Then you replace the segment $$$a[l \ldots r]$$$ with it's cyclic shift to the left by an arbitrary offset $$$d$$$. The concept of a cyclic shift can be also explained by following relations: the sequence $$$[1, 4, 1, 3]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$1$$$ and the sequence $$$[4, 1, 3, 1]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$2$$$. For example, if $$$a = [1, \color{blue}{3, 2, 8}, 5]$$$, then choosing $$$l = 2$$$, $$$r = 4$$$ and $$$d = 2$$$ yields a segment $$$a[2 \ldots 4] = [3, 2, 8]$$$. This segment is then shifted by the offset $$$d = 2$$$ to the left, and you get a segment $$$[8, 3, 2]$$$ which then takes the place of of the original elements of the segment. In the end you get $$$a = [1, \color{blue}{8, 3, 2}, 5]$$$.Sort the given array $$$a$$$ using no more than $$$n$$$ cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires $$$n$$$ or less cyclic shifts will be accepted.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain the descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$2 \leq n \leq 50$$$) — the length of the array. The second line consists of space-separated elements of the array $$$a_i$$$ ($$$-10^9 \leq a_i \leq 10^9$$$). Elements of array $$$a$$$ may repeat and don't have to be unique.

Print $$$t$$$ answers to all input test cases.  The first line of the answer of each test case should contain an integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of actions to sort the array. The next $$$k$$$ lines should contain descriptions of the actions formatted as "$$$l$$$ $$$r$$$ $$$d$$$" (without quotes) where $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) are the boundaries of the segment being shifted, while $$$d$$$ ($$$1 \le d \le r - l$$$) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset $$$d$$$ to the to the left. Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed $$$n$$$ will be accepted. If the given array $$$a$$$ is already sorted, one of the possible answers is $$$k = 0$$$ and an empty sequence of cyclic shifts. If there are several possible answers, you may print any of them.

NoteExplanation of the fourth data set in the example:   The segment $$$a[2 \ldots 4]$$$ is selected and is shifted to the left by $$$2$$$: $$$[2, \color{blue}{5, 1, 4}, 3] \longrightarrow [2, \color{blue}{4, 5, 1}, 3]$$$  The segment $$$a[1 \ldots 5]$$$ is then selected and is shifted to the left by $$$3$$$: $$$[\color{blue}{2, 4, 5, 1, 3}] \longrightarrow [\color{blue}{1, 3, 2, 4, 5}]$$$  After that the segment $$$a[1 \ldots 2]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\color{blue}{1, 3}, 2, 4, 5] \longrightarrow [\color{blue}{3, 1}, 2, 4, 5]$$$  And in the end the segment $$$a[1 \ldots 3]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\color{blue}{3, 1, 2}, 4, 5] \longrightarrow [\color{blue}{1, 2, 3}, 4, 5]$$$

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	auto shifts = new int[3][](0);
	int[] doShift(int l, int r, int d)
	{
		if (l == r) return a[l..l+1].dup;
		shifts ~= [l+1, r+1, d];
		auto len = r - l + 1;
		auto shifted = new int[](r - l + 1);
		foreach(i; 0 .. len)
		{
			shifted[i] = a[l+(i+d)%len];
		}
		return shifted;
	}
	void doSort(int f)
	{
		auto mnB = a[f .. n].fold!min;
		int mnBI = -1;
		foreach(i; f .. n)
		{
			if (a[i] == mnB) {mnBI = cast(int)i; break;}
		}
		assert(mnBI != -1);
		auto shifted = doShift(f, mnBI, mnBI - f);
		a[f .. mnBI + 1][] = shifted;
	}
	foreach(i; 0 .. n)
		doSort(i);
	debug writeln(a);
	shifts.length.writeln;
	foreach(shift; shifts)
	{
		writeln(shift[0], " ", shift[1], " ", shift[2]);
	}
	writeln;
}

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

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

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

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

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

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	auto shifts = new int[3][](0);
	int[] doShift(int l, int r, int d)
	{
		shifts ~= [l+1, r+1, d];
		auto len = r - l + 1;
		auto shifted = new int[](r - l + 1);
		foreach(i; 0 .. len)
		{
			shifted[i] = a[l+(i+d)%len];
		}
		return shifted;
	}
	void doSort(int f)
	{
		auto mnB = a[f .. n].fold!min;
		int mnBI = -1;
		foreach(i; f .. n)
		{
			if (a[i] == mnB) {mnBI = cast(int)i; break;}
		}
		assert(mnBI != -1);
		auto shifted = doShift(f, mnBI, mnBI - f);
		a[f .. mnBI + 1][] = shifted;
	}
	foreach(i; 0 .. n)
		doSort(i);
	debug writeln(a);
	shifts.length.writeln;
	foreach(shift; shifts)
	{
		writeln(shift[0], " ", shift[1], " ", shift[2]);
	}
	writeln;
}

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

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

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

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

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


Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:  a1 = p, where p is some integer;  ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.Sequence s1,  s2,  ...,  sk is a subsequence of sequence b1,  b2,  ...,  bn, if there is such increasing sequence of indexes i1, i2, ..., ik (1  ≤  i1  <  i2  < ...   <  ik  ≤  n), that bij  =  sj. In other words, sequence s can be obtained from b by crossing out some elements.

The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106).

Print a single integer — the length of the required longest subsequence.

NoteIn the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10.

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

void solve(int[] b)
{
    auto m = reduce!(max)(b);
    auto pos = new int[m + 1];
    fill(pos, -1);
    int[][] arr;
    auto cnt = 0;
    foreach (int i, v; b)
    {
        if (pos[v] == -1)
        {
            pos[v] = cnt;
            ++ cnt;
            int[] a;
            arr ~= a;
        }
        arr[pos[v]] ~= i;
    }
    auto ans = 0;
    for (int i = 0; i < cnt; ++ i)
    {
        ans = max(ans, cast(int)arr[i].length);
        for (int j = i + 1; j < cnt; ++ j)
        {
            if (arr[i].length + arr[j].length <= ans)
            {
                continue;
            }
            auto pi = 0, pj = 0;
            auto count = 2;
            auto prev = arr[i][pi] < arr[j][pj] ? 0 : 1;
            while (pi < arr[i].length && pj < arr[j].length)
            {
                if (count + arr[i].length - pi + 1 + arr[j].length - pj + 1 <= ans)
                {
                    break;
                }
                if (prev == 0)
                {
                    ++ pi;
                    if (pi < arr[i].length && arr[i][pi] > arr[j][pj])
                    {
                        prev = 1;
                        ++ count;
                    }
                }
                else
                {
                    ++ pj;
                    if (pj < arr[j].length && arr[j][pj] > arr[i][pi])
                    {
                        prev = 0;
                        ++ count;
                    }
                }
            }
            ans = max(ans, count);
        }
    }
    writeln(ans);
}

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


As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.

The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.

Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.

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

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

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

    int [int] cnt;

    readln.chomp.split.map!(to!int).each!(x => cnt[x] += 1);

    debug { cnt.writeln; }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    foreach (x; cnt.byPair) {
        rbt.insert(tuple(x[1], x[0]));
    }

    debug { rbt.writeln; }

    int[3][] ans;
    while (rbt.length >= 3) {
        int[] ids;
        int[] vals;
        foreach (i; 0 .. 3) {
            auto p = rbt.back;
            vals ~= p[0];
            ids ~= p[1];
            rbt.removeBack();
        }

        int[3] sorted = ids.dup.sort().retro().array;
        ans ~= sorted;

        foreach (i; 0 .. 3) {
            int left = vals[i] - 1;
            if (left > 0) {
                rbt.insert(tuple(left, ids[i]));
            }
        }
    }

    ans.length.writeln;
    foreach (r; ans) {
        r.writefln!"%(%s %)";
    }
}

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

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

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

    int [int] cnt;

    readln.chomp.split.map!(to!int).each!(x => cnt[x] += 1);

    debug { cnt.writeln; }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    foreach (x; cnt.byPair) {
        rbt.insert(tuple(x[1], x[0]));
    }

    debug { rbt.writeln; }

    int[3][] ans;
    while (rbt.length >= 3) {
        int[3] ids;
        int[3] vals;
        foreach (i; 0 .. 3) {
            auto p = rbt.back;
            vals[i] = p[0];
            ids[i] = p[1];
            rbt.removeBack();
        }

        foreach (_; 0 .. vals.back) {
            int[3] sorted = ids.dup.sort().retro().array;
            ans ~= sorted;
        }

        foreach (i; 0 .. 2) {
            int left = vals[i] - vals.back;
            if (left > 0) {
                rbt.insert(tuple(left, ids[i]));
            }
        }
    }

    ans.length.writeln;
    foreach (r; ans) {
        r.writefln!"%(%s %)";
    }
}

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

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

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

    int [int] cnt;

    readln.chomp.split.map!(to!int).each!(x => cnt[x] += 1);

    debug { cnt.writeln; }

    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));

    foreach (x; cnt.byPair) {
        rbt.insert(tuple(x[1], x[0]));
    }

    debug { rbt.writeln; }

    int[3][] ans;
    while (rbt.length >= 3) {
        int[3] ids;
        int[3] vals;
        foreach (i; 0 .. 3) {
            auto p = rbt.back;
            vals[i] = p[0];
            ids[i] = p[1];
            rbt.removeBack();
        }

        foreach (_; 0 .. vals.back) {
            ans ~= ids;
        }

        foreach (i; 0 .. 2) {
            int left = vals[i] - vals.back;
            if (left > 0) {
                rbt.insert(tuple(left, ids[i]));
            }
        }
    }

    ans.length.writeln;
    foreach (r; ans) {
        r.writefln!"%(%s %)";
    }
}