As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.Each warrior is represented by his personality — an integer number pi. Each commander has two characteristics — his personality pj and leadership lj (both are integer numbers). Warrior i respects commander j only if  ( is the bitwise excluding OR of x and y).Initially Vova's army is empty. There are three different types of events that can happen with the army:  1 pi — one warrior with personality pi joins Vova's army;  2 pi — one warrior with personality pi leaves Vova's army;  3 pi li — Vova tries to hire a commander with personality pi and leadership li. For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.

The first line contains one integer q (1 ≤ q ≤ 100000) — the number of events. Then q lines follow. Each line describes the event:   1 pi (1 ≤ pi ≤ 108) — one warrior with personality pi joins Vova's army;  2 pi (1 ≤ pi ≤ 108) — one warrior with personality pi leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment);  3 pi li (1 ≤ pi, li ≤ 108) — Vova tries to hire a commander with personality pi and leadership li. There is at least one event of this type.

For each event of the third type print one integer — the number of warriors who respect the commander Vova tries to hire in the event.

NoteIn the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him (, and 2 < 3, but , and 5 ≥ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.

module main;
__gshared:
import std.bigint, std.container, std.array, std.algorithm, std.conv,
	std.parallelism, std.functional, std.math, std.string, std.range,
	std.complex, std.bitmanip, std.typecons, std.regex, std.random, std.uni,
	std.traits, std.stdio, std.variant, core.bitop, std.meta, std.datetime,
	core.stdc.stdio : freopen;
import std.numeric : fft, Fft, gcd, inverseFft;

alias big = BigInt;
alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
public const int mod = 10 ^^ 9 + 7;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///big greatest common divizor
		big gcd(big a, big b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///integer size
		int sz(T)(T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (!(a[m] < g))
					r = m;
				else
					l = m;
			}
			return (!(a[l] < g)) ? l : r;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return binf(a, g) != a.length;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ')
			if (isInputRange!X && !isInputRange!(ElementEncodingType!X))
	{
		foreach (const ref i; a)
			write(i, ch);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementEncodingType!X))
	{
		foreach (ref const i; a)
		{
			foreach (ref const j; i)
				write(j, ' ');
			writeln;
		}
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		return s == ptrs.length;
	}
	///readln without format
	bool read(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		readln;
		return s == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//compilation ldc2 -d-debug -d-version=home main.d
//------------------------------------------program beginning--------------------------
class bor
{
	int cnt;
	bor l, r;
	this()
	{
		cnt = 0;
		l = r = null;
	}
};
void add(bor v, int lev, int x)
{
	v.cnt++;
	if (lev < 0)
		return;
	if (x & (1 << lev))
	{
		if (!v.r)
			v.r = new bor;
		add(v.r, lev - 1, x);
	}
	else
	{
		if (!v.l)
			v.l = new bor;
		add(v.l, lev - 1, x);
	}
}

void dec(bor v, int lev, int x)
{
	v.cnt--;
	if (lev < 0)
		return;
	if (x & (1 << lev))
	{
		dec(v.r, lev - 1, x);
	}
	else
	{
		dec(v.l, lev - 1, x);
	}
}

int cnt(bor v)
{
	return v ? v.cnt : 0;
}

int cel(bor v, int lev, int x, int y)
{
	if (!v || lev < 0)
		return 0;
	if ((y & (1 << lev)) < (x & (1 << lev)))
		return cel(v.r, lev - 1, x, y);
	if ((y & (1 << lev)) > (x & (1 << lev)))
		return cnt(v.l) + cel(v.r, lev - 1, x, y);
	if ((y & (1 << lev)) + (x & (1 << lev)))
		return cnt(v.r) + cel(v.l, lev - 1, x, y);
	else
		return cel(v.l, lev - 1, x, y);
}

bor root = new bor;
void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//assert(freopen("output.txt", "w", core.stdc.stdio.stdout));
		StopWatch sw;
		sw.start;
		scope (exit)
		{
			sw.stop;
			stderr.writefln("\nTime: %d ms", sw.peek.msecs);
		}
	}
	int q;
	loop: while (read(q))
	{
		foreach (ii; 0 .. q)
		{
			int t;
			input(t);
			switch (t)
			{
			case 1:
				int p;
				read(p);
				add(root, 29, p);
				break;
			case 2:
				int p;
				read(p);
				dec(root, 29, p);
				break;
			case 3:
				int p, ll;
				read(p, ll);
				writeln(cel(root, 29, p, ll));
				break;
			default:
				break;
			}

		}
	}

}

module main;
__gshared:
import std.bigint, std.container, std.array, std.algorithm, std.conv,
	std.parallelism, std.functional, std.math, std.string, std.range,
	std.complex, std.bitmanip, std.typecons, std.regex, std.random, std.uni,
	std.traits, std.stdio, std.variant, core.bitop, std.meta, std.datetime,
	core.stdc.stdio : freopen;
import std.numeric : fft, Fft, gcd, inverseFft;

alias big = BigInt;
alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
public const int mod = 10 ^^ 9 + 7;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///big greatest common divizor
		big gcd(big a, big b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///integer size
		int sz(T)(T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (!(a[m] < g))
					r = m;
				else
					l = m;
			}
			return (!(a[l] < g)) ? l : r;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return binf(a, g) != a.length;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ')
			if (isInputRange!X && !isInputRange!(ElementEncodingType!X))
	{
		foreach (const ref i; a)
			write(i, ch);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementEncodingType!X))
	{
		foreach (ref const i; a)
		{
			foreach (ref const j; i)
				write(j, ' ');
			writeln;
		}
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		return s == ptrs.length;
	}
	///readln without format
	bool read(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		readln;
		return s == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//compilation ldc2 -d-debug -d-version=home main.d
//------------------------------------------program beginning--------------------------
class bor
{
	int cnt;
	bor l, r;
	this()
	{
		cnt = 0;
		l = r = null;
	}
};
void add(bor v, int lev, int x)
{
	v.cnt++;
	if (lev < 0)
		return;
	if (x & (1 << lev))
	{
		if (!v.r)
			v.r = new bor;
		add(v.r, lev - 1, x);
	}
	else
	{
		if (!v.l)
			v.l = new bor;
		add(v.l, lev - 1, x);
	}
}

void dec(bor v, int lev, int x)
{
	if(!v)return;
	v.cnt--;
	if (lev < 0)
		return;
	if (x & (1 << lev))
	{
		dec(v.r, lev - 1, x);
	}
	else
	{
		dec(v.l, lev - 1, x);
	}
}

int cnt(bor v)
{
	return v ? v.cnt : 0;
}

int cel(bor v, int lev, int x, int y)
{
	if (!v || lev < 0)
		return 0;
	if ((y & (1 << lev)) > (x & (1 << lev)))
		return cnt(v.r);
	if ((y & (1 << lev)) < (x & (1 << lev)))
		return cnt(v.l);
	return cel(v.l, lev - 1, x, y) + cel(v.r, lev - 1, x, y);
}

bor root = new bor;
void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//assert(freopen("output.txt", "w", core.stdc.stdio.stdout));
		StopWatch sw;
		sw.start;
		scope (exit)
		{
			sw.stop;
			stderr.writefln("\nTime: %d ms", sw.peek.msecs);
		}
	}
	int q;
	loop: while (read(q))
	{
		foreach (ii; 0 .. q)
		{
			int t;
			input(t);
			switch (t)
			{
			case 1:
				int p;
				read(p);
				add(root, 29, p);
				break;
			case 2:
				int p;
				read(p);
				dec(root, 29, p);
			case 3:
				int p, ll;
				read(p, ll);
				writeln(cel(root, 29, p, ll));
			default:
				break;
			}

		}
	}

}


Toad Pimple has an array of integers $$$a_1, a_2, \ldots, a_n$$$.We say that $$$y$$$ is reachable from $$$x$$$ if $$$x<y$$$ and there exists an integer array $$$p$$$ such that $$$x = p_1 < p_2 < \ldots < p_k=y$$$, and $$$a_{p_i}\, \&\, a_{p_{i+1}} > 0$$$ for all integers $$$i$$$ such that $$$1 \leq i < k$$$.Here $$$\&$$$ denotes the bitwise AND operation.You are given $$$q$$$ pairs of indices, check reachability for each of them.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 300\,000$$$, $$$1 \leq q \leq 300\,000$$$) — the number of integers in the array and the number of queries you need to answer. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 300\,000$$$) — the given array. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th of them contains two space-separated integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i < y_i \leq n$$$). You need to check if $$$y_i$$$ is reachable from $$$x_i$$$.

Output $$$q$$$ lines. In the $$$i$$$-th of them print "Shi" if $$$y_i$$$ is reachable from $$$x_i$$$, otherwise, print "Fou".

