You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

In the first line of the output print one integer $$$r$$$ — the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;

    auto T = ["RGB", "RBG", "GRB", "GBR", "BRG", "BGR"];
    int minv = 1 << 29;
    int mink = -1;

    foreach (k; 0..6) {
        int v = 0;
        foreach (i; 0..N) {
            if (S[i] != T[k][i%3]) {
                v += 1;
            }
        }
        if (v < minv) {
            minv = v;
            mink = k;
        }
    }

    minv.writeln;
    foreach (i; 0..N) {
        write(T[mink][i%3]);
    }
    writeln;
}


Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.

The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.  The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.

Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.

NoteFor the first sample test, the graph looks like this:    Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this:    We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.

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

__gshared:

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

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

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

struct Dsu(int n) {
    int[n] p, size, count;
    bool[n] cap;

    int get(int x) {
        return x == p[x]? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        x = get(x);
        y = get(y);
        if (x != y) {
            p[x] = y;
            size[y] += size[x];
            count[y] += count[x] + 1;
        } else
            count[y]++;
    }
}

int n, m, k;
int[1000] _caps;
Dsu!1000 dsu;

void main() {
    while (read(&n, &m, &k)) {
        auto caps = _caps[0 .. k];
        foreach (ref x; caps) {
            read(&x);
            x--;
        }
        iota(0, n).copy(dsu.p[ ]);
        repeat(1, n).copy(dsu.size[ ]);
        memset(dsu.count.ptr, 0x00, dsu.count.sizeof);
        memset(dsu.cap.ptr, 0x00, dsu.cap.sizeof);
        while (m--) {
            int a, b;
            read(&a, &b);
            a--;
            b--;
            dsu.merge(a, b);
        }
        foreach (x; caps)
            dsu.cap[dsu.get(x)] = true;
        int result = 0;
        int best = 0;
        foreach (i; 0 .. n) {
            int x = dsu.get(i);
            if (dsu.cap[x])
                best = max(best, dsu.size[x]);
            int total = dsu.size[x] * (dsu.size[x] - 1) >> 1;
            debug writefln("%s %s %s %s", result, dsu.size[x], total, dsu.count[x]);
            result += total - dsu.count[x];
            dsu.count[x] = total;
        }
        foreach (i; 0 .. n) {
            int x = dsu.get(i);
            if (!dsu.cap[x]) {
                result -= dsu.size[x] * (dsu.size[x] - 1) >> 1;
                foreach (j; 0 .. dsu.size[x]) {
                    result += best;
                    best++;
                }
                dsu.cap[x] = true;
            }
        }
        writeln(result);
        debug writeln();
    }
}

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;
	int m;
	int k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto c = new bool [n];
		foreach (i; 0..k)
		{
			int u;
			readf (" %s", &u);
			u -= 1;
			c[u] = true;
		}

		auto a = new int [] [n];
		foreach (j; 0..m)
		{
			int u;
			int v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto b = new bool [n];
		int vertices;

		bool recur (int v)
		{
			if (b[v])
			{
				return false;
			}
			b[v] = true;
			vertices += 1;
			bool ok = c[v];
			foreach (u; a[v])
			{
				ok |= recur (u);
			}
			return ok;
		}

		long res = -m;
		int largest = 0;
		int add = 0;
		for (int i = 0; i < n; i++)
		{
			if (!b[i])
			{
				vertices = 0;
				bool ok = recur (i);
				if (ok)
				{
					res += vertices * 1L *
					    (vertices - 1) / 2;
					largest = max (largest, vertices);
				}
				else
				{
					add += vertices;
				}
			}
		}
		add += largest;
		res += add * 1L * (add - 1) / 2;
		res -= largest * 1L * (largest - 1) / 2;

		writeln (res);
	}
}

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

__gshared:

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

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

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

struct Dsu(int n) {
    int[n] p, size, count;
    bool[n] cap;

    int get(int x) {
        return x == p[x]? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        x = get(x);
        y = get(y);
        if (x != y) {
            p[x] = y;
            size[y] += size[x];
            count[y] += count[x] + 1;
        } else
            count[y]++;
    }
}

int n, m, k;
int[1000] _caps;
Dsu!1000 dsu;

void main() {
    while (read(&n, &m, &k)) {
        auto caps = _caps[0 .. k];
        foreach (ref x; caps) {
            read(&x);
            x--;
        }
        iota(0, n).copy(dsu.p[ ]);
        repeat(1, n).copy(dsu.size[ ]);
        memset(dsu.count.ptr, 0x00, dsu.count.sizeof);
        memset(dsu.cap.ptr, 0x00, dsu.cap.sizeof);
        while (m--) {
            int a, b;
            read(&a, &b);
            a--;
            b--;
            dsu.merge(a, b);
        }
        foreach (x; caps)
            dsu.cap[dsu.get(x)] = true;
        int result = 0;
        int best = 0;
        foreach (i; 0 .. n) {
            int x = dsu.get(i);
            if (dsu.cap[x])
                best = max(best, dsu.size[x]);
            int total = dsu.size[x] * (dsu.size[x] - 1) >> 1;
            debug writefln("%s %s %s %s", result, dsu.size[x], total, dsu.count[x]);
            result += total - dsu.count[x];
            dsu.count[x] = total;
        }
        foreach (i; 0 .. n) {
            int x = dsu.p[i];
            if (!dsu.cap[x]) {
                result -= dsu.size[x] * (dsu.size[x] - 1) >> 1;
                foreach (j; 0 .. dsu.size[x]) {
                    result += best;
                    best++;
                }
            }
        }
        writeln(result);
        debug writeln();
    }
}