NoteIn the first example, $$$a_3 = 0$$$. You can't reach it, because AND with it is always zero. $$$a_2\, \&\, a_4 > 0$$$, so $$$4$$$ is reachable from $$$2$$$, and to go from $$$1$$$ to $$$4$$$ you can use $$$p = [1, 2, 4]$$$.

/+ dub.sdl:
    name "C"
    dependency "dunkelheit" version="1.0.1"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner, dkh.algorithm;

immutable L = 19;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n, q;
    sc.read(n, q);
    int[] a;
    sc.read(a);

    int[L] bk; bk[] = n;
    int[L][] dp = new int[L][n];
    foreach_reverse (i; 0..n) {
        int d = a[i];
        dp[i][] = n;
        foreach (j; 0..L) {
            if (!(d & (1 << j))) continue;
            dp[i][j] = i;

            int bi = bk[j];
            if (bi != n) {
                foreach (k; 0..L) {
                    dp[i][k] = min(dp[i][k], dp[bi][k]);
                }
            }

            bk[j] = i;
        }
    }
    debug writeln(dp);

    foreach (ph; 0..q) {
        int u, v;
        sc.read(u, v); u--; v--;

        bool ok = false;
        foreach (i; 0..L) {
            if (!(a[v] & (1 << i))) continue;
            if (dp[u][i] <= v) {
                ok = true;
                break;
            }
        }

        if (ok) writeln("Shi");
        else writeln("Fou");
    }
    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

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

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

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

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

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/algorithm.d */
// module dkh.algorithm;

import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = l + (r-l) / 2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

import std.range.primitives;

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "minimum: range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "maximum: range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() const {
        return now.empty;
    }
    @property auto front() const {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

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

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

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


On a plane are n points (xi, yi) with integer coordinates between 0 and 106. The distance between the two points with numbers a and b is said to be the following value:  (the distance calculated by such formula is called Manhattan distance).We call a hamiltonian path to be some permutation pi of numbers from 1 to n. We say that the length of this path is value .Find some hamiltonian path with a length of no more than 25 × 108. Note that you do not have to minimize the path length.

The first line contains integer n (1 ≤ n ≤ 106). The i + 1-th line contains the coordinates of the i-th point: xi and yi (0 ≤ xi, yi ≤ 106). It is guaranteed that no two points coincide.

Print the permutation of numbers pi from 1 to n — the sought Hamiltonian path. The permutation must meet the inequality . If there are multiple possible answers, print any of them. It is guaranteed that the answer exists.

NoteIn the sample test the total distance is:(|5 - 3| + |0 - 4|) + (|3 - 0| + |4 - 7|) + (|0 - 8| + |7 - 10|) + (|8 - 9| + |10 - 12|) = 2 + 4 + 3 + 3 + 8 + 3 + 1 + 2 = 26

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

immutable int ONE_C = 1001;
immutable int TWO_C = 1001;
immutable int MAX_C = ONE_C * TWO_C;

alias Point = Tuple !(int, q{x}, int, q{y});

pure int dist (ref Point a, ref Point b)
{
	return abs (a.x - b.x) + abs (a.y - b.y);
}

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = new Point [n];
		foreach (i, ref p; a)
		{
			auto t = readln.split.map !(to !(int));
			p.x = t.front;
			t.popFront ();
			p.y = t.front;
		}

		auto d = new int [MAX_C];
		foreach (i, ref p; a)
		{
			d[p.x + 1]++;
		}
		foreach (i; 1..MAX_C)
		{
			d[i] += d[i - 1];
		}

		auto v = new int [n];
		foreach (i, ref p; a)
		{
			v[d[p.x]] = i;
			d[p.x]++;
		}

		auto b = new int [] [ONE_C];
		foreach (i; v)
		{
			b[a[i].y / TWO_C] ~= i;
		}

		int [] ans;
		ans.reserve (n);
		auto cur = Point (0, 0);
		foreach (ref c; b)
		{
			if (c.empty)
			{
				continue;
			}
			if (dist (cur, a[c.front]) > dist (cur, a[c.back]))
			{
				reverse (c);
			}
			foreach (i; c)
			{
				ans ~= i + 1;
			}
			cur = a[c.back];
		}

		ans.map !(text).join (" ").writeln;

		debug
		{
			auto q = Point (0, 0);
			long res = 0;
			foreach (i; ans)
			{
				res += dist (a[i - 1], q);
				q = a[i - 1];
//				stderr.writeln (q);
			}
			stderr.writeln (res);
		}
	}
}

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

immutable int ONE_C = 1001;
immutable int TWO_C = 1001;
immutable int MAX_C = ONE_C * TWO_C;

alias Point = Tuple !(int, q{x}, int, q{y});

pure int dist (ref Point a, ref Point b)
{
	return abs (a.x - b.x) + abs (a.y - b.y);
}

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = new Point [n];
		foreach (i, ref p; a)
		{
			auto t = readln.split.map !(to !(int));
			p.x = t.front;
			t.popFront ();
			p.y = t.front;
		}

		auto d = new int [MAX_C];
		foreach (i, ref p; a)
		{
			d[p.x + 1]++;
		}
		foreach (i; 1..MAX_C)
		{
			d[i] += d[i - 1];
		}

		auto v = new int [MAX_C];
		foreach (i, ref p; a)
		{
			v[d[p.x]] = i;
			d[p.x]++;
		}

		auto b = new int [] [ONE_C];
		foreach (i; v)
		{
			b[a[i].y / TWO_C] ~= i;
		}

		int [] ans;
		ans.reserve (n);
		auto cur = Point (0, 0);
		foreach (ref c; b)
		{
			if (c.empty)
			{
				continue;
			}
			if (dist (cur, a[c.front]) > dist (cur, a[c.back]))
			{
				reverse (c);
			}
			foreach (i; c)
			{
				ans ~= i + 1;
			}
			cur = a[c.back];
		}

		ans.map !(text).join (" ").writeln;

		debug
		{
			auto q = Point (0, 0);
			long res = 0;
			foreach (i; ans)
			{
				res += dist (a[i - 1], q);
				q = a[i - 1];
//				stderr.writeln (q);
			}
			stderr.writeln (res);
		}
	}
}


Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.This "personal treasure" is a multiset $$$S$$$ of $$$m$$$ "01-strings".A "01-string" is a string that contains $$$n$$$ characters "0" and "1". For example, if $$$n=4$$$, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are $$$5$$$ characters, not $$$4$$$) and "zero" (unallowed characters) are not.Note that the multiset $$$S$$$ can contain equal elements.Frequently, Mr. Kasoura will provide a "01-string" $$$t$$$ and ask Childan how many strings $$$s$$$ are in the multiset $$$S$$$ such that the "Wu" value of the pair $$$(s, t)$$$ is not greater than $$$k$$$. Mrs. Kasoura and Mr. Kasoura think that if $$$s_i = t_i$$$ ($$$1\leq i\leq n$$$) then the "Wu" value of the character pair equals to $$$w_i$$$, otherwise $$$0$$$. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to $$$n$$$.For example, if $$$w=[4, 5, 3, 6]$$$, "Wu" of ("1001", "1100") is $$$7$$$ because these strings have equal characters only on the first and third positions, so $$$w_1+w_3=4+3=7$$$.You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset $$$S$$$ such that the "Wu" value of the pair is not greater than $$$k$$$.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$q$$$ ($$$1\leq n\leq 12$$$, $$$1\leq q, m\leq 5\cdot 10^5$$$) — the length of the "01-strings", the size of the multiset $$$S$$$, and the number of queries. The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 100$$$) — the value of the $$$i$$$-th caracter. Each of the next $$$m$$$ lines contains the "01-string" $$$s$$$ of length $$$n$$$ — the string in the multiset $$$S$$$. Each of the next $$$q$$$ lines contains the "01-string" $$$t$$$ of length $$$n$$$ and integer $$$k$$$ ($$$0\leq k\leq 100$$$) — the query.

For each query, print the answer for this query.

NoteIn the first example, we can get:"Wu" of ("01", "00") is $$$40$$$."Wu" of ("10", "00") is $$$20$$$."Wu" of ("11", "00") is $$$0$$$."Wu" of ("01", "11") is $$$20$$$."Wu" of ("10", "11") is $$$40$$$."Wu" of ("11", "11") is $$$60$$$.In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than $$$20$$$.In the second query, all strings satisfy the condition.In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is $$$2$$$, not $$$1$$$.In the fourth query, since $$$k$$$ was increased, pair ("10", "11") satisfies the condition too.In the fifth query, since $$$k$$$ was increased, pair ("11", "11") satisfies the condition too.

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

void main()
{
    immutable int mxcost = 101;

    int n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

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

    auto cnt = new int[] (1 << n);
    foreach (_; 0 .. m) {
        auto x = readln.chomp.to!(int)(2);
        ++cnt[x];
    }

    auto v = new int[][] (1 << n, mxcost+1);
    foreach (e; 0 .. 1 << n) {
        foreach (o; e .. 1 << n) {
            auto xr = e ^ o;
            auto cost = 0;
            foreach (b; 0 .. n) {
                if ((xr & (1 << b)) == 0) cost += w[b];
            }
            cost = min(cost, mxcost);

            v[e][cost] += cnt[o];
            if (e != o) v[o][cost] += cnt[e];
        }
    }

    foreach (ref rw; v) {
        rw = rw.cumulativeFold!((a, b) => a + b).array;
    }

    debug { v.each!(arr => arr.take(20).writeln); }

    while (q--) {
        string t; int k;
        readf("%s %s", &t, &k);
        readln;
        auto x = t.to!(int)(2);
        v[x][k].writeln;
    }

}

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

void main()
{
    immutable int mxcost = 101;

    int n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

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

    auto cnt = new int[] (1 << n);
    foreach (_; 0 .. m) {
        auto x = readln.chomp.to!(int)(2);
        ++cnt[x];
    }

    auto v = new int[][] (1 << n, mxcost+1);
    foreach (e; 0 .. 1 << n) {
        foreach (o; e .. 1 << n) {
            auto xr = e ^ o;
            auto cost = 0;
            foreach (b; 0 .. n) {
                if ((xr & (1 << b)) == 0) cost += w[b];
            }
            cost = min(cost, mxcost);

            v[e][cost] += cnt[o];
            if (e != o) v[o][cost] += cnt[e];
        }
    }

    foreach (e; 0 .. 1 << n) {
        foreach (i; 0 .. mxcost) v[e][i+1] += v[e][i];

    }

    debug { v.each!(arr => arr.take(20).writeln); }

    while (q--) {
        auto line = readln.splitter;
        auto x = line.front.to !(int) (2);
        line.popFront ();
        auto k = line.front.to !(int);
        /*
        string t; int k;
        readf("%s %s", &t, &k);
        readln;
        auto x = t.to!(int)(2);
        */
        v[x][k].writeln;
    }

}

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

void main()
{
    immutable int mxcost = 101;

    int n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

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

    auto cnt = new int[] (1 << n);
    foreach (_; 0 .. m) {
        auto x = readln.chomp.to!(int)(2);
        ++cnt[x];
    }

    auto v = new int[][] (1 << n, mxcost+1);
    foreach (e; 0 .. 1 << n) {
        foreach (o; e .. 1 << n) {
            auto xr = e ^ o;
            auto cost = 0;
            foreach (b; 0 .. n) {
                if ((xr & (1 << b)) == 0) cost += w[b];
            }
            cost = min(cost, mxcost);

            v[e][cost] += cnt[o];
            if (e != o) v[o][cost] += cnt[e];
        }
    }

    foreach (ref rw; v) {
        rw = rw.cumulativeFold!((a, b) => a + b).array;
    }

    debug { v.each!(arr => arr.take(20).writeln); }

    while (q--) {
        auto line = readln.splitter;
        auto x = line.front.to !(int) (2);
        line.popFront ();
        auto k = line.front.to !(int);
        /*
        string t; int k;
        readf("%s %s", &t, &k);
        readln;
        auto x = t.to!(int)(2);
        */
        v[x][k].writeln;
    }

}

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

immutable int limit = 102;

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		readln;
		auto w = readln.splitter.map !(to !(int)).array;
		reverse (w);
		auto num = new int [1 << n];
		foreach (i; 0..m)
		{
			auto b = readln.strip.to !(int) (2);
			num[b] += 1;
		}
		debug {writeln (num);}

		auto numAtCost = new int [] [] (1 << n, limit + 1);
		foreach (s; 0..1 << n)
		{
			foreach (t; s..1 << n)
			{
				int cost = 0;
				auto r = s ^ t;
				foreach (k; 0..n)
				{
					if (!((r >> k) & 1))
					{
						cost += w[k];
					}
				}
				cost = min (cost, limit);
				numAtCost[s][cost] += num[t];
				if (s < t)
				{
					numAtCost[t][cost] += num[s];
				}
			}
		}

		foreach (s; 0..1 << n)
		{
			foreach (cost; 0..limit)
			{
				numAtCost[s][cost + 1] += numAtCost[s][cost];
			}
			debug {writeln (s, ": ", numAtCost[s]);}
		}

		foreach (j; 0..q)
		{
			auto v = readln.splitter;
			auto b = v.front.to !(int) (2);
			v.popFront ();
			auto k = v.front.to !(int);
			debug {writeln (b, ", ", k, ": ");}
			writeln (numAtCost[b][k]);
		}
	}
}

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() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const Q = readInt();
      auto W = new int[N];
      foreach (i; 0 .. N) {
        W[i] = readInt();
      }

      int readIt() {
        const str = readToken();
        int ret;
        foreach (i; 0 .. N) {
          ret |= (str[i] - '0') << i;
        }
        return ret;
      }

      auto S = new int[M];
      foreach (j; 0 .. M) {
        S[j] = readIt();
      }
      auto T = new int[Q];
      auto K = new int[Q];
      foreach (q; 0 .. Q) {
        T[q] = readIt();
        K[q] = readInt();
      }

      auto WSum = new int[1 << N];
      foreach (i; 0 .. N) {
        foreach (h; 0 .. 1 << i) {
          WSum[h | 1 << i] = WSum[h] + W[i];
        }
      }

      auto cnt = new int[1 << N];
      foreach (j; 0 .. M) {
        ++cnt[S[j]];
      }
      auto anss = new int[][](1 << N, LIM);
      foreach (t; 0 .. 1 << N) {
        foreach (s; 0 .. 1 << N) {
          const w = WSum[((1 << N) - 1) ^ s ^ t];
          if (w < LIM) {
            anss[t][w] += cnt[s];
          }
        }
        foreach (k; 1 .. LIM) {
          anss[t][k] += anss[t][k - 1];
        }
      }

      foreach (q; 0 .. Q) {
        writeln(anss[T[q]][K[q]]);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main()
{
    immutable int mxcost = 100;

    int n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

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

    auto cnt = new int[] (1 << n);
    foreach (_; 0 .. m) {
        auto x = readln.chomp.to!(int)(2);
        ++cnt[x];
    }

    auto v = new int[][] (1 << n, mxcost+1);
    foreach (e; 0 .. 1 << n) {
        foreach (o; e .. 1 << n) {
            auto xr = e ^ o;
            auto cost = 0;
            foreach (b; 0 .. n) {
                if ((xr & (1 << b)) != 0) cost += w[b];
            }
            cost = min(cost, mxcost);

            v[e][cost] += cnt[o];
            if (e != o) v[o][cost] += cnt[e];
        }
    }

    foreach (e; 0 .. 1 << n) {
        foreach (i; 0 .. mxcost) v[e][i+1] += v[e][i];

    }

    debug { v.each!(arr => arr.take(20).writeln); }

    while (q--) {
        auto line = readln.splitter;
        auto x = line.front.to !(int) (2);
        line.popFront ();
        auto k = line.front.to !(int);
        /*
        string t; int k;
        readf("%s %s", &t, &k);
        readln;
        auto x = t.to!(int)(2);
        */
        v[x][k].writeln;
    }

}

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

void main()
{
    immutable int mxcost = 100;

    int n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

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

    auto cnt = new int[] (1 << n);
    foreach (_; 0 .. m) {
        auto x = readln.chomp.to!(int)(2);
        ++cnt[x];
    }

    auto v = new int[][] (1 << n, mxcost+1);
    foreach (e; 0 .. 1 << n) {
        foreach (o; e .. 1 << n) {
            auto xr = e ^ o;
            auto cost = 0;
            foreach (b; 0 .. n) {
                if ((xr & (1 << b)) == 0) cost += w[b];
            }
            cost = min(cost, mxcost);

            v[e][cost] += cnt[o];
            if (e != o) v[o][cost] += cnt[e];
        }
    }

    foreach (e; 0 .. 1 << n) {
        foreach (i; 0 .. mxcost) v[e][i+1] += v[e][i];

    }

    debug { v.each!(arr => arr.take(20).writeln); }

    while (q--) {
        auto line = readln.splitter;
        auto x = line.front.to !(int) (2);
        line.popFront ();
        auto k = line.front.to !(int);
        /*
        string t; int k;
        readf("%s %s", &t, &k);
        readln;
        auto x = t.to!(int)(2);
        */
        v[x][k].writeln;
    }

}


Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai — the current skill level. All skills have the same maximum level A.Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values:  The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force.

The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≤ n ≤ 100 000, 1 ≤ A ≤ 109, 0 ≤ cf, cm ≤ 1000, 0 ≤ m ≤ 1015). The second line contains exactly n integers ai (0 ≤ ai ≤ A), separated by spaces, — the current levels of skills.