You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 109; 0 ≤ p ≤ q ≤ 109; y > 0; q > 0). It is guaranteed that p / q is an irreducible fraction. Hacks. For hacks, an additional constraint of t ≤ 5 must be met.

For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.

NoteIn the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,
	core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	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;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	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;
	}
	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;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto 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;
}
bool read(T...)(auto 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;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int t;
loop:while(read(t))
	{
		foreach(ii;0..t)
		{
			long x,y,p,q;
			read(x,y,p,q);
			long l=0,r=int.max;
			while(l<r)
			{
				long m=(l+r)>>1;
				if(p*m-x<=q*m-y && p*m-x>=0)r=m;
				else l=m+1;
			}
			if(l==int.max)writeln(-1);
			else writeln(l*q-y);
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const X = readLong();
        const Y = readLong();
        const P = readLong();
        const Q = readLong();

        long ans;
        if (P == 0) {
          ans = (X == 0) ? 0 : -1;
        } else if (Q - P == 0) {
          ans = (Y - X == 0) ? 0 : -1;
        } else {
          long mx;
          chmax(mx, (X + P - 1) / P);
          chmax(mx, ((Y - X) + (Q - P) - 1) / (Q - P));
          ans = (mx * P - X) + (mx * (Q - P) - (Y - X));
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $$$n$$$ bosses in this tower, numbered from $$$1$$$ to $$$n$$$. The type of the $$$i$$$-th boss is $$$a_i$$$. If the $$$i$$$-th boss is easy then its type is $$$a_i = 0$$$, otherwise this boss is hard and its type is $$$a_i = 1$$$.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.For example: suppose $$$n = 8$$$, $$$a = [1, 0, 1, 1, 0, 1, 1, 1]$$$. Then the best course of action is the following:  your friend kills two first bosses, using one skip point for the first boss;  you kill the third and the fourth bosses;  your friend kills the fifth boss;  you kill the sixth and the seventh bosses;  your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of bosses. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th boss. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    int n;
    n = rd!int;
    int[] arr = rdarr!int;
    int[][] dp = new int[][](2, n+1);
    if(n == 1){
        writeln(to!int(arr[0] == 1));
        return;
    }
    dp[1][0] = arr[0];
    dp[1][1] = dp[1][0] + arr[1];
    dp[0][0] = to!int(1e8);
    dp[0][1] = dp[1][0];
    foreach(i; 2..(n)){
        dp[0][i] = min(dp[1][i-2], dp[1][i-1]);
        dp[1][i] = min(arr[i-1] + dp[0][i-2], dp[0][i-1]) + arr[i];
    }
    int res = min(dp[1][n-1], dp[0][n-1]);
    /* writeln(dp); */
    writeln(res);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    int n;
    n = rd!int;
    int[] arr = rdarr!int;
    int[][] dp = new int[][](2, n+1);
    if(n == 1){
        writeln(to!int(arr[0] == 1));
        return;
    }
    dp[1][0] = arr[0];
    dp[1][1] = dp[1][0] + arr[1];
    dp[0][0] = to!int(1e7);
    dp[0][1] = dp[1][0];
    foreach(i; 2..(n)){
        dp[0][i] = min(dp[1][i-2], dp[1][i-1]);
        dp[1][i] = min(arr[i-1] + dp[0][i-2], dp[0][i-1]) + arr[i];
    }
    int res = min(dp[1][n-1], dp[0][n-1]);
    /* writeln(dp); */
    writeln(res);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto dp = new int[][](n+1, 2);
		foreach (i; 0..dp.length)
		{
			dp[i][] = n;
		}
		dp[0][0] = 0;

		foreach (i; 0..n)
		{
			dp[i+1][1].chmin(dp[i][0]+a[i]);
			if (i < n-1)
				dp[i+2][1].chmin(dp[i][0]+a[i]+a[i+1]);
			dp[i+1][0].chmin(dp[i][1]);
			if (i < n-1)
				dp[i+2][0].chmin(dp[i][1]);
		}

		ans[ti] = min(dp[n][0], dp[n][1]);
	}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    int n;
    n = rd!int;
    int[] arr = rdarr!int;
    int[][] dp = new int[][](2, n+1);
    if(n == 1){
        writeln(to!int(arr[0] == 1));
    }

    dp[1][0] = arr[0];
    dp[1][1] = dp[1][0] + arr[1];
    dp[0][0] = to!int(1e7);
    dp[0][1] = dp[1][0];
    foreach(i; 2..(n)){
        dp[0][i] = min(dp[1][i-2], dp[1][i-1]);
        dp[1][i] = min(arr[i-1] + dp[0][i-2], dp[0][i-1]) + arr[i];
    }
    int res = min(dp[1][n-1], dp[0][n-1]);
    /* writeln(dp); */
    writeln(res);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    int n;
    n = rd!int;
    int[] arr = rdarr!int;
    int[][] dp = new int[][](2, n);
    int pt = (arr[0] == 1);
    dp[1][0] = pt;
    dp[0][0] = to!int(1e8);
    foreach(i; 1..(n)){
        dp[0][i] = dp[1][i-1];
        dp[1][i] = dp[1][i-1] + (arr[i] == 1);
        if(i > 1){
            dp[0][i] = min(dp[1][i-2], dp[1][i]);
            dp[1][i] = min((arr[i-1] == 1) + dp[0][i-2], dp[0][i-1]) + (arr[i] == 1);
        }
    }
    int res = min(dp[1][n-1], dp[0][n-1]);
    if(n == 1){ res = pt; }
    /* writeln(dp); */
    writeln(res);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int i;
		bool turn;
		while (i < n)
		{
			if (turn)
			{
				++i;
				if (i < n)
				{
					if (a[i] == 1)
						++i;
				}
				turn = !turn;
			}
			else
			{
				if (a[i] == 1)
				{
					++ans[ti];
				}
				++i;
				if (i < n)
				{
					if (a[i] == 0)
						++i;
				}
				turn = !turn;
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		int i;
		bool turn;
		while (i < n)
		{
			if (turn)
			{
				i += 2;
				turn = !turn;
			}
			else
			{
				if (a[i] == 1)
				{
					++ans[ti];
				}
				++i;
				if (i < n)
				{
					if (a[i] == 0)
						++i;
				}
				turn = !turn;
			}
		}
	}

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


There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.

The first line of the input contains one integer $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) — the size of the chessboard. The second line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to an enemy pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. The third line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to a Gregor's pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. It is guaranteed that the sum of $$$n$$$ across all test cases is less than $$$2\cdot{10}^{5}$$$.

For each test case, print one integer: the maximum number of Gregor's pawns which can reach the $$$1$$$-st row.

NoteIn the first example, Gregor can simply advance all $$$3$$$ of his pawns forward. Thus, the answer is $$$3$$$.In the second example, Gregor can guarantee that all $$$4$$$ of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"!  In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly $$$0$$$.

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto used = new bool[](n);
		foreach (i; 0..n)
		{
			if (b[i] == '0') continue;
			if (a[i] == '0')
			{
				++ans[ti];
				continue;
			}
			if (i != 0)
			{
				if (used[i-1] == false && a[i-1] == '1')
				{
					used[i-1] = true;
					++ans[ti];
					continue;
				}
			}
			if (i != n-1)
			{
				if (used[i+1] == false && a[i+1] == '1')
				{
					used[i+1] = true;
					++ans[ti];
					continue;
				}
			}
		}
	}

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


You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.

The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.   In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.  In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.  In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.

Output the answer with absolute or relative error no more than 1e - 9.

NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability  we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability  the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto p = new int [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
			x--;
		}

		if (n < 2)
		{
			writeln (0);
			continue;
		}

		auto f = new real [] [] [] (2, n, n);
		int d = 0;
		foreach (ref g; f[d])
		{
			g[] = 0.0;
		}
		foreach (a; 0..n - 1)
		{
			foreach (b; a + 1..n)
			{
				if (p[a] < p[b])
				{
					f[d][b][a] += 1.0;
				}
				else
				{
					f[d][a][b] += 1.0;
				}
			}
		}

		real total = 2.0 / n / (n + 1);
		foreach (t; 0..k)
		{
			d ^= 1;
			foreach (ref g; f[d])
			{
				g[] = 0.0;
			}
			foreach (lo; 0..n)
			{
				foreach (hi; lo..n)
				{
					auto z = n.iota.array;
					reverse (z[lo..hi + 1]);
					foreach (a; 0..n)
					{
						foreach (b; 0..n)
						{
							f[d][z[a]][z[b]] +=
							    f[!d][a][b];
						}
					}
				}
			}

			foreach (a; 0..n)
			{
				foreach (b; 0..n)
				{
					f[d][a][b] *= total;
				}
			}
		}

		real answer = 0;
		foreach (a; 0..n - 1)
		{
			foreach (b; a + 1..n)
			{
				answer += f[d][a][b];
			}
		}
		writefln ("%.20f", answer);
	}
}

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