On the first line print the maximum value of the Force that the character can achieve using no more than m currency units. On the second line print n integers a'i (ai ≤ a'i ≤ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces.

NoteIn the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1.In the second test one should increase all skills to maximum.

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

void main ()
{
	int n, a;
	long cf, cm, m;
	while (readf (" %s %s %s %s %s ", &n, &a, &cf, &cm, &m) > 0)
	{
		auto c = readln.split.map !(to !(int)).array;
		auto d = c.enumerate.array;
		schwartzSort !(x => x.value) (d);
		auto prefSum = [0L];
		foreach (i; 0..n)
		{
			prefSum ~= prefSum.back + d[i].value;
		}

		bool canDo (int lim, int val)
		{
			int lo = 0;
			int hi = lim;
			while (lo < hi)
			{
				int me = (lo + hi + 1) >> 1;
				if (d[me].value < val)
				{
					lo = me;
				}
				else
				{
					hi = me - 1;
				}
			}
			long s = prefSum[lo + 1];
			s = val * 1L * (lo + 1) - s;
			return s <= m;
		}

		int countLower (int lim)
		{
			int lo = 0;
			int hi = a;
			while (lo < hi)
			{
				int me = (lo + hi + 1) >> 1;
				if (canDo (lim, me))
				{
					lo = me;
				}
				else
				{
					hi = me - 1;
				}
			}
			return lo;
		}

		long res = -1;
		int k = -1;
		auto mSaved = m;
		foreach_reverse (i; 0..n)
		{
			if (m < 0)
			{
				break;
			}

			long cur = cf * 1L * (n - i - 1);
			cur += cm * 1L * countLower (i);
			if (res < cur)
			{
				res = cur;
				k = i + 1;
			}

			m -= a - d[i].value;
			d[i].value = a;
		}
		if (m >= 0)
		{
			k = 0;
			res = cf * 1L * n + cm * 1L * a;
		}
		writeln (res);

		m = mSaved;
		d = c.enumerate.array;
		schwartzSort !(x => x.value) (d);
		foreach (i; k..n)
		{
			m -= a - d[i].value;
			d[i].value = a;
		}
		int temp = countLower (k - 1);
		foreach (i; 0..k)
		{
			d[i].value = max (d[i].value, temp);
		}
		schwartzSort !(x => x.index) (d);
		writefln ("%(%s %)", d.map !(x => x.value));
	}
}


An n × n square matrix is special, if:  it is binary, that is, each cell contains either a 0, or a 1;  the number of ones in each row and column equals 2. You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones.As the required value can be rather large, print the remainder after dividing the value by the given number mod.

The first line of the input contains three integers n, m, mod (2 ≤ n ≤ 500, 0 ≤ m ≤ n, 2 ≤ mod ≤ 109). Then m lines follow, each of them contains n characters — the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m × n table contains at most two numbers one.

Print the remainder after dividing the required value by number mod.

NoteFor the first test the required matrices are: 011101110011110101In the second test the required matrix is already fully given, so the answer is 1.

import std.stdio;

long[][] cache;
long modulo;

long F(int i, int j)
{
	if (i < 0 || j < 0)
		return 0;

	if (cache[i][j] == -1)
	{
		if (i == 0 && j == 0)
			cache[i][j] = 1;
		else
		{
			long res;
			res += i * (i - 1) / 2 * F(i - 2, j + 2);
			res %= modulo;
			res += j * (j - 1) / 2 * F(i, j - 2);
			res %= modulo;
			res += i * j * F(i - 1, j);
			res %= modulo;
			cache[i][j] = res;
		}
	}
	return cache[i][j];
}

void fill_cache(long value)
{
	foreach (ref r; cache)
		foreach (ref e; r)
				e = value;
}

void main()
{
	int n, m;
	readf("%s %s %s\n", &n, &m, &modulo);
	cache = new long[][](n + 1, n + 1);
	fill_cache(-1);
	auto ones_count = new int[](n);
	foreach (_; 0 .. m)
	{
		string tmp;
		readf("%s\n", &tmp);
		foreach (i; 0 .. n)
		{
			if (tmp[i] == '1')
				ones_count[i] += 1;
		}
	}
	int i, j;
	foreach (c; ones_count)
	{
		if (c == 0) {
			i += 1;
		}
		else if (c == 1) {
			j += 1;
		}
	}
	writeln(F(i, j));
}


Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer φ(n) is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number 1 is coprime to all the positive integers and φ(1) = 1.Now the teacher gave Vovochka an array of n positive integers a1, a2, ..., an and a task to process q queries li ri — to calculate and print  modulo 109 + 7. As it is too hard for a second grade school student, you've decided to help Vovochka.

The first line of the input contains number n (1 ≤ n ≤ 200 000) — the length of the array given to Vovochka. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106). The third line contains integer q (1 ≤ q ≤ 200 000) — the number of queries. Next q lines contain the queries, one per line. Each query is defined by the boundaries of the segment li and ri (1 ≤ li ≤ ri ≤ n).

Print q numbers — the value of the Euler function for each query, calculated modulo 109 + 7.

// Round floating point numbers
import std.stdio;
import std.algorithm;

const int N = 200000, NN = 1 << 18, Q = 200000, MAX = 1000001, MOD = 1000000007;

int ri()
{
  int x;
  readf(" %s", &x);
  return x;
}

struct B
{
  int l, r, id;
};

B b[Q];

int pre[MAX];
int fac[MAX];
int a[N];
int prod[N];
int seg[NN*2];
int ans[Q];

void modify(int l, int r, int x)
{
  l += NN-1;
  r += NN-1;
  for (; l < r; l >>= 1, r >>= 1) {
    if (l%2 == 0)
      seg[l] = seg[l] * long(x) % MOD;
    if (r%2 == 0)
      r--, seg[r] = seg[r] * long(x) % MOD;
  }
}

int query(int i)
{
  int r = 1;
  for (i += NN-1; ; ) {
    r = r * long(seg[i]) % MOD;
    if (! i) break;
    i = i-1 >> 1;
  }
  return r;
}

int inv(int x)
{
  int r = 1;
  for (; x > 1; x = MOD % x)
    r = r * long(-MOD/x) % MOD;
  return (r+MOD)%MOD;
}

void main()
{
/*
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)
*/
	for (int i = 2; i<MAX; i++)
    if (! fac[i])
      for (int j = i; j < MAX; j += i)
        fac[j] = i;

  int n = ri();
  for (int i = 0; i<n; i++) {
    a[i] = ri();
    prod[i] = (i ? prod[i-1] : 1) * long(a[i]) % MOD;
  }
  int q = ri();
  for( int i=0; i<q; i++) {
    b[i].id = i;
    b[i].l = ri()-1;
    b[i].r = ri()-1;
  }
  sort!("a.r < b.r")(b[0..q]);
  //fill_n(seg, NN*2, 1);
  for (int i=0; i<NN*2; i++)
    seg[i] = 1;

  int j = 0;
  for(int i=0; i<n; i++) {
    for (int x = a[i]; x > 1; ) {
      int y = fac[x];
      while ((x /= y) % y == 0){}
      modify(pre[y], i+1, long(y-1)*inv(y)%MOD);
      pre[y] = i+1;
    }
    for (; j < q && b[j].r == i; j++)
      ans[b[j].id] = query(b[j].l) * long(prod[i]) % MOD * (b[j].l ? inv(prod[b[j].l-1]) : 1) % MOD;
  }
  for(int i=0; i<q; i++)
    printf("%d\n", ans[i]);
}


Please notice the unusual memory limit of this problem.Orac likes games. Recently he came up with the new game, "Game of Life".You should play this game on a black and white grid with $$$n$$$ rows and $$$m$$$ columns. Each cell is either black or white.For each iteration of the game (the initial iteration is $$$0$$$), the color of each cell will change under the following rules: If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same. Otherwise, the color of the cell on the next iteration will be different.Two cells are adjacent if they have a mutual edge.Now Orac has set an initial situation, and he wants to know for the cell $$$(i,j)$$$ (in $$$i$$$-th row and $$$j$$$-th column), what will be its color at the iteration $$$p$$$. He may ask you these questions several times.

The first line contains three integers $$$n,m,t\ (1\le n,m\le 1000, 1\le t\le 100\,000)$$$, representing the number of rows, columns, and the number of Orac queries. Each of the following $$$n$$$ lines contains a binary string of length $$$m$$$, the $$$j$$$-th character in $$$i$$$-th line represents the initial color of cell $$$(i,j)$$$. '0' stands for white, '1' stands for black. Each of the following $$$t$$$ lines contains three integers $$$i,j,p\ (1\le i\le n, 1\le j\le m, 1\le p\le 10^{18})$$$, representing a query from Orac.

Print $$$t$$$ lines, in $$$i$$$-th line you should print the answer to the $$$i$$$-th query by Orac. If the color of this cell is black, you should print '1'; otherwise, you should write '0'.

Note  For the first example, the picture above shows the initial situation and the color of cells at the iteration $$$1$$$, $$$2$$$, and $$$3$$$. We can see that the color of $$$(1,1)$$$ at the iteration $$$1$$$ is black, the color of $$$(2,2)$$$ at the iteration $$$2$$$ is black, and the color of $$$(3,3)$$$ at the iteration $$$3$$$ is also black.For the second example, you can prove that the cells will never change their colors.

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

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	int rows, cols, tests;
	while (readf !(" %s %s %s") (rows, cols, tests) > 0)
	{
		readln;
		bool [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map !(q{a == '1'}).array;
		}

		auto dist = new int [] [] (rows, cols);
		auto mark = new bool [] [] (rows, cols);
		alias Coord = Tuple !(int, q{row}, int, q{col});
		Coord [] q;
		q.reserve (rows * cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				bool same = false;
				foreach (dir; 0..dirs)
				{
					auto nRow = row + dRow[dir];
					auto nCol = col + dCol[dir];
					if (0 <= nRow && nRow < rows &&
					    0 <= nCol && nCol < cols)
					{
						same |= (board[row][col] ==
						    board[nRow][nCol]);
					}
				}
				if (same)
				{
					dist[row][col] = 0;
					mark[row][col] = board[row][col];
					q ~= Coord (row, col);
				}
				else
				{
					dist[row][col] = int.max;
				}
			}
		}

		while (!q.empty)
		{
			auto row = q.front.row;
			auto col = q.front.col;
			q.popFront ();
			q.assumeSafeAppend ();
			foreach (dir; 0..dirs)
			{
				auto nRow = row + dRow[dir];
				auto nCol = col + dCol[dir];
				if (0 <= nRow && nRow < rows &&
				    0 <= nCol && nCol < cols)
				{
					if (dist[nRow][nCol] == int.max)
					{
						dist[nRow][nCol] =
						    dist[row][col] + 1;
						mark[nRow][nCol] =
						    mark[row][col];
						q ~= Coord (nRow, nCol);
					}
				}
			}
		}

		foreach (test; 0..tests)
		{
			int row, col;
			long moment;
			readf !(" %s %s %s") (row, col, moment);
			row -= 1;
			col -= 1;
			moment = min (moment, rows * cols * 8 + (moment & 1));
			int res;
			if (moment < dist[row][col])
			{
				res = board[row][col];
			}
			else
			{
				res = mark[row][col] ^ (moment & 1);
			}
			writeln (res);
		}
	}
}

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

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	int rows, cols, tests;
	while (readf !(" %s %s %s") (rows, cols, tests) > 0)
	{
		readln;
		bool [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map !(q{a == '1'}).array;
		}

		auto dist = new int [] [] (rows, cols);
		auto mark = new bool [] [] (rows, cols);
		alias Coord = Tuple !(int, q{row}, int, q{col});
		Coord [] q;
		q.reserve (rows * cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				bool same = false;
				foreach (dir; 0..dirs)
				{
					auto nRow = row + dRow[dir];
					auto nCol = col + dCol[dir];
					if (0 <= nRow && nRow < rows &&
					    0 <= nCol && nCol < cols)
					{
						same |= (board[row][col] ==
						    board[nRow][nCol]);
					}
				}
				if (same)
				{
					dist[row][col] = 0;
					mark[row][col] = board[row][col];
					q ~= Coord (row, col);
				}
				else
				{
					dist[row][col] = int.max;
				}
			}
		}

		while (!q.empty)
		{
			auto row = q.front.row;
			auto col = q.front.col;
			q.popFront ();
			q.assumeSafeAppend ();
			foreach (dir; 0..dirs)
			{
				auto nRow = row + dRow[dir];
				auto nCol = col + dCol[dir];
				if (0 <= nRow && nRow < rows &&
				    0 <= nCol && nCol < cols)
				{
					if (dist[nRow][nCol] == int.max)
					{
						dist[nRow][nCol] =
						    dist[row][col] + 1;
						mark[nRow][nCol] =
						    mark[row][col];
						q ~= Coord (nRow, nCol);
					}
				}
			}
		}

		foreach (test; 0..tests)
		{
			int row, col;
			long moment;
			readf !(" %s %s %s") (row, col, moment);
			row -= 1;
			col -= 1;
			moment = min (moment, 1 + rows * cols);
			int res;
			if (moment < dist[row][col])
			{
				res = board[row][col];
			}
			else
			{
				res = mark[row][col] ^ (moment & 1);
			}
			writeln (res);
		}
	}
}


Limak has a grid that consists of 2 rows and n columns. The j-th cell in the i-th row contains an integer ti, j which can be positive, negative or zero.A non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to 0.Limak wants to choose some nice rectangles and give them to his friends, as gifts. No two chosen rectangles should share a cell. What is the maximum possible number of nice rectangles Limak can choose?

The first line of the input contains an integer n (1 ≤ n ≤ 300 000) — the number of columns in the grid. The next two lines contain numbers in the grid. The i-th of those two lines contains n integers ti, 1, ti, 2, ..., ti, n ( - 109 ≤ ti, j ≤ 109).

Print one integer, denoting the maximum possible number of cell-disjoint nice rectangles.

NoteIn the first sample, there are four nice rectangles:  Limak can't choose all of them because they are not disjoint. He should take three nice rectangles: those denoted as blue frames on the drawings.In the second sample, it's optimal to choose six nice rectangles, each consisting of one cell with a number 0.In the third sample, the only nice rectangle is the whole grid — the sum of all numbers is 0. Clearly, Limak can choose at most one nice rectangle, so the answer is 1.

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

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

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

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

enum E = 18;

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

      auto TSum = new long[][](3, N + 1);
      foreach (i; 0 .. 2) {
        foreach (j; 0 .. N) {
          TSum[i][j + 1] = TSum[i][j] + T[i][j];
        }
        TSum[2][] += TSum[i][];
      }

      auto nxt = new int[][](3, N + 1);
      foreach (i; 0 .. 3) {
        nxt[i][] = -1;
        int[long] cnt;
        int du;
        void add(int j) {
          if (cnt[TSum[i][j]]++ > 0) {
            ++du;
          }
        }
        void rem(int j) {
          if (--cnt[TSum[i][j]] > 0) {
            --du;
          }
        }
        int l, r;
        void doIt(int jL, int jR, int kL, int kR) {
          if (jR - jL < 1) {
            return;
          }
          const j = (jL + jR) / 2;
          for (; l < j; ) rem(l++);
          for (; l > j; ) add(--l);
          foreach (k; kL .. kR) {
            if (k == N + 1) {
              nxt[i][j] = N + 1;
              break;
            }
            for (; r < k + 1; ) add(r++);
            for (; r > k + 1; ) rem(--r);
            if (du > 0) {
              nxt[i][j] = k;
              break;
            }
          }
          doIt(jL, j, kL, nxt[i][j] + 1);
          doIt(j + 1, jR, nxt[i][j], kR);
        }
        doIt(0, N + 1, 0, N + 1 + 1);
      }
      debug {
        writeln("TSum = ", TSum);
        writeln("nxt = ", nxt);
        foreach (i; 0 .. 3) {
          foreach (j; 0 .. N + 1) {
            int brt = N + 1;
            bool[long] app;
            foreach (k; j .. N + 1) {
              if (TSum[i][k] in app) {
                brt = k;
                break;
              }
              app[TSum[i][k]] = true;
            }
            assert(brt == nxt[i][j]);
          }
        }
      }

      auto nxts = new int[][][](3, E, N + 2);
      foreach (i; 0 .. 3) {
        nxts[i][0][0 .. N + 1] = nxt[i][];
        nxts[i][0][N + 1] = N + 1;
        foreach (e; 0 .. E - 1) {
          foreach (j; 0 .. N + 2) {
            nxts[i][e + 1][j] = nxts[i][e][nxts[i][e][j]];
          }
        }
      }

      int[long] cache;
      int calc(int x, int y) {
        const key = 1L * x * (N + 1) + y;
        int ret;
        cache.update(key, {
          if (x <= y) {
            int score;
            int xx = x;
            foreach_reverse (e; 0 .. E) {
              if (nxts[0][e][xx] <= y) {
                score += 1 << e;
                xx = nxts[0][e][xx];
              }
            }
            chmax(ret, score);
            if (nxt[2][y] <= N) {
              chmax(ret, score + 1 + calc(nxt[2][y], nxt[2][y]));
            }
            if (nxt[0][xx] <= N) {
              chmax(ret, score + 1 + calc(nxt[0][xx], y));
            }
            if (nxt[1][y] <= N) {
              chmax(ret, score + 1 + calc(xx, nxt[1][y]));
            }
          }
          if (x >= y) {
            int score;
            int yy = y;
            foreach_reverse (e; 0 .. E) {
              if (nxts[1][e][yy] <= x) {
                score += 1 << e;
                yy = nxts[1][e][yy];
              }
            }
            chmax(ret, score);
            if (nxt[2][x] <= N) {
              chmax(ret, score + 1 + calc(nxt[2][x], nxt[2][x]));
            }
            if (nxt[1][yy] <= N) {
              chmax(ret, score + 1 + calc(x, nxt[1][yy]));
            }
            if (nxt[0][x] <= N) {
              chmax(ret, score + 1 + calc(nxt[0][x], yy));
            }
          }
          debug {
            writefln("calc %s %s = %s", x, y, ret);
          }
          return ret;
        }, (ref int r) {
          return ret = r;
        });
        return ret;
      }

      const ans = calc(0, 0);
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Creatnx has $$$n$$$ mirrors, numbered from $$$1$$$ to $$$n$$$. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The $$$i$$$-th mirror will tell Creatnx that he is beautiful with probability $$$\frac{p_i}{100}$$$ for all $$$1 \le i \le n$$$.Some mirrors are called checkpoints. Initially, only the $$$1$$$st mirror is a checkpoint. It remains a checkpoint all the time.Creatnx asks the mirrors one by one, starting from the $$$1$$$-st mirror. Every day, if he asks $$$i$$$-th mirror, there are two possibilities:  The $$$i$$$-th mirror tells Creatnx that he is beautiful. In this case, if $$$i = n$$$ Creatnx will stop and become happy, otherwise he will continue asking the $$$i+1$$$-th mirror next day;  In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the checkpoint with a maximal number that is less or equal to $$$i$$$. There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints. You are given $$$q$$$ queries, each query is represented by an integer $$$u$$$: If the $$$u$$$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $$$u$$$-th mirror is no longer a checkpoint.After each query, you need to calculate the expected number of days until Creatnx becomes happy.Each of this numbers should be found by modulo $$$998244353$$$. Formally, let $$$M = 998244353$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