int mul(int n)
{
    auto res = 1;
    foreach (i; 2 .. n + 1)
    {
        res *= i;
    }
    return res;
}

int calc(int[] p)
{
    auto n = cast(int)p.length;
    auto f = new bool[n + 1];
    fill(f, false);
    auto res = 0;
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        foreach (j; 1 .. p[i])
        {
            if (!f[j])
            {
                ++ cnt;
            }
        }
        res += cnt * mul(n - i - 1);
        f[p[i]] = true;
    }
    return res;
}

int countReverse(int[] p)
{
    auto res = 0;
    foreach (i; 0 .. p.length)
    {
        foreach (j; i + 1 .. p.length)
        {
            if (p[i] > p[j])
            {
                ++ res;
            }
        }
    }
    return res;
}

void reverse(int[] p, int left, int right)
{
    while (left < right)
    {
        swap(p[left], p[right]);
        ++ left;
        -- right;
    }
}

double saiki(int[] p, int n, int c, int k, double[][] dp)
{
    auto r = calc(p);
    if (dp[r][c] != -1)
    {
        return dp[r][c];
    }
    if (c == k)
    {
        auto cnt = countReverse(p);
        dp[r][c] = cnt;
        return cnt;
    }
    auto res = 0.0;
    auto prob = 1.0 / ((1 + n) * n / 2);
    foreach (i; 0 .. n)
    {
        foreach (j; i .. n)
        {
            reverse(p, i, j);
            auto ret = saiki(p, n, c + 1, k, dp);
            res += prob * ret;
            reverse(p, i, j);
        }
    }
    dp[r][c] = res;
    return res;
}