The first line contains two integers $$$n$$$, $$$q$$$ ($$$2 \leq n, q \le 2 \cdot 10^5$$$)  — the number of mirrors and queries. The second line contains $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq 100$$$). Each of $$$q$$$ following lines contains a single integer $$$u$$$ ($$$2 \leq u \leq n$$$) — next query.

Print $$$q$$$ numbers – the answers after each query by modulo $$$998244353$$$.

NoteIn the first test after the first query, the first and the second mirrors are checkpoints. Creatnx will ask the first mirror until it will say that he is beautiful, after that he will ask the second mirror until it will say that he is beautiful because the second mirror is a checkpoint. After that, he will become happy. Probabilities that the mirrors will say, that he is beautiful are equal to $$$\frac{1}{2}$$$. So, the expected number of days, until one mirror will say, that he is beautiful is equal to $$$2$$$ and the answer will be equal to $$$4 = 2 + 2$$$.

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

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

void solve(){
	int n = rint, q = rint;
	long[] ps = rlong(n);

	Finite[] prods = [Finite(1)];
	foreach(p; ps) prods ~= (prods[$ - 1] * p) / 100;
	log("prods:", prods);

	Finite[] invprods = [Finite(1)];
	foreach(p; ps) invprods ~= (invprods[$ - 1] * 100) / p;
	log("invprods:", invprods);

	Finite[] sums = [Finite(0)];
	foreach(pr; prods) sums ~= sums[$ - 1] + pr;
	log("sums:", sums);

	auto seg1 = new SegTree!int(0, n, (x, y) => y, 0);
	seg1.setValue(0, n, 0);
	log("seg1:\n", seg1);

	auto seg2 = new SegTree!int(0, n, (x, y) => y, 0);
	seg2.setValue(0, n, n);
	log("seg2:\n", seg2);

	Finite ans = (sums[n] - sums[0]) * invprods[n];
	log("ans:", ans);
	foreach(_; 0 .. q){
		int u = rint - 1;
		int i = seg1.getValue(u), j = seg2.getValue(u);
		if(i < u){ // u is not a checkpoint
			seg2.setValue(i, u, u), seg1.setValue(u, j, u);
			log("u:", u, "i:", i, "j:", j);
			log("seg1:\n", seg1);
			log("seg2:\n", seg2);
			ans -= (sums[j] - sums[i]) * invprods[j];
			ans += (sums[u] - sums[i]) * invprods[u];
			ans += (sums[j] - sums[u]) * invprods[j];
		}
		else{ // u is a checkpoint
			i = seg1.getValue(u - 1);
			seg2.setValue(i, u, j), seg1.setValue(u, j, i);
			log("u:", u, "i:", i, "j:", j);
			log("seg1:\n", seg1);
			log("seg2:\n", seg2);
			ans -= (sums[u] - sums[i]) * invprods[u];
			ans -= (sums[j] - sums[u]) * invprods[j];
			ans += (sums[j] - sums[i]) * invprods[j];
		}
		ans.writeln;
	}
}

const long mod = 998244353;
struct Finite{
	long value;
	private static long[] _inv = [0, 1], _frac = [1, 1], _invfrac = [1, 1];
	this(long v){ value = val(v); }
	static long val(long v){
		if(v >= 0) return v % mod;
		else return (v + mod  - (v / mod) * mod) % mod;
	}
	bool opCast(T: bool)(){ return value != 0; }
	Finite opUnary(string s){ long v;
		if(s == "+") v = value;
		else if(s == "-") v = mod - value;
		else if(s == "++") v = value + 1;
		else if(s == "--") v = value + mod - 1;
		else assert(0, "Operator unary " ~ s ~ " not implemented");
		return Finite(v);
	}
	Finite opBinary(string s)(Finite b){
		return opBinary!s(b.value);
	}
	Finite opBinary(string s)(long u){ long v;
		if(s == "+") v = value + u;
		else if(s == "-") v = value + mod - u;
		else if(s == "*") v = value * u;
		else if(s == "/") v = value * inv(u);
		else assert(0, "Operator " ~ s ~ " not implemented");
		return Finite(v);
	}
	Finite opBinaryRight(string s)(long u){ long v;
		if(s == "+") v = u + value;
		else if(s == "-") v = u + mod - value;
		else if(s == "*") v = u * value;
		else if(s == "/") v = u * invvalue;
		else assert(0, "Operator " ~ s ~ " not implemented");
		return Finite(v);
	}
	Finite opAssign(long v){ value = v; return this; }
	Finite opOpAssign(string s)(Finite b){
		return opOpAssign!s(b.value);
	}
	Finite opOpAssign(string s)(long v){
		if(s == "+") value = (value + v) % mod;
		else if(s == "-") value = (value + mod - v) % mod;
		else if(s == "*") value = (value * v) % mod;
		else if(s == "/") value = (value * inv(v)) % mod;
		else assert(0, "Operator " ~ s ~ "= not implemented");
		return this;
	}
	bool opEquals(Finite b){
		return(value == b.value);
	}
	string toString(){ return value.to!string; }
	long inv(long v){
		v = val(v);
		while(v >= _inv.length){
			_inv ~= _inv[mod % $] * (mod - mod / _inv.length) % mod;
		}
		return _inv[v.to!int];
	}
	long invvalue(){
		return inv(value);
	}
	static Finite opCall(long v){ return Finite(val(v)); }

}

class SegTree(T){
	T delegate(T, T) apply;
	T initial;
	int a, b; // a <= x < b を担当する
	bool hasValue;
	SegTree left, right; // 左の子(a <= x < c)、右の子(c <= x < b)
	T value;
	this(int a, int b, T delegate(T, T) apply, T initial = T.init){
		this.a = a, this.b = b;
		this.apply = apply;
		this.initial = initial;
		this.value = initial;
		if(b - a == 1){
			this.hasValue = 1;
		}
		else{
			int c = (a + b) / 2;
			this.left = new SegTree(a, c, apply, initial);
			this.right = new SegTree(c, b, apply, initial);
		}
	}

	// [a, b) に値を設定する ※[a, b) はこのノードの担当区間とかぶっていなくてもよい
	void setValue(int a, int b, T value){
		if(b <= this.a || this.b <= a) return;
		if(a <= this.a && this.b <= b){
			this.hasValue = true;
			this.value = apply(this.value, value);
		}
		else{
			if(this.hasValue){
				left.setValue(left.a, left.b, this.value);
				right.setValue(right.a, right.b, this.value);
				this.hasValue = false;
			}
			left.setValue(a, b, value);
			right.setValue(a, b, value);
		}
	}

	// iにおける値 ※iは必ずこのノードの担当区間内である前提
	T getValue(int i){
		assert(a <= i && i < b);
		if(this.hasValue) return this.value;
		else if(i < left.b) return left.getValue(i);
		else return right.getValue(i);
	}