void solve(int[] p, int n, int k)
{
    auto r = mul(n);
    auto dp = new double[][](r + 1, k + 1);
    foreach (i; 0 .. r + 1)
    {
        fill(dp[i], -1);
    }
    auto ans = saiki(p, n, 0, k, dp);
    writefln("%.10f", ans);
}

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

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

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

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

    DList!(Tuple!(int, int[])) arrs;
    arrs ~= tuple(k, arr);

    while (!arrs.empty && arrs.front[0] > 0) {
        auto cur = arrs.front;
        arrs.removeFront();

        foreach (i; 0 .. n) {
            foreach (j; i .. n) {
                debug { writeln(i, ' ', j); }
                auto rev = cur[1].dup;
                for (int le = i, r = j; le < r; ++le, --r) { swap(rev[le], rev[r]); }

                arrs ~= tuple(cur[0] - 1, rev);
            }
        }
    }

    debug { arrs.each!writeln; }

    long invsum = 0;
    foreach (a; arrs) {
        auto cur = a[1];
        foreach (i; 0 .. n) {
            foreach (j; i+1 .. n) {
                if (cur[i] > cur[j]) { ++invsum; }
            }
        }
    }

    auto ans = invsum.to!double / arrs.array.length;
    ans.writefln!"%.12f";
}

import std.algorithm;
import std.stdio;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto p = new int [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
			x--;
		}

		real total = 0;
		real answer = 0;

		real calc ()
		{
			int res = 0;
			foreach (i; 0..n - 1)
			{
				foreach (j; i + 1..n)
				{
					res += (p[i] > p[j]);
				}
			}
			return res;
		}

		void recur (int d)
		{
			if (d == 0)
			{
				total += 1;
				answer += calc ();
				return;
			}

			foreach (i; 0..n)
			{
				foreach (j; i..n)
				{
					reverse (p[i..j + 1]);
					recur (d - 1);
					reverse (p[i..j + 1]);
				}
			}
		}

		recur (k);
		writefln ("%.20f", answer / total);
	}
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto p = new int [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
			x--;
		}

		if (n < 2)
		{
			writeln (0);
			continue;
		}

		auto f = new real [] [] [] (2, n, n);
		int d = 0;
		foreach (ref g; f[d])
		{
			g[] = 0.0;
		}
		foreach (a; 0..n - 1)
		{
			foreach (b; a + 1..n)
			{
				if (p[a] < p[b])
				{
					f[d][b][a] += 1.0;
				}
				else
				{
					f[d][a][b] += 1.0;
				}
			}
		}

		real total = 1.0 / n / (n - 1);
		foreach (t; 0..k)
		{
			d ^= 1;
			foreach (ref g; f[d])
			{
				g[] = 0.0;
			}
			foreach (lo; 0..n)
			{
				foreach (hi; lo..n)
				{
					auto z = n.iota.array;
					reverse (z[lo..hi + 1]);
					foreach (a; 0..n)
					{
						foreach (b; 0..n)
						{
							f[d][z[a]][z[b]] +=
							    f[!d][a][b];
						}
					}
				}
			}

			foreach (a; 0..n)
			{
				foreach (b; 0..n)
				{
					f[d][a][b] *= total;
				}
			}
		}

		real answer = 0;
		foreach (a; 0..n - 1)
		{
			foreach (b; a + 1..n)
			{
				answer += f[d][a][b];
			}
		}
		writefln ("%.20f", answer);
	}
}


Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.

Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000.

/+ dub.sdl:
    name "B"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner, dcomp.array;
import std.typecons;
import std.container.rbtree;

int main() {
    auto sc = new Scanner(stdin);
    int n, k;
    int[] a;
    sc.read(n, k, a); a[] -= 1;

    int[][] l = new int[][n];
    foreach (int i, d; a) {
        l[d] ~= i;
    }
    l.each!((ref v) => v ~= n);
    auto used = new bool[n];
    int sm = 0;

    auto tr = redBlackTree!(int[2]);
    foreach (d; a) {
        int ba = l[d][0];
        l[d] = l[d][1..$];
        int nx = l[d][0];
        if (used[d]) {
            tr.removeKey([ba, d].fixed);
            tr.insert([nx, d].fixed);
            continue;
        }
        // add d
        if (tr.length == k) {
            auto u = tr.back();
            tr.removeBack();
            used[u[1]] = false;
        }
        sm++;
        tr.insert([nx, d].fixed);
        used[d] = true;
    }
    writeln(sm);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

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

struct FastAppender(A) {
    import std.algorithm : max;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

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

    @property size_t length() {return len;}

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

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

        cap = nlen;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool 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;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        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 {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

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

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    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);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}

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

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

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

    auto nxtpos = new int[] (n+1);
    auto lst = new int[] (n+1);
    lst[] = n+1;

    foreach_reverse (i, e; arr) {
        nxtpos[i] = lst[e];
        lst[e] = i.to!int;
    }

    int ans = 0;
    auto rbt = make!(RedBlackTree!(Tuple!(int, int)));
    auto nxtel = new int[] (n+1);
    foreach (i, e; arr) {
        auto cur = tuple(nxtel[e], e);

        if (cur in rbt) {
            rbt.removeKey(cur);
            nxtel[e] = nxtpos[i];
            rbt.insert(tuple(nxtel[e], e));
            continue;
        }

        if (rbt.length() < k) {
            nxtel[e] = nxtpos[i];
            ans += 1;
            rbt.insert(tuple(nxtel[e], e));
            continue;
        }

        rbt.removeBack();
        nxtel[e] = nxtpos[i];
        ans += 1;
        rbt.insert(tuple(nxtel[e], e));
    }

    ans.writeln;
}

/+ dub.sdl:
    name "B"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner, dcomp.array;
import std.typecons;
import std.container.rbtree;

int main() {
    auto sc = new Scanner(stdin);
    int n, k;
    int[] a;
    sc.read(n, k, a); a[] -= 1;

    int[][] l = new int[][n];
    foreach (int i, d; a) {
        l[d] ~= i;
    }
    l.each!((ref v) => v ~= n);
    auto used = new bool[n];
    int sm = 0;

    auto tr = redBlackTree!(int[2]);
    foreach (d; a) {
        int ba = l[d][0];
        l[d] = l[d][1..$];
        int nx = l[d][0];
        if (used[d]) {
            tr.removeKey([d, ba].fixed);
            tr.insert([d, nx].fixed);
            continue;
        }
        // add d
        if (tr.length == k) {
            auto u = tr.back();
            tr.removeBack();
            used[u[1]] = false;
        }
        sm++;
        tr.insert([nx, d].fixed);
        used[d] = true;
    }
    writeln(sm);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

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

struct FastAppender(A) {
    import std.algorithm : max;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

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

    @property size_t length() {return len;}

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

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

        cap = nlen;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool 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;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        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 {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

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

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    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);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}

/+ dub.sdl:
    name "B"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner, dcomp.array;
import std.typecons;
import std.container.rbtree;

int main() {
    auto sc = new Scanner(stdin);
    int n, k;
    int[] a;
    sc.read(n, k, a); a[] -= 1;

    int[][] l = new int[][n];
    foreach (int i, d; a) {
        l[d] ~= i;
    }
    l.each!((ref v) => v ~= n);
    auto used = new bool[n];
    int sm = 0;

    auto tr = redBlackTree!(int[2]);
    foreach (d; a) {
        l[d] = l[d][1..$];
        int nx = l[d][0];
        if (used[d]) continue;
        // add d
        if (tr.length == k) {
            auto u = tr.back();
            tr.removeBack();
            used[u[1]] = false;
        }
        sm++;
        tr.insert([nx, d].fixed);
        used[d] = true;
    }
    writeln(sm);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

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

struct FastAppender(A) {
    import std.algorithm : max;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

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

    @property size_t length() {return len;}

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

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

        cap = nlen;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool 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;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        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 {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

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

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    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);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}


A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.The fare is constructed in the following manner. There are three types of tickets:   a ticket for one trip costs 20 byteland rubles,  a ticket for 90 minutes costs 50 byteland rubles,  a ticket for one day (1440 minutes) costs 120 byteland rubles. Note that a ticket for x minutes activated at time t can be used for trips started in time range from t to t + x - 1, inclusive. Assume that all trips take exactly one minute.To simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is a, and the total sum charged before is b. Then the system charges the passenger the sum a - b.You have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip.

The first line of input contains integer number n (1 ≤ n ≤ 105) — the number of trips made by passenger. Each of the following n lines contains the time of trip ti (0 ≤ ti ≤ 109), measured in minutes from the time of starting the system. All ti are different, given in ascending order, i. e. ti + 1 > ti holds for all 1 ≤ i < n.

Output n integers. For each trip, print the sum the passenger is charged after it.

NoteIn the first example, the system works as follows: for the first and second trips it is cheaper to pay for two one-trip tickets, so each time 20 rubles is charged, after the third trip the system understands that it would be cheaper to buy a ticket for 90 minutes. This ticket costs 50 rubles, and the passenger had already paid 40 rubles, so it is necessary to charge 10 rubles only.

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

immutable int infinity = 0x3F3F3F3F;
immutable int maxDelta = 1441;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int prevT = -10_000;
		auto f = new int [] [] (2, maxDelta);
		int b = 0;
		f[b][] = infinity;
		f[b][0] = 0;
		foreach (i; 0..n)
		{
			int t;
			readf (" %s", &t);
			int delta = t - prevT;
			b ^= 1;
			f[b][] = infinity;
			foreach (s; delta + 1..maxDelta)
			{
				f[b][s - delta] = f[!b][s];
			}
			int prevW = f[!b].reduce !(min);
			f[b][0] = min (f[b][0], prevW + 20);
			f[b][90] = min (f[b][90], prevW + 50);
			f[b][1440] = min (f[b][1440], prevW + 120);
			int w = f[b].reduce !(min);
			writeln (w - prevW);
			prevT = t;
			prevW = w;
		}
	}
}


Given two integers $$$n$$$ and $$$x$$$, construct an array that satisfies the following conditions:   for any element $$$a_i$$$ in the array, $$$1 \le a_i<2^n$$$;  there is no non-empty subsegment with bitwise XOR equal to $$$0$$$ or $$$x$$$,  its length $$$l$$$ should be maximized. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The only line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 18$$$, $$$1 \le x<2^{18}$$$).

The first line should contain the length of the array $$$l$$$. If $$$l$$$ is positive, the second line should contain $$$l$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\dots$$$, $$$a_l$$$ ($$$1 \le a_i < 2^n$$$) — the elements of the array $$$a$$$. If there are multiple solutions, print any of them.