	// 配列に変換したもの（デバッグ用）
	T[] array(){
		T[] res;
		foreach(i; a .. b) res ~= this.value;
		return res;
	}

	// 文字列に変換したもの（デバッグ用）
	override string toString(){
		if(this.hasValue) return this.array.to!string;
		else return left.toString ~ right.toString;
	}
}

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

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

// 1 + p0 + p0 p1 + p0 p1 p2
struct Info {
  Mint prod, sum;
  Info opBinary(string op)(Info a) const if (op == "*") {
    return Info(prod * a.prod, sum + prod * a.sum);
  }
}
enum IDENTITY = Info(Mint(1), Mint(0));

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

      int segN;
      for (segN = 1; segN < N; segN <<= 1) {}
      auto seg = new Info[segN << 1];
      seg[] = IDENTITY;
      foreach (i; 0 .. N) {
        seg[segN + i] = Info(Mint(P[i]) / 100, Mint(1));
      }
      foreach_reverse (a; 1 .. segN) {
        seg[a] = seg[a << 1] * seg[a << 1 | 1];
      }
      Info rangeProd(int a, int b) {
        Info retL = IDENTITY, retR = IDENTITY;
        for (a += segN, b += segN; a < b; a >>= 1, b >>= 1) {
          if (a & 1) retL = retL * seg[a++];
          if (b & 1) retR = seg[--b] * retR;
        }
        return retL * retR;
      }
      Mint calc(int a, int b) {
        const res = rangeProd(a, b);
        const ret = res.sum / res.prod;
        debug {
          writeln("calc ", a, " ", b, ": ", res, " ", ret);
        }
        return ret;
      }

      auto set = new RedBlackTree!int;
      set.insert(0);
      set.insert(N);
      Mint now = calc(0, N);
      foreach (q; 0 .. Q) {
        const l = set.lowerBound(U[q]).back;
        const r = set.upperBound(U[q]).front;
        if (set.removeKey(U[q])) {
          debug {
            writeln("remove ", U[q], "; ", l, " ", r);
          }
          now -= calc(l, U[q]);
          now -= calc(U[q], r);
          now += calc(l, r);
        } else {
          debug {
            writeln("insert ", U[q], "; ", l, " ", r);
          }
          set.insert(U[q]);
          now -= calc(l, r);
          now += calc(l, U[q]);
          now += calc(U[q], r);
        }
        writeln(now);
      }
    }
  } catch (EOFException e) {
  }
}


You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.

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

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

void solve() {
    int n, q;
    readf!" %d %d "(n, q);
    auto a = readarray!long;
    long odds, evens;
    long oddn, evenn;
    foreach(el; a) {
        if (el & 1) {
            odds += el;
            oddn++;
        }
        else {
            evens += el;
            evenn++;
        }
    }
    foreach(casenum; 0 .. q) {
        byte type;
        long x;
        readf!" %d %d "(type, x);
        if (type == 0) {
            evens += evenn*x;
            writeln(odds + evens);
            if (x & 1) {
                oddn += evenn;
                odds += evens;
                evenn = 0;
                evens = 0;
            }
        }
        else {
            odds += oddn*x;
            writeln(odds + evens);
            if (x & 1) {
                evenn += oddn;
                evens += odds;
                oddn = 0;
                odds = 0;
            }
        }
    }
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n, q;
    readf!" %d %d "(n, q);
    auto a = readln.splitter.map!(to!long).array;
    long cntodd, cnteven, ans;
    foreach (x ; a) {
      if (x % 2 == 0)
        cnteven++;
      else
        cntodd++;
      ans += x;
    }
    foreach (i ; 0 .. q) {
      long type, xj;
      readf!" %d %d "(type, xj);
      if (type == 0) {
        ans += cnteven * xj;
        if (xj % 2 != 0) {
          cntodd += cnteven;
          cnteven = 0;
        }
      } else {
        ans += cntodd * xj;
        if (xj % 2 != 0) {
          cnteven += cntodd;
          cntodd = 0;
        }
      }
      writeln(ans);
    }
  }
}


Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $$$a$$$ with elements $$$a_1, a_2, \ldots, a_{2k-1}$$$, is the array $$$b$$$ with elements $$$b_1, b_2, \ldots, b_{k}$$$ such that $$$b_i$$$ is equal to the median of $$$a_1, a_2, \ldots, a_{2i-1}$$$ for all $$$i$$$. Omkar has found an array $$$b$$$ of size $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$-10^9 \leq b_i \leq 10^9$$$). Given this array $$$b$$$, Ray wants to test Omkar's claim and see if $$$b$$$ actually is an OmkArray of some array $$$a$$$. Can you help Ray?The median of a set of numbers $$$a_1, a_2, \ldots, a_{2i-1}$$$ is the number $$$c_{i}$$$ where $$$c_{1}, c_{2}, \ldots, c_{2i-1}$$$ represents $$$a_1, a_2, \ldots, a_{2i-1}$$$ sorted in nondecreasing order.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — the elements of $$$b$$$. It is guaranteed the sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one line containing YES if there exists an array $$$a$$$ such that $$$b_i$$$ is the median of $$$a_1, a_2, \dots, a_{2i-1}$$$ for all $$$i$$$, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).

NoteIn the second case of the first sample, the array $$$[4]$$$ will generate an OmkArray of $$$[4]$$$, as the median of the first element is $$$4$$$.In the fourth case of the first sample, the array $$$[3, 2, 5]$$$ will generate an OmkArray of $$$[3, 3]$$$, as the median of $$$3$$$ is $$$3$$$ and the median of $$$2, 3, 5$$$ is $$$3$$$.In the fifth case of the first sample, the array $$$[2, 1, 0, 3, 4, 4, 3]$$$ will generate an OmkArray of $$$[2, 1, 2, 3]$$$ as   the median of $$$2$$$ is $$$2$$$  the median of $$$0, 1, 2$$$ is $$$1$$$  the median of $$$0, 1, 2, 3, 4$$$ is $$$2$$$  and the median of $$$0, 1, 2, 3, 3, 4, 4$$$ is $$$3$$$. In the second case of the second sample, the array $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ will generate an OmkArray of $$$[1, 1, 3, 1, 0, -2, -1]$$$, as   the median of $$$1$$$ is $$$1$$$  the median of $$$0, 1, 4$$$ is $$$1$$$  the median of $$$0, 1, 3, 4, 5$$$ is $$$3$$$  the median of $$$-2, -2, 0, 1, 3, 4, 5$$$ is $$$1$$$  the median of $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$0$$$  the median of $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$-2$$$  and the median of $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ is $$$-1$$$ For all cases where the answer is NO, it can be proven that it is impossible to find an array $$$a$$$ such that $$$b$$$ is the OmkArray of $$$a$$$.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto b = ma(n, readInt!int);
	auto s = redBlackTree!int();
	foreach(i, bi; b)
	{
		if (i == 0 || bi == b[i-1])
		{
			s.insert(bi);
		}
		else
		{
			if (bi < b[i-1])
			{
				auto lbim1 = s.lowerBound(b[i-1]);
				if (lbim1.empty || lbim1.back <= bi)
				{
					s.insert(bi);
				}
				else
				{
					return writeln("No");
				}
			}
			else
			{
				auto gbim1 = s.upperBound(b[i-1]);
				if (gbim1.empty || gbim1.front >= bi)
				{
					s.insert(bi);
				}
				else
				{
					return writeln("No");
				}
			}
		}
	}
	return writeln("Yes");
}

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


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

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

void f(string s[], int x, int y, char base, ref int count)
{
    static int[char] flag;
    static bool[111][111] w;
    if(w[x][y] || s[x][y] == '.') return;
    w[x][y] = true;
    if(base != s[x][y])
    {
        if(s[x][y] !in flag)
        {
            flag[s[x][y]] = 42;
            count++;
        }
    }
    else
    {
        f(s, x + 1, y, base, count);
        f(s, x - 1, y, base, count);
        f(s, x, y + 1, base, count);
        f(s, x, y - 1, base, count);
    }
}

void f(int[] a)
{
    a ~= 4;
}

void main(char[][] args)
{
    version(MY_SUPER_PUPER_ONLINE_JUDGE)
    {
        stdin.open("src/input.txt", "rt");
        stdout.open("src/output.txt","wt");
    }

    int w, h;
    char c;
    readf("%d %d %s\n", &w, &h, &c);
    string[] s = new string[w + 2];
    s[0] = s[w + 1] = replicate(".", h + 2);
    for(int i = 1; i <= w; i++)
    {
        s[i] = "." ~ readln()[0..$-1] ~ ".";
    }
    foreach(x; 0..s.length)
    {
        foreach(y; 0..s[x].length)
        {
            if(s[x][y] == c)
            {
                int count = 0;
                f(s, to!int(x), to!int(y), c, count);
                writeln(count);
                return;
            }
        }
    }
}

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