NoteIn the first example, the bitwise XOR of the subsegments are $$$\{6,7,4,1,2,3\}$$$.

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

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto X = s[1];

    if (N == 1 && X == 1) {
        writeln(0);
        return;
    }
    if (N == 1) {
        writeln(1);
        writeln(1);
        return;
    }

    auto Y = N.iota.filter!(i => bsr(X) != i).map!(i => 1 << i).array;
    int[] ans;

    void dfs(int idx) {
        if (idx == 0) {
            ans ~= Y[idx];
            return;
        }
        dfs(idx-1);
        ans ~= Y[idx];
        dfs(idx-1);
    }

    dfs(Y.length.to!int-1);
    ans.length.writeln;
    ans.map!(to!string).join(" ").writeln;
}

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

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

    auto isFree = new bool[] (2^^n + 1);
    isFree[] = true;
    isFree[0] = false;
    if (x < 2^^n) { isFree[x] = false; }

    int nextFreeVal(int idx) {
        while (!isFree[idx]) { ++idx; }
        return idx;
    }

    int sm = 0;
    int[] ans;
    int nxtsm = 1;
    while ((nxtsm = nextFreeVal(nxtsm)) < 2^^n && (sm ^ nxtsm) < 2^^n) {
        ans ~= sm ^ nxtsm;
        sm = nxtsm;
        isFree[sm] = false;
        if ((sm ^ x) < 2^^n) { isFree[sm ^ x] = false; }
    }

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

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

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

    auto isFree = new bool[] (2^^n + 1);
    isFree[] = true;
    isFree[0] = false;
    if (x < 2^^n) { isFree[x] = false; }

    int nextFreeVal(int idx) {
        while (!isFree[idx]) { ++idx; }
        return idx;
    }

    int sm = 0;
    int[] ans;
    int nxtsm = 1;
    while ((nxtsm = nextFreeVal(nxtsm)) < 2^^n && (sm ^ nxtsm) < 2^^n) {
        isFree[nxtsm] = false;
        if ((x ^ nxtsm) < 2^^n) { isFree[nxtsm ^ x] = false; }
        ans ~= sm ^ nxtsm;
        sm = nxtsm;
    }

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

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

void main() {
  int n, x;
  readf!" %d %d" (n, x);
  immutable m = 1 << n;
  int[] s;
  auto t = redBlackTree!int ();
  foreach (i; 1 .. m) {
    if (i != x) {
      t.insert (i);
    }
  }
  while (!t.empty) {
    int i = t.front;
    s ~= i;
    t.removeFront();
    t.removeKey (i ^ x);
  }
  if (!s.length) {
    writeln (0);
    return;
  }
  auto a = new int[s.length];
  a[0] = s[0];
  foreach (i; 1 .. s.length) {
    a[i] = s[i] ^ s[i-1];
  }
  debug stderr.writeln (s);
  writeln (a.length);
  writefln ("%(%s %)", a);
}

module D;

import std.typecons;
import core.stdc.stdio;
import std.stdio;
import std.algorithm;
import std.range;
import std.container.rbtree;

alias PII = Tuple!(int, int);
alias PLL = Tuple!(long, long);

void main()
{
    int n, x;
    scanf("%d%d", &n, &x);

    bool[int] mm;

    int[] ans;
    mm[0] = true;
    mm[x] = true;

    int prefix = 0;

    foreach (i; 1 .. (1 << n))
    {
        if (i !in mm)
        {
            ans ~= (i ^ prefix);

            prefix = i;
            mm[prefix] = true;
            mm[prefix ^ x] = true;

        }
    }

    writeln(ans.length);
    if (ans.length > 0)
        writefln("%(%d%| %)", ans);
}


Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$; $$$1 \le x \le 10^4$$$) — the number of gold pieces that Phoenix has and the weight to avoid, respectively.  The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \le w_i \le 100)$$$ — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.

For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.

NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode.

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}

void solve()
{
	int n = readInt!int;
	int x = readInt!int;
	auto a = new int[](n); foreach(ref ai; a) ai = readInt!int;
	int acc = 0;
	foreach(i, ref ai; a)
	{
		acc += ai;
		if (acc == x)
		{
			if (i + 1 < n)
			{
				swap(a[i+1], a[i]);
			}
			else
			{
				return "NO".writeln;
			}
		}
	}
	"YES".writeln;
	foreach(ai; a) ai.write(" "); writeln; return;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	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;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n, x;
        readf!"%d %d\n"(n, x);
        int[] w = readln.split.map!(to!int).array;
        if (w.sum == x)
            writeln("NO");
        else
        {
            writeln("YES");
            foreach (i; 0 .. n)
            {
                if (x == w[i])
                    swap(w[i], w[i + 1]);
                writef!"%d "(w[i]);
                x -= w[i];
            }
            writeln();
        }
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		if (x == 0 || x == sum (a) || (a.minElement == a.maxElement &&
		    0 < x && x < sum (a) && x % a[0] == 0))
		{
			writeln ("NO");
			continue;
		}
		while (true)
		{
			randomShuffle (a);
			bool ok = true;
			int cur = 0;
			foreach (ref c; a)
			{
				cur += c;
				ok &= (cur != x);
			}
			if (ok)
			{
				writeln ("YES");
				writefln !("%(%s %)") (a);
				break;
			}
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long tot;
		while (!w.empty)
		{
			long y;
			if (tot+w.front != x)
			{
				y = w.front; w.popFront;
			}
			else
			{
				y = w.back; w.popBack;
			}
			tot += y;
			ans[ti] ~= y;
		}
		if (tot == x)
			ans[ti].length = 0;
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}


Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $$$\ell$$$ letters long. So, the scientists decided to write each word of this language as an integer from $$$0$$$ to $$$2^{\ell} - 1$$$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $$$1001_2$$$ and $$$1100_2$$$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $$$x$$$ and $$$y$$$ as $$$d(x, y)$$$.Let the word have $$$n$$$ forms, the $$$i$$$-th of which is described with an integer $$$x_i$$$. All the $$$x_i$$$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $$$y$$$. Then, closeness of the word $$$y$$$ is equal to the sum of distances to each of the word forms, i. e. the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$.The initial form is the word $$$y$$$ with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the $$$n$$$ given forms.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains two integers $$$n$$$ and $$$\ell$$$ ($$$1 \le n \le 100$$$, $$$1 \le \ell \le 30$$$) — the amount of word forms, and the number of letters in one word. The second line contains $$$n$$$ integers $$$x_i$$$ ($$$0 \le x_i \le 2^\ell - 1$$$) — word forms. The integers are not necessarily different.

For each test, print a single integer, the initial form of the word, i. e. such $$$y$$$ ($$$0 \le y \le 2^\ell - 1$$$) that the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$ is minimal possible. Note that $$$y$$$ can differ from all the integers $$$x_i$$$. If there are multiple ways to restore the initial form, print any.

NoteIn the first test case, the words can be written as $$$x_1 = 10010_2$$$, $$$x_2 = 01001_2$$$ and $$$x_3 = 10101_2$$$ in binary. Let $$$y = 10001_2$$$. Then, $$$d(x_1, y) = 2$$$ (the difference is in the fourth and the fifth positions), $$$d(x_2, y) = 2$$$ (the difference is in the first and the second positions), $$$d(x_3, y) = 1$$$ (the difference is in the third position). So, the closeness is $$$2 + 2 + 1 = 5$$$. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to $$$18$$$ ($$$10010_2$$$ in binary), so the initial form is also $$$18$$$. It's easy to see that closeness is equal to zero in this case.

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        immutable n = read!(uint, " ");
        immutable l = read!(uint, "\n");

        immutable vec =
            readln.chomp.split(' ')
            .to!(uint[]);

        iota(0, l)
            .map!(bit =>
                        vec.count!(x => cast(bool)(x & (1 << bit)))
                        > n / 2)
            .array
            .to!BitArray
            .opCast!(size_t[])
            .front
            .writeln;
    }
}
// ""

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		auto cnt = new long[](l);
		foreach (i; 0..n)
		{
			foreach (j; 0..l)
			{
				auto bit = 1L << j;
				if (x[i] & bit)
					++cnt[j];
			}
		}

		foreach (i; 0..l)
		{
			auto bit = 1L << i;
			if (cnt[i] >= (n+1)/2)
				ans[ti] |= bit;
		}
	}

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

void main() { runSolver(); }