void f(string s[], int x, int y, char base, ref int count)
{
    static int[char] flag;
    static bool[111][111] w;
    if(w[x][y] || s[x][y] == '.') return;
    w[x][y] = true;
    if(base != s[x][y])
    {
        if(s[x][y] !in flag)
        {
            flag[s[x][y]] = 42;
            count++;
        }
    }
    else
    {
        f(s, x + 1, y, base, count);
        f(s, x - 1, y, base, count);
        f(s, x, y + 1, base, count);
        f(s, x, y - 1, base, count);
    }
}

void f(int[] a)
{
    a ~= 4;
}

void main(char[][] args)
{
    version(MY_SUPER_PUPER_ONLINE_JUDGE)
    {
        stdin.open("src/input.txt", "rt");
        stdout.open("src/output.txt","wt");
    }

    int w, h;
    char c;
    readf("%d %d %s\n", &w, &h, &c);
    string[] s = new string[w + 2];
    s[0] = s[w + 1] = replicate(".", h + 2);
    for(int i = 1; i <= w; i++)
    {
        s[i] = "." ~ readln() ~ ".";
    }
    foreach(x; 0..s.length)
    {
        foreach(y; 0..s[x].length)
        {
            if(s[x][y] == c)
            {
                int count = 0;
                f(s, to!int(x), to!int(y), c, count);
                writeln(count);
                return;
            }
        }
    }
}


You are given an array $$$a$$$ of length $$$2n$$$. Consider a partition of array $$$a$$$ into two subsequences $$$p$$$ and $$$q$$$ of length $$$n$$$ each (each element of array $$$a$$$ should be in exactly one subsequence: either in $$$p$$$ or in $$$q$$$).Let's sort $$$p$$$ in non-decreasing order, and $$$q$$$ in non-increasing order, we can denote the sorted versions by $$$x$$$ and $$$y$$$, respectively. Then the cost of a partition is defined as $$$f(p, q) = \sum_{i = 1}^n |x_i - y_i|$$$.Find the sum of $$$f(p, q)$$$ over all correct partitions of array $$$a$$$. Since the answer might be too big, print its remainder modulo $$$998244353$$$.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 150\,000$$$). The second line contains $$$2n$$$ integers $$$a_1, a_2, \ldots, a_{2n}$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of array $$$a$$$.

Print one integer — the answer to the problem, modulo $$$998244353$$$.

NoteTwo partitions of an array are considered different if the sets of indices of elements included in the subsequence $$$p$$$ are different.In the first example, there are two correct partitions of the array $$$a$$$:  $$$p = [1]$$$, $$$q = [4]$$$, then $$$x = [1]$$$, $$$y = [4]$$$, $$$f(p, q) = |1 - 4| = 3$$$;  $$$p = [4]$$$, $$$q = [1]$$$, then $$$x = [4]$$$, $$$y = [1]$$$, $$$f(p, q) = |4 - 1| = 3$$$. In the second example, there are six valid partitions of the array $$$a$$$:   $$$p = [2, 1]$$$, $$$q = [2, 1]$$$ (elements with indices $$$1$$$ and $$$2$$$ in the original array are selected in the subsequence $$$p$$$);  $$$p = [2, 2]$$$, $$$q = [1, 1]$$$;  $$$p = [2, 1]$$$, $$$q = [1, 2]$$$ (elements with indices $$$1$$$ and $$$4$$$ are selected in the subsequence $$$p$$$);  $$$p = [1, 2]$$$, $$$q = [2, 1]$$$;  $$$p = [1, 1]$$$, $$$q = [2, 2]$$$;  $$$p = [2, 1]$$$, $$$q = [2, 1]$$$ (elements with indices $$$3$$$ and $$$4$$$ are selected in the subsequence $$$p$$$).

// Cheese-Cracker: cheese-cracker.github.io

const ll PRIME = 998244353;

ll modinv(ll num){
    ll res = 1;
    ll x = num;
    ll y = PRIME-2;
    while(y > 0){
        if(y & 1){
            res *= x;
            res %= PRIME;
        }
        x = x * x;
        x %= PRIME;
        y >>= 1;
    }
    return res;
}

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    arr.sort;

    ll s1 = 0, s2 = 0;
    // 1st half
    foreach(i; 0..n){ s1 += arr[i]; }
    // 2nd half
    foreach(i; n..2*n){ s2 += arr[i]; }

    ll res = s2 - s1;
    show(res);
    res %= PRIME;

    ll combi = 1;
    // Multiply 2nCn
    foreach(k; n+1..2*n+1){
        combi *= k;
        combi %= PRIME;
    }
    ll divi = 1;
    foreach(k; 1..n+1){
        divi *= k;
        divi %= PRIME;
    }
    combi *= modinv(divi);
    combi %= PRIME;
    res *= combi;
    res %= PRIME;
    writeln(res);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, "x",  long, "y");
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

enum LIM = 10^^6 + 10;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

void main() {
  prepare;

  try {
    for (; ; ) {
      const N = readInt();
      auto A = new long[2 * N];
      foreach (i; 0 .. 2 * N) {
        A[i] = readLong();
      }
      A.sort;

      Mint ans;
      ans -= A[0 .. N].sum;
      ans += A[N .. 2 * N].sum;
      ans *= binom(2 * N, N);
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable int mod = 998_244_353;

int powMod (int a, int p)
{
	int res = 1 % mod;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

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

		int f = 1;
		foreach (i; 1..n + 1)
		{
			f = (f * 1L * i) % mod;
		}

		int invF = powMod (f, mod - 2);

		int g = f;
		foreach (i; n + 1..n * 2 + 1)
		{
			g = (g * 1L * i) % mod;
		}

		int add = g;
		add = (add * 1L * invF) % mod;
		add = (add * 1L * invF) % mod;

		int res = 0;
		foreach (i; 1..n * 2)
		{
			int mult = n - abs (n - i);
			int cur = (add * 1L * (a[i] - a[i - 1])) % mod;
			res = (res + cur * 1L * mult) % mod;
		}
		writeln (res);
	}
}


You are given $$$n$$$ blocks, each of them is of the form [color$$$_1$$$|value|color$$$_2$$$], where the block can also be flipped to get [color$$$_2$$$|value|color$$$_1$$$]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.The value of the sequence is defined as the sum of the values of the blocks in this sequence.Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of given blocks. Each of the following $$$n$$$ lines describes corresponding block and consists of $$$\mathrm{color}_{1,i}$$$, $$$\mathrm{value}_i$$$ and $$$\mathrm{color}_{2,i}$$$ ($$$1 \le \mathrm{color}_{1,i}, \mathrm{color}_{2,i} \le 4$$$, $$$1 \le \mathrm{value}_i \le 100\,000$$$).

Print exactly one integer — the maximum total value of the subset of blocks, which makes a valid sequence.

NoteIn the first example, it is possible to form a valid sequence from all blocks.One of the valid sequences is the following:[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]The first block from the input ([2|1|4] $$$\to$$$ [4|1|2]) and second ([1|2|4] $$$\to$$$ [4|2|1]) are flipped.In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):[2|100000|1] [1|100000|1] [1|100000|2]In the third example, it is not possible to form a valid sequence of two or more blocks, so the answer is a sequence consisting only of the first block since it is the block with the largest value.

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;

immutable long MOD = 10^^9 + 7;
immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Tuple!(int, int, int)[](N);
    auto E = new int[][][](4, 4);
    auto D = new int[](4);
    auto uf = new UnionFind(4);
    int ans = 0;

    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        int l = s[0] - 1;
        int r = s[2] - 1;
        int score = s[1];
        if (l > r) swap(l, r);
        A[i] = tuple(l, score, r);
        E[l][r] ~= score;
        D[l] += 1;
        D[r] += 1;
        uf.unite(l, r);
    }
    foreach (i; 0..4) foreach (j; 0..4) E[i][j].sort();

    // 非連結
    if (4.iota.map!(i => uf.find(i) != uf.find(0)).any) {
        foreach (mask; 1..15) {
            int[] C;
            foreach (i; 0..4) if (mask & (1 << i)) C ~= i;
            if (C.map!(c => uf.find(c) != uf.find(C[0])).any) continue;
            int tmp = 0;
            foreach (i; 0..4)
                foreach (j; i..4)
                    if ((mask & (1 << i)) && (mask & (1 << j)))
                        tmp += E[i][j].sum;
            ans = max(ans, tmp);
        }
        ans.writeln;
        return;
    }

    ans = A.map!(a => a[1]).sum;
    if (4.iota.map!(i => D[i] % 2).sum == 4) {
        int tmp = 1 << 29;
        foreach (a; A) if (a[0] != a[2]) tmp = min(tmp, a[1]);
        ans -= tmp;
    }

    ans.writeln;
}

class UnionFind {
    int N;
    int[] table;

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

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

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