void problem() {
  auto QN = scan!long;

  auto solve() {
    foreach(_; 0..QN) {
      auto N = scan!int;
      auto L = scan!int;
      auto A = scan!long(N);

      long[] bits;
      foreach(i; 0..L) {
        long count;
        foreach(ref a; A) {
          if (a % 2 == 1) count++;
          a /= 2;
        }

        bits ~= count > N / 2 ? 1 : 0;
      }

      long ans;
      foreach_reverse(b; bits) {
        ans *= 2;
        ans += b;
      }

      ans.writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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


Alice and Bob are playing a game. There are $$$n$$$ cells in a row. Initially each cell is either red or blue. Alice goes first.On each turn, Alice chooses two neighbouring cells which contain at least one red cell, and paints that two cells white. Then, Bob chooses two neighbouring cells which contain at least one blue cell, and paints that two cells white. The player who cannot make a move loses.Find the winner if both Alice and Bob play optimally.Note that a chosen cell can be white, as long as the other cell satisfies the constraints.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. For each test case, the first line contains an integer $$$n$$$ ($$$2 \leq n \leq 5 \cdot 10^5$$$) — the number of cells. The second line contains a string $$$s$$$ of length $$$n$$$ — the initial state of the cells. The $$$i$$$-th cell is red if $$$s_i = $$$ R, blue if $$$s_i = $$$ B. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.

For each test case, output the name of the winner on a separate line.

8

3

BRB

5

RRBBB

6

RBRBRB

8

BBRRBRRB

6

BRRBRB

12

RBRBRBRBRRBB

12

RBRBRBRBBBRR

4

RBBR

NoteIn the notes, the cell numbers increase from left to right.In the first testcase for Alice, she has two choices: paint the first and the second cells, or paint the second and the third cells. No matter what choice Alice makes, there will be exactly one blue cell after Alice's move. Bob just needs to paint the blue cell and its neighbour, then every cell will be white and Alice can't make a move. So Bob is the winner.In the second testcase no matter what Alice chooses, Bob can choose to paint the fourth and fifth cells in $$$2$$$ turns.In the third testcase at first, Alice paints the third and the fourth cells. It doesn't matter if Bob paints the first and the second cells or the fifth and sixth cells, as Alice can paint the other two cells.In the fourth testcase at first, Alice paints the second and the third cells. If Bob paints the fifth and the sixth cells or the fourth and the fifth cells, then Alice paints the seventh and the eighth cells. If Bob paints the seventh and the eighth cells, then Alice paints the fifth and the sixth cells.In the fifth Alice chooses the middle two cells at first, then Bob obviously has only two options, whichever variant he chooses, Alice can choose the other one and win.In the eighth no matter what Alice chooses, Bob can choose the other two symmetrical cells.

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

// https://oeis.org/A002187
enum LIM = 1000;
enum PER = 34;
int[] gs;
void init() {
  gs = new int[LIM];
  foreach (n; 0 .. LIM) {
    bool[int] app;
    for (int k = 0; k <= n - 2 - k; ++k) {
      app[gs[k] ^ gs[n - 2 - k]] = true;
    }
    for (int x = 0; ; ++x) {
      if (x !in app) {
        gs[n] = x;
        break;
      }
    }
  }
  debug {
    writeln("gs = ", gs);
  }
  foreach (n; LIM / 2 .. LIM) {
    assert(gs[n - PER] == gs[n]);
  }
}
int getG(int n) {
  if (n >= LIM) {
    n = (LIM - PER) + (n - (LIM - PER)) % PER;
  }
  return gs[n];
}

int N;
string S;

bool solve() {
  auto A = S.map!(s => ((s == 'B') ? 1 : 0)).array;
  int[2] cnt;
  foreach (i; 0 .. N) {
    ++cnt[A[i]];
  }
  if (cnt[0] > cnt[1]) return true;
  if (cnt[0] < cnt[1]) return false;

  int sum;
  for (int i = 0, j; i < N; i = j) {
    for (j = i; j < N && (A[i] ^ (i & 1)) == (A[j] ^ (j & 1)); ++j) {}
    const g = getG(j - i);
    debug {
      writeln("  ", S[i .. j], " ", g);
    }
    sum ^= g;
  }
  return (sum != 0);
}

void main() {
  /*
  debug {{
    foreach (n; 2 .. 8 + 1) {
      auto dp = new int[][](3^^n, 2);
      foreach (p; 0 .. 3^^n) {
        const s = iota(n).map!(i => "012"[p / 3^^i % 3]).array;
        foreach (turn; 0 .. 2) {
          const me = "12"[turn];
          bool[int] app;
          foreach (i; 0 .. n - 1) {
            if (s[i] == me || s[i + 1] == me) {
              int pp = p;
              pp -= (s[i] - '0') * 3^^i;
              pp -= (s[i + 1] - '0') * 3^^(i + 1);
              app[dp[pp][turn ^ 1]] = true;
            }
          }
          for (int x = 0; ; ++x) {
            if (x !in app) {
              dp[p][turn] = x;
              break;
            }
          }
        }
        int[2] cnt;
        foreach (turn; 0 .. 2) {
          cnt[turn] = cast(int)(s.count("12"[turn]));
        }
        if (cnt[0] > cnt[1]) {
          assert(dp[p][0]);
          assert(!dp[p][1]);
        } else if (cnt[0] < cnt[1]) {
          assert(!dp[p][0]);
          assert(dp[p][1]);
        } else {
          writeln(s, " ", dp[p]);
        }
      }
      stdout.flush;
    }
    return;
  }}
  */

  init;

  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        S = readToken;

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


Consider a square grid with $$$h$$$ rows and $$$w$$$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $$$998\,244\,353$$$.

The first line contains three integers $$$h$$$, $$$w$$$, and $$$n$$$ ($$$1 \le h, w \le 3600$$$; $$$0 \le n \le 2400$$$), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from $$$1$$$ to $$$h$$$, and the columns are numbered from $$$1$$$ to $$$w$$$. Each of the next $$$n$$$ lines contains four integers $$$r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2}$$$ ($$$1 \le r_{i, 1} \le r_{i, 2} \le h$$$; $$$1 \le c_{i, 1} \le c_{i, 2} \le w$$$), denoting the row id and the column id of the cells covered by the $$$i$$$-th domino. Cells $$$(r_{i, 1}, c_{i, 1})$$$ and $$$(r_{i, 2}, c_{i, 2})$$$ are distinct and share a common side. The given domino placement is perfectly balanced.

Output the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo $$$998\,244\,353$$$.

NoteIn the first example, the initial grid looks like this:Here are $$$8$$$ ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, 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 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;

enum LIM = 10005;
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);
  }
}

Mint[] dpIt(bool[] used) {
  const int n = cast(int)(used.length);
  auto dp = new Mint[][](n + 1, n / 2 + 1);
  dp[0][0] = 1;
  foreach (i; 0 .. n) {
    foreach (p; 0 .. i / 2 + 1) {
      dp[i + 1][p] += dp[i][p];
      if (i + 2 <= n && !used[i] && !used[i + 1]) {
        dp[i + 2][p + 1] += dp[i][p];
      }
    }
  }
  return dp[n];
}

void main() {
  prepare();
  try {
    for (; ; ) {
      const int H = readInt();
      const int W = readInt();
      const int N = readInt();
      auto R1 = new int[N];
      auto C1 = new int[N];
      auto R2 = new int[N];
      auto C2 = new int[N];
      foreach (i; 0 .. N) {
        R1[i] = readInt() - 1;
        C1[i] = readInt() - 1;
        R2[i] = readInt() - 1;
        C2[i] = readInt() - 1;
      }

      auto usedX = new bool[H];
      auto usedY = new bool[W];
      foreach (i; 0 .. N) {
        usedX[R1[i]] = usedX[R2[i]] = true;
        usedY[C1[i]] = usedY[C2[i]] = true;
      }

      const a = usedX.count(false);
      const b = usedY.count(false);
      auto dpX = usedX.dpIt;
      auto dpY = usedY.dpIt;
      debug {
        writeln("a = ", a);
        writeln("b = ", b);
        writeln("dpX = ", dpX);
        writeln("dpY = ", dpY);
      }

      Mint ans = 0;
      foreach (j; 0 .. a / 2 + 1) foreach (k; 0 .. b / 2 + 1) {
        if (2 * j + k <= a && j + 2 * k <= b) {
          Mint tmp = 1;
          tmp *= dpX[j];
          tmp *= binom(a - 2 * j, k);
          tmp *= dpY[k];
          tmp *= binom(b - 2 * k, j);
          tmp *= fac[j];
          tmp *= fac[k];
          ans += tmp;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}