Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :)Rick and Morty like to go to the ridge High Cry for crying loudly — there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them. Bitwise OR is a binary operation which is determined the following way. Consider representation of numbers x and y in binary numeric system (probably with leading zeroes) x = xk... x1x0 and y = yk... y1y0. Then z = x | y is defined following way: z = zk... z1z0, where zi = 1, if xi = 1 or yi = 1, and zi = 0 otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers 10 = 10102 and 9 = 10012 equals 11 = 10112. In programming languages C/C++/Java/Python this operation is defined as «|», and in Pascal as «or».Help Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs l and r (1 ≤ l < r ≤ n) such that bitwise OR of heights of all mountains between l and r (inclusive) is larger than the height of any mountain at this interval.

The first line contains integer n (1 ≤ n ≤ 200 000), the number of mountains in the ridge. Second line contains n integers ai (0 ≤ ai ≤ 109), the heights of mountains in order they are located in the ridge.

Print the only integer, the number of ways to choose two different mountains.

NoteIn the first test case all the ways are pairs of mountains with the numbers (numbering from one):(1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)In the second test case there are no such pairs because for any pair of mountains the height of cry from them is 3, and this height is equal to the height of any mountain.

import std.stdio;

static immutable int N = 200010;
uint n;
uint[N] pre, nxt;
long ans;
long[N] a;

int main() {
  readf(" %d", &n), ans = long(n - 1) * long(n) >> 1;
  for (uint i = 1; i <= n; ++ i) readf(" %d", &a[i]);
  for (uint i = 1; i <= n; ++ i) {
    pre[i] = i - 1;
    while (pre[i] && (a[i] | a[pre[i]]) == a[i]) pre[i] = pre[pre[i]];
  }
  for (uint i = n; i; -- i) {
    nxt[i] = i + 1;
    while (nxt[i] <= n && (a[i] | a[nxt[i]]) == a[i] && a[i] > a[nxt[i]]) nxt[i] = nxt[nxt[i]];
    ans -= long(nxt[i] - i) * long(i - pre[i]) - 1;
  }
  writeln(ans);
  return 0;
}

import std.stdio;

static immutable int N = 200010;
uint n;
uint[N] pre, nxt;
long ans;
long[N] a;

int main() {
  readf(" %d", &n), ans = (n - 1) * n >> 1;
  for (uint i = 1; i <= n; ++ i) readf(" %d", &a[i]);
  for (uint i = 1; i <= n; ++ i) {
    pre[i] = i - 1;
    while (pre[i] && (a[i] | a[pre[i]]) == a[i]) pre[i] = pre[pre[i]];
  }
  for (uint i = n; i; -- i) {
    nxt[i] = i + 1;
    while (nxt[i] <= n && (a[i] | a[nxt[i]]) == a[i] && a[i] > a[nxt[i]]) nxt[i] = nxt[nxt[i]];
    ans -= long(nxt[i] - i) * long(i - pre[i]) - 1;
  }
  writeln(ans);
  return 0;
}

import std.stdio;

static immutable int N = 200010;
uint n;
uint[N] pre, nxt;
long ans;
long[N] a;

int main() {
  readf(" %d", &n), ans = (n - 1) * n >> 1;
  for (uint i = 1; i <= n; ++ i) readf(" %d", &a[i]);
  for (uint i = 1; i <= n; ++ i) {
    pre[i] = i - 1;
    while (pre[i] && (a[i] | a[pre[i]]) == a[i]) pre[i] = pre[pre[i]];
  }
  for (uint i = n; i; -- i) {
    nxt[i] = i + 1;
    while (nxt[i] <= n && (a[i] | a[nxt[i]]) == a[i] && a[i] > a[nxt[i]]) nxt[i] = nxt[nxt[i]];
    ans -= (nxt[i] - i) * (i - pre[i]) - 1;
  }
  writeln(ans);
  return 0;
}


This is an interactive problem. In the interaction section below you will see the information about flushing the output.In this problem, you will be playing a game with Hongcow. How lucky of you!Hongcow has a hidden n by n matrix M. Let Mi, j denote the entry i-th row and j-th column of the matrix. The rows and columns are labeled from 1 to n.The matrix entries are between 0 and 109. In addition, Mi, i = 0 for all valid i. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each i, you must find .To do this, you can ask Hongcow some questions.A question consists of giving Hongcow a subset of distinct indices {w1, w2, ..., wk}, with 1 ≤ k ≤ n. Hongcow will respond with n integers. The i-th integer will contain the minimum value of min1 ≤ j ≤ kMi, wj.You may only ask Hongcow at most 20 questions — he thinks you only need that many questions answered.When you are ready to answer, print out a single integer  - 1 on its own line, then n integers on the next line. The i-th integer should be the minimum value in the i-th row of the matrix, excluding the i-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.You will get Wrong Answer verdict if   Your question or answers are not in the format described in this statement.  You ask strictly more than 20 questions.  Your question contains duplicate indices.  The value of k in your question does not lie in the range from 1 to n, inclusive.  Your final answer is not correct.  You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).

The first line of input will contain a single integer n (2 ≤ n ≤ 1, 000).

To print the final answer, print out the string -1 on its own line. Then, the next line should contain n integers. The i-th integer should be the minimum value of the i-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer!

NoteIn the first sample, Hongcow has the hidden matrix [ [0, 3, 2], [5, 0, 7], [4, 8 ,0],]Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant. 3              3              1 2 30 0 0              1              32 7 0              2              1 20 0 4              1              23 0 8              1              10 5 4              -1              2 5 4For the second sample, it is possible for off-diagonal elements of the matrix to be zero.

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

void main()
{
	int n;
	while(input(&n))
	{
		readln;
		auto m=new int[n];
		fill(m,int.max);
		foreach(i;0..10)
		{
			if((1<<i)>n)break;

			foreach(j;0..2)
			{
				int[] z;
				foreach(f;1..n+1)
				{
					if(((f>>i)&1)==j)z~=f;
				}
				writeln(z.length);
				putarr(z);

				stdout.flush;
				writeln;
				auto ans=arread!int;
				debug writeln(ans.length);
				foreach(p,y;ans)
				{
					debug writeln(p);
					if((((p+1)>>i)&1)!=j)m[p]=min(m[p],y);
				}
			}
		}
		writeln(-1);
		putarr(m);
		stdout.flush;
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto ans = new int [n];
		ans[] = int.max;
		foreach (d; 0..10)
		{
			foreach (g; 0..2)
			{
				auto p = n.iota.filter
				    !(x => ((x >> d) & 1) == g).array;
				p[] += 1;
				if (p.length == 0)
				{
					continue;
				}
				writefln ("%s\n%(%s %)", p.length, p);
				stdout.flush ();
				auto cur = readln.split.map !(to !(int)).array;
				foreach (i; 0..n)
				{
					if ((i >> d & 1) != g)
					{
						ans[i] = min (ans[i], cur[i]);
					}
				}
			}
		}
		writeln (-1);
		writefln ("%(%s %)", ans);
		stdout.flush ();
	}
}

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

void main()
{
	int n;
	while(input(&n))
	{
		readln;
		auto m=new int[n];
		fill(m,int.max);
		foreach(i;0..10)
		{
			if((1<<i)>n)break;

			foreach(j;0..2)
			{
				int[] z;
				foreach(f;1..n+1)
				{
					if(((f>>i)&1)==j)z~=f;
				}
				writeln(z.length);
				putarr(z);

				stdout.flush;
				writeln;
				auto ans=arread!int;
				foreach(y,p;ans)
				{
					if((((p+1)>>i)&1)!=j)m[p]=min(m[p],y);
				}
			}
		}
		writeln(-1);
		putarr(m);
		stdout.flush;
	}
}

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

void main()
{
	int n;
	while(input(&n))
	{
		auto m=new int[n];
		fill(m,int.max);
		foreach(i;0..10)
		{
			if((1<<i)>n)break;

			foreach(j;0..2)
			{
				int[] z;
				foreach(f;1..n+1)
				{
					if(((f>>i)&1)==j)z~=f;
				}
				writeln(z.length);
				putarr(z);
				writeln;
				stdout.flush;
				auto ans=arread!int;
				foreach(y,p;ans)
				{
					if((((p+1)>>i)&1)!=j)m[p]=min(m[p],y);
				}
			}
		}
		writeln(-1);
		putarr(m);
		stdout.flush;
	}
}


Bearland is a dangerous place. Limak can’t travel on foot. Instead, he has k magic teleportation stones. Each stone can be used at most once. The i-th stone allows to teleport to a point (axi, ayi). Limak can use stones in any order.There are n monsters in Bearland. The i-th of them stands at (mxi, myi).The given k + n points are pairwise distinct.After each teleportation, Limak can shoot an arrow in some direction. An arrow will hit the first monster in the chosen direction. Then, both an arrow and a monster disappear. It’s dangerous to stay in one place for long, so Limak can shoot only one arrow from one place.A monster should be afraid if it’s possible that Limak will hit it. How many monsters should be afraid of Limak?

The first line of the input contains two integers k and n (1 ≤ k ≤ 7, 1 ≤ n ≤ 1000) — the number of stones and the number of monsters. The i-th of following k lines contains two integers axi and ayi ( - 109 ≤ axi, ayi ≤ 109) — coordinates to which Limak can teleport using the i-th stone. The i-th of last n lines contains two integers mxi and myi ( - 109 ≤ mxi, myi ≤ 109) — coordinates of the i-th monster. The given k + n points are pairwise distinct.

Print the number of monsters which should be afraid of Limak.

NoteIn the first sample, there are two stones and four monsters. Stones allow to teleport to points ( - 2,  - 1) and (4, 5), marked blue in the drawing below. Monsters are at (4, 2), (2, 1), (4,  - 1) and (1,  - 1), marked red. A monster at (4,  - 1) shouldn't be afraid because it's impossible that Limak will hit it with an arrow. Other three monsters can be hit and thus the answer is 3.  In the second sample, five monsters should be afraid. Safe monsters are those at (300, 600), (170, 340) and (90, 180).

import std.algorithm, std.array, std.range, std.stdio, std.typecons;
alias Point = Tuple !(int, q{x}, int, q{y});
long sp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.x - a.x) + (b.y - a.y) * 1L * (c.y - a.y);}
long vp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.y - a.y) - (b.y - a.y) * 1L * (c.x - a.x);}
void main () {
	int k, n, res;
	readf (" %s %s", &k, &n);
	auto a = new Point [k], b = new Point [n], s = new int [] [] [] (k, n);
	foreach (ref p; a) readf (" %s %s", &p.x, &p.y);
	foreach (ref q; b) readf (" %s %s", &q.x, &q.y);
	foreach (p; 0..k) foreach (q; 0..n) s[p][q] = n.iota.filter !(r => vp (b[r], a[p], b[q]) == 0 && sp (b[r], a[p], b[q]) < 0).take (k).array;
	bool go (int mask, int depth, int [] t) {
		if (t.empty) return true;
		if (depth < t.length) return false;
		foreach (p; 0..k) if (mask & (1 << p)) foreach (i, q; t) {
			auto next = t[0..i] ~ t[i + 1..$] ~ s[p][q];
			if (go (mask ^ (1 << p), depth - 1, next.sort ().uniq.array)) return true;
		}
		return false;
	}
	foreach (q; 0..n) res += go (-1, k, [q]);
	writeln (res);
}

import core.bitop;
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;

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

long sp (Point a, Point b, Point c)
{
	return (b.x - a.x) * 1L * (c.x - a.x) + (b.y - a.y) * 1L * (c.y - a.y);
}

long vp (Point a, Point b, Point c)
{
	return (b.x - a.x) * 1L * (c.y - a.y) - (b.y - a.y) * 1L * (c.x - a.x);
}

void main ()
{
	int k;
	int n;
	while (readf (" %s %s", &k, &n) > 0)
	{
		auto a = new Point [k];
		foreach (ref p; a)
		{
			readf (" %s %s", &p.x, &p.y);
		}
		auto b = new Point [n];
		foreach (ref q; b)
		{
			readf (" %s %s", &q.x, &q.y);
		}
		auto s = new int [] [] [] (k, n);
		foreach (p; 0..k)
		{
			foreach (q; 0..n)
			{
				s[p][q] = n.iota.filter
				    !(r => vp (b[r], a[p], b[q]) == 0 &&
				    sp (b[r], a[p], b[q]) < 0).take (k).array;
			}
		}

		bool go (int mask, int depth, int [] t)
		{
			if (t.empty)
			{
				return true;
			}
			if (depth < t.length)
			{
				return false;
			}
			foreach (p; 0..k)
			{
				if (mask & (1 << p))
				{
					foreach (i, q; t)
					{
						int [] next = t[0..i] ~
						    t[i + 1..$] ~ s[p][q];
						next = next.sort ().uniq.array;
						if (go (mask ^ (1 << p),
						    depth - 1,
						    next))
						{
							return true;
						}
					}
				}
			}
			return false;
		}

		long res = 0;
		int m = (1 << k) - 1;
		foreach (q; 0..n)
		{
			res += k.iota.any
			    !(p => go (m ^ (1 << p), k - 1, s[p][q]));
		}

		writeln (res);
	}
}

import std.algorithm, std.array, std.range, std.stdio, std.typecons;
alias Point = Tuple !(int, q{x}, int, q{y});
long sp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.x - a.x) + (b.y - a.y) * 1L * (c.y - a.y);}
long vp (Point a, Point b, Point c) {return (b.x - a.x) * 1L * (c.y - a.y) - (b.y - a.y) * 1L * (c.x - a.x);}
void main () {
	int k, n, res;
	readf (" %s %s", &k, &n);
	auto a = new Point [k], b = new Point [n], s = new int [] [] [] (k, n);
	foreach (ref p; a) readf (" %s %s", &p.x, &p.y);
	foreach (ref q; b) readf (" %s %s", &q.x, &q.y);
	foreach (p; 0..k) foreach (q; 0..n) s[p][q] = n.iota.filter !(r => vp (b[r], a[p], b[q]) == 0 && sp (b[r], a[p], b[q]) < 0).take (k).array;
	bool go (int mask, int depth, int [] t) {
		if (t.empty) return true;
		if (depth < t.length) return false;
		foreach (p; 0..k) if (mask & (1 << p)) foreach (i, q; t) {
			auto next = t[0..i] ~ t[i + 1..$] ~ s[p][q];
			if (go (mask ^ (1 << p), depth - 1, next.sort ().uniq.array)) return true;
		}
		return false;
	}
	foreach (q; 0..n) res += k.iota.any !(p => go (-1, k, [p]));
	writeln (res);
}


You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$a_i \cdot a_j = i + j$$$.

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

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

NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    auto b = zip(a, iota(0L, n)).array.sort!((a, b) => a[0] < b[0]).array;
    long result = 0;
    foreach (i ; 0 .. b.length) {
      long maxaj = (4 * n + b[i][0] - 1) / b[i][0];
      foreach (j ; 0 .. b.length) {
        if (b[j][0] > maxaj)
          break;
        if (b[i][1] < b[j][1]) {
          long x = b[i][0] * b[j][0];
          long y = b[i][1] + 1 + b[j][1] + 1;
          if (x == y) {
            result++;
          }
        }
      }
    }
    writeln(result);
  }
}

// Vicfred
// https://codeforces.com/contest/1541/problem/B
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    long[] a = readln.split.map!(to!long).array;
    int[long] index;
    for(int i = 1; i <= n; ++i) {
        index[a[i - 1]] = i;
    }
    a.sort;
    long count = 0L;
    for(int i = 0; i < n; ++i) {
        for(int j = i + 1; j < n; ++j) {
            if(a[i] * a[j] > n * 2) {
                break;
            }
            if(a[i] * a[j] == index[a[i]] + index[a[j]]) {
                count += 1L;
            }
        }
    }
    count.writeln;
}
}

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int t;
  read(t);

  while (t--) {
    int n;
    read(n);
    auto arr = list!int;

    int[] pos = new int[2 * n + 2];
    pos.fill(-1);

    int total = 0;

    foreach (int i, e; arr) {
      int q = (2 * i + 1) / e;
      foreach (j; 1 .. q + 1) {
        if (pos[j] != -1 && j * e == i + 1 + pos[j]) {
          total++;
        }
      }

      pos[e] = i + 1;
    }

    writeln(total);
  }
}

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

void theCode(){
    int n = scan!int;
    auto arr = scanArray!int;
    auto ix = new int[2*n+1];
    ix[] = -1000_000_0;
    for(int i = 0; i < n; ++i){
        ix[arr[i]] = i+1;
    }
    int cnt = 0;
    for(int k = 2; k <= 2*n; ++k){
        for(int i = 1; i * i < k; ++i){
            if(k % i == 0 && ix[k/i] + ix[i] == k){
                ++cnt;
            }
        }
    }
    writeln(cnt);
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    auto b = zip(a, iota(0, n)).array.sort!((a, b) => a[0] < b[0]);
//    writeln(a);
//    writeln(b);
    size_t maxn = b.length;
    foreach (i ; 1 .. b.length) {
//      long x = b[i - 1][0];
//      long y = b[i - i][0];
//      writefln("%d * %d = %d", x, y, x * y);
      if (b[i - 1][0] * b[i][0] > 4 * n) {
        maxn = i + 1;
        break;
      }
    }
//    writeln(maxn);
    long result = 0;
    foreach (i ; 0 .. maxn) {
      foreach (j ; 0 .. maxn) {
        if (b[i][1] < b[j][1]) {
          long x = b[i][0] * b[j][0];
          long y = b[i][1] + 1 + b[j][1] + 1;
          if (x == y) {
            result++;
          }
        }
      }
    }
    writeln(result);
  }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    auto b = zip(a, iota(0, n)).array.sort!((a, b) => a[0] < b[0]);
//    writeln(a);
//    writeln(b);
    size_t maxn = a.length;
    foreach (i ; 1 .. a.length) {
      if (a[i - i] * a[i] > 4 * n) {
        maxn = i + 1;
        break;
      }
    }
    long result = 0;
    foreach (i ; 0 .. maxn) {
      foreach (j ; i + 1 .. maxn) {
        long x = b[i][0] * b[j][0];
        long y = b[i][1] + 1 + b[j][1] + 1;
        if (x == y) {
          result++;
        }
      }
    }
    writeln(result);
  }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    auto b = zip(a, iota(0, n)).array.sort!((a, b) => a[0] < b[0]);
    writeln(a);
    writeln(b);
    size_t maxn = a.length;
    foreach (i ; 1 .. a.length) {
      if (a[i - i] * a[i] > 4 * n) {
        maxn = i + 1;
        break;
      }
    }
    long result = 0;
    foreach (i ; 0 .. maxn) {
      foreach (j ; i + 1 .. maxn) {
        long x = b[i][0] * b[j][0];
        long y = b[i][1] + 1 + b[j][1] + 1;
        if (x == y) {
          result++;
        }
      }
    }
    writeln(result);
  }
}


You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$), $$$a_{x}+a_{y} \neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, print a complete array on a single line. All elements have to be integers between $$$1$$$ and $$$1000$$$ and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$) (not necessarily distinct), $$$a_{x}+a_{y} \neq a_{z}$$$ must hold. If multiple solutions exist, you may print any.

NoteIt can be shown that the outputs above are valid for each test case. For example, $$$44+44 \neq 384$$$.Below are some examples of arrays that are NOT complete for the 1st test case:$$$[1,2,3,4,5]$$$ Notice that $$$a_{1}+a_{2} = a_{3}$$$.$$$[1,3000,1,300,1]$$$ Notice that $$$a_{2} = 3000 > 1000$$$.

import std.algorithm;
import std.stdio;

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

    while(t--) {
        int n;
        readf("%s\n", &n);
        foreach(_; 0..n)
            writef("1 ");
        writeln;
    }
}

import std.conv, std.range, std.stdio, std.string;
void main () {
	foreach (test; 0..readln.strip.to !(int))
		1.repeat (readln.strip.to !(int)).writefln !("%(%s %)");
}

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 int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto arr = new int[](n);
		arr[] = 1;
		ans[ti] = arr;
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;

	stdout.flush;
	debug readln;
}


We're giving away nice huge bags containing number tiles! A bag we want to present to you contains $$$n$$$ tiles. Each of them has a single number written on it — either $$$1$$$ or $$$2$$$.However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.Can you win the prize? Hurry up, the bags are waiting!

The first line of the input contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the number of number tiles in the bag. The following line contains $$$n$$$ space-separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i \in \{1, 2\}$$$) — the values written on the tiles.

Output a permutation $$$b_1, b_2, \dots, b_n$$$ of the input sequence $$$(a_1, a_2, \dots, a_n)$$$ maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.

NoteThe first solution produces the prefix sums $$$1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}}$$$ (four primes constructed), while the prefix sums in the second solution are $$$1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}}$$$ (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.

import std.stdio;
import std.array: array, split;
import std.algorithm: map, count;
import std.conv: to;

void main() {
	readln();
	int[] a = readln.split.map!(to!int).array;
	if (a.count(1) == 0 || a.count(2) == 0) {
		writefln("%(%s %)", a);
	} else {
		write("2 1 ");
		foreach (ulong i; 0..(a.count(2)-1)) {
			write("2 ");
		}
		foreach (ulong i; 0..(a.count(1)-1)) {
			write("1 ");
		}
		writeln();
	}
}

// https://codeforces.com/problemset/problem/1149/A
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    readln;
    int[] a = readln.split.map!(to!int).array;
    long ones = a.count(1);
    long twos = a.count(2);
    if(ones == 0) {
        foreach(two; 0..twos) {
            writefln("%s ", 2);
        }
        return;
    }
    if(twos == 0) {
        foreach(one; 0..ones) {
            writefln("%s ", 1);
        }
        return;
    }
    writef("2 1 ");
    ones -= 1;
    twos -= 1;
    for(long i = 0; i < twos; i++)
        writef("%s ", 2);
    for(long i = 0; i < ones; i++)
        writef("%s ", 1);
    writeln();
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto c1 = a.count (1);
		auto c2 = a.count (2);
		auto total = sum (a) + 1;

		auto s = new bool [total];
		s[2..$] = true;
		for (int d = 0; d * d < total; d++)
		{
			if (s[d])
			{
				for (int e = d * d; e < total; e += d)
				{
					s[e] = false;
				}
			}
		}

		int [] answer;
		int cur = 0;
		foreach (d; 0..total)
		{
			if (s[d])
			{
				while (cur + 2 <= d && c2 > 0)
				{
					cur += 2;
					c2 -= 1;
					answer ~= 2;
				}
				while (cur + 1 <= d && c1 > 0)
				{
					cur += 1;
					c1 -= 1;
					answer ~= 1;
				}
			}
		}
		while (c2 > 0)
		{
			c2 -= 1;
			answer ~= 2;
		}
		while (c1 > 0)
		{
			c1 -= 1;
			answer ~= 1;
		}

		writefln ("%(%s %)", answer);
	}
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  auto a = r.nextA!int (n);
  int[3] c;
  foreach (i; a) {
    c[i]++;
  }
  int[] b;
  debug stderr.writeln (c);
  void o (int k) {
    if (c[k] > 0) {
      --c[k];
      b ~= k;
    }
  }
  o (2);
  o (1);
  while (c[2] > 0) {
    o (2);
  }
  while (c[1] > 0) {
    o (1);
  }
  writefln ("%(%s %)", b);
}

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

void solve(){
	int n = read.to!int;
	int[] as = readln.chomp.split.to!(int[]);

	int[] acount = [0, 0, 0];
	foreach(a; as) acount[a] += 1;

	int[] ans;
	if(acount[1] > 0 && acount[2] > 0){
		acount[2] -= 1, ans ~= 2;
		acount[1] -= 1, ans ~= 1;
	}
	while(acount[2] > 0){
		acount[2] -= 1, ans ~= 2;
	}
	while(acount[1] > 0){
		acount[1] -= 1, ans ~= 1;
	}

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

}

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

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

  int one = 0, two = 0;
  foreach (el; a) {
    if (el == 1) {
      one += 1;
    } else {
      two += 1;
    }
  }
  if (one == 0 || two == 0) {
    writefln("%(%s %)", a);
    return;
  }
  int[] b;
  b ~= [2, 1];
  foreach (_; 0 .. (two - 1)) {
    b ~= 2;
  }
  foreach (_; 0 .. (one - 1)) {
    b ~= 1;
  }
  writefln("%(%s %)", b);
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;

alias Tree = RBT!int;

void main()
{
  GC.disable();

  uint n;
  readf(" %s\n", n);

  auto a = new int[n];
  foreach (i; 0 .. n)
    readf(" %s", a[i]);

  sort!"a>b"(a);
  if (a[$ - 1] == 1 && a[0] == 2)
  {
    writefln("2 1 %(%s %)", a[1 .. $ - 1]);
  }
  else
    writefln("%(%s %)", a);
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

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

	long[2] cnt;
	foreach (i; 0..N)
	{
		auto j = a[i] - 1;
		++cnt[j];
	}

	long x;
	if (cnt[1] != 0)
	{
		--cnt[1];
		x = 2;
		write(2);
	}
	else
	{
		--cnt[0];
		x = 1;
		write(1);
	}

	foreach (i; 1..N)
	{
		if (x % 2 == 1 && cnt[1] != 0)
		{
			--cnt[1];
			x += 2;
			write(" 2");
		}
		else if (cnt[0] != 0)
		{
			--cnt[0];
			x += 1;
			write(" 1");
		}
		else
		{
			--cnt[1];
			x += 2;
			write(" 2");
		}
	}

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

// https://codeforces.com/problemset/problem/1149/A
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    readln;
    int[] a = readln.split.map!(to!int).array;
    long ones = a.count(1);
    long twos = a.count(2);
    if(ones == 0)
        foreach(two; 0..twos) {
            writefln("%s ", 2);
            return;
        }
    if(twos == 0)
        foreach(one; 0..ones) {
            writefln("%s ", 1);
            return;
        }
    writef("2 1 ");
    ones -= 1;
    twos -= 1;
    foreach(two; 0..twos)
        writef("%s ", 2);
    foreach(one; 0..ones)
        writef("%s ", 1);
    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;

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  auto a = r.nextA!int (n);
  int[3] c;
  foreach (i; a) {
    c[a[i]]++;
  }
  int[] b;
  void o (int k) {
    if (c[k] > 0) {
      --c[k];
      b ~= k;
    }
  }
  o (2);
  o (1);
  while (c[2] > 0) {
    o (2);
  }
  while (c[1] > 0) {
    o (1);
  }
  writefln ("%(%s %)", b);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;

alias Tree = RBT!int;

void main()
{
  GC.disable();

  uint n;
  readf(" %s\n", n);

  auto a = new int[n];
  foreach (i; 0 .. n)
    readf(" %s", a[i]);

  sort!"a>b"(a);
  if (a[$ - 1] == 1 && a[0] == 2)
  {
    writefln("2 1 %(%s %)", a[1 .. $ - 1]);
  }
  else
    writeln(a);
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

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

	long[2] cnt;
	foreach (i; 0..N)
	{
		auto j = a[i] - 1;
		++cnt[j];
	}

	if (cnt[1] != 0)
	{
		--cnt[1];
		write(2);
	}
	else
	{
		--cnt[0];
		write(1);
	}

	foreach (i; 1..N)
	{
		if (i % 2 == 0 && cnt[1] != 0)
		{
			--cnt[1];
			write(" 2");
		}
		else if (cnt[0] != 0)
		{
			--cnt[0];
			write(" 1");
		}
		else
		{
			--cnt[1];
			write(" 2");
		}
	}

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


In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.

The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.

For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.

NoteThe picture corresponds to the first example test case.  When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.

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

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

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

    arr[] -= 1;

    auto ans = new int[] (n);
    auto vis = new int[] (n);
    void dfs(int v) {
        if (vis[v] == 2) return;

        if (arr[v] == v) {
            vis[v] = 2;
            ans[v] = v;
            return;
        }

        if (vis[v] == 1) {
            vis[v] = 2;
            ans[v] = v;
            dfs(arr[v]);
            return;
        }

        vis[v] = 1;
        dfs(arr[v]);
        if (vis[v] != 2) {
            vis[v] = 2;
            ans[v] = ans[arr[v]];
        }
    }

    foreach (i; 0 .. n) {
        dfs(i);
    }

    debug { ans.writeln; }

    ans[] += 1;

    ans.writefln!("%(%s %)");
}

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

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

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

    int[] ans;
    foreach (i; 0 .. n) {
        auto vis = new int[] (n);
        vis[] = false;

        int j = i;
        do {
            vis[j] = true;
            j = arr[j] - 1;
        } while (!vis[j]);

        ans ~= j;
    }

    ans[] += 1;

    ans.writefln!("%(%s %)");
}

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

  int n; rd(n);
  auto g=readln.split.to!(int[]).map!((e)=>(e-1)).array;

  int f(int i, bool[] vis){
    if(vis[i]) return i;
    vis[i]=true;
    return f(g[i], vis);
  }

  foreach(i; 0..n){
    auto vis=new bool[](n);
    writeln(f(i, vis)+1);
  }
}

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

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

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

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

    arr[] -= 1;

    auto start = new bool[] (n);
    start[] = true;
    foreach (i, e; arr) {
        if (i != e) start[e] = false;
    }

    auto ans = new int[] (n);
    auto vis = new int[] (n);
    void dfs(int v) {
        if (vis[v] == 2) return;

        if (arr[v] == v) {
            vis[v] = 2;
            ans[v] = v;
            return;
        }

        if (vis[v] == 1) {
            vis[v] = 2;
            ans[v] = v;
            dfs(arr[v]);
            return;
        }

        vis[v] = 1;
        dfs(arr[v]);
        if (vis[v] != 2) {
            vis[v] = 2;
            ans[v] = ans[arr[v]];
        }
    }

    foreach (i; 0 .. n) {
        if (start[i]) {
            dfs(i);
        }
    }

    debug { ans.writeln; }

    ans[] += 1;

    ans.writefln!("%(%s %)");
}

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

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

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

    arr[] -= 1;

    auto start = new bool[] (n);
    start[] = true;
    foreach (i, e; arr) {
        if (i != e) start[e] = false;
    }

    auto ans = new int[] (n);
    auto vis = new int[] (n);
    int dfs(int v) {
        if (arr[v] == v) {
            vis[v] = 2;
            ans[v] = v;
            return v;
        }

        if (vis[v] == 1) {
            vis[v] = 2;
            ans[v] = v;
            dfs(arr[v]);
            return v;
        }

        if (vis[v] == 2) {
            return ans[v];
        }

        vis[v] = 1;
        ans[v] = dfs(arr[v]);
        vis[v] = 2;
        return ans[v];
    }

    foreach (i; 0 .. n) {
        if (start[i]) {
            dfs(i);
        }
    }

    ans[] += 1;

    ans.writefln!("%(%s %)");
}


Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.

The first line contains one integer n (1 ≤ n ≤ 50) — the length of the hidden word. The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed. The third line contains an integer m (1 ≤ m ≤ 1000) — the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves — n-letter strings of lowercase Latin letters. All words are distinct. It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed.

Output the single integer — the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.

NoteIn the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns.

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
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:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.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));
}

void main() {
    int n, m;
    char[51] _pattern, _word;
    while (read(n)) {
        auto pattern = _pattern[ ];
        readln(pattern);
        pattern = pattern[0 .. $ - 1];
        int revealed = 0x0;
        foreach (c; pattern)
            if (c != '*')
                revealed |= 1 << (c - 'a');
        read(m);
        int possible = ~0x0;
        while (m--) {
            auto s = _word[ ];
            readln(s);
            s = s[0 .. $ - 1];
            int starred = 0x0;
            foreach (p, c; zip(pattern, s))
                if (p == '*') {
                    if (revealed & 1 << (c - 'a'))
                        goto no;
                    starred |= 1 << (c - 'a');
                } else if (p != c)
                    goto no;
            possible &= starred;
        no:
        }
        writeln(popcnt(possible));
    }
}


You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.Consider a number axis. The capital of your empire is initially at $$$0$$$. There are $$$n$$$ unconquered kingdoms at positions $$$0<x_1<x_2<\ldots<x_n$$$. You want to conquer all other kingdoms.There are two actions available to you:   You can change the location of your capital (let its current position be $$$c_1$$$) to any other conquered kingdom (let its position be $$$c_2$$$) at a cost of $$$a\cdot |c_1-c_2|$$$.  From the current capital (let its current position be $$$c_1$$$) you can conquer an unconquered kingdom (let its position be $$$c_2$$$) at a cost of $$$b\cdot |c_1-c_2|$$$. You cannot conquer a kingdom if there is an unconquered kingdom between the target and your capital. Note that you cannot place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $$$0$$$ or one of $$$x_1,x_2,\ldots,x_n$$$. Also note that conquering a kingdom does not change the position of your capital.Find the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. The description of each test case follows. The first line of each test case contains $$$3$$$ integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq a,b \leq 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$1 \leq x_1 < x_2 < \ldots < x_n \leq 10^8$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer  — the minimum cost to conquer all kingdoms.

NoteHere is an optimal sequence of moves for the second test case:  Conquer the kingdom at position $$$1$$$ with cost $$$3\cdot(1-0)=3$$$.  Move the capital to the kingdom at position $$$1$$$ with cost $$$6\cdot(1-0)=6$$$.  Conquer the kingdom at position $$$5$$$ with cost $$$3\cdot(5-1)=12$$$.  Move the capital to the kingdom at position $$$5$$$ with cost $$$6\cdot(5-1)=24$$$.  Conquer the kingdom at position $$$6$$$ with cost $$$3\cdot(6-5)=3$$$.  Conquer the kingdom at position $$$21$$$ with cost $$$3\cdot(21-5)=48$$$.  Conquer the kingdom at position $$$30$$$ with cost $$$3\cdot(30-5)=75$$$. The total cost is $$$3+6+12+24+3+48+75=171$$$. You cannot get a lower cost than this.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int T = readln.chomp.to!int;
    foreach (int t; 0 .. T) {
        long N, A, B; scanf("%Ld %Ld %Ld\n", &N, &A, &B);
        long[] X = [0L] ~ readln.chomp.split(" ").map!(to!long).array;
        long[] S = new long[cast(int)N+1];
        S[0] = 0;
        for (int i = 1; i <= N; i++) {
            S[i] = S[i-1] + X[i];
        }
        long ans = long.max;
        for (int k = 0; k <= N; k++) {
            // the last captal is at xk
            long c = (A + B) * X[k] + B * (S[cast(int)N] - S[k] - (N - k) * X[k]);
            ans = min(ans, c);
        }
        writeln(ans);
    }
}


This is an interactive problem.Ayush devised a new scheme to set the password of his lock. The lock has $$$k$$$ slots where each slot can hold integers from $$$1$$$ to $$$n$$$. The password $$$P$$$ is a sequence of $$$k$$$ integers each in the range $$$[1, n]$$$, $$$i$$$-th element of which goes into the $$$i$$$-th slot of the lock.To set the password of his lock, Ayush comes up with an array $$$A$$$ of $$$n$$$ integers each in the range $$$[1, n]$$$ (not necessarily distinct). He then picks $$$k$$$ non-empty mutually disjoint subsets of indices $$$S_1, S_2, ..., S_k$$$ $$$(S_i \underset{i \neq j} \cap S_j = \emptyset)$$$ and sets his password as $$$P_i = \max\limits_{j \notin S_i} A[j]$$$. In other words, the $$$i$$$-th integer in the password is equal to the maximum over all elements of $$$A$$$ whose indices do not belong to $$$S_i$$$.You are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. You can ask no more than 12 queries.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$ — the size of the array and the number of subsets. $$$k$$$ lines follow. The $$$i$$$-th line contains an integer $$$c$$$ $$$(1 \leq c \lt n)$$$ — the size of subset $$$S_i$$$, followed by $$$c$$$ distinct integers in the range $$$[1, n]$$$  — indices from the subset $$$S_i$$$. It is guaranteed that the intersection of any two subsets is empty.

NoteThe array $$$A$$$ in the example is $$$[1, 2, 3, 4]$$$. The length of the password is $$$2$$$. The first element of the password is the maximum of $$$A[2]$$$, $$$A[4]$$$ (since the first subset contains indices $$$1$$$ and $$$3$$$, we take maximum over remaining indices). The second element of the password is the maximum of $$$A[1]$$$, $$$A[3]$$$ (since the second subset contains indices $$$2$$$, $$$4$$$).Do not forget to read the string "Correct" / "Incorrect" after guessing the password.

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

int ask (int [] r)
{
	writefln !("? %s%( %s%)") (r.length, r);
	stdout.flush ();
	auto res = readln.strip.to !(int);
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = new int [] [k];
		foreach (ref line; a)
		{
			line = readln.splitter.drop (1).map !(to !(int)).array;
		}

		auto total = ask (iota (1, n + 1).array);

		int lo = 0;
		int hi = k;
		while (lo + 1 < hi)
		{
			auto me = (lo + hi) / 2;
			auto cur = ask (a[lo..me].join);
			if (cur < total)
			{
				lo = me;
			}
			else
			{
				hi = me;
			}
		}

		auto used = new bool [n + 1];
		foreach (ref c; a[lo])
		{
			used[c] = true;
		}
		auto absent = iota (1, n + 1).filter !(c => !used[c]).array;
		auto grail = ask (absent);

		auto answer = repeat (total, k).array;
		answer[lo] = grail;
		writefln !("!%( %s%)") (answer);
		stdout.flush;
		if (readln.strip != "Correct")
		{
			assert (false);
		}
	}
}


Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.There are $$$k$$$ boxes numbered from $$$1$$$ to $$$k$$$. The $$$i$$$-th box contains $$$n_i$$$ integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, $$$k$$$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 15$$$), the number of boxes.  The $$$i$$$-th of the next $$$k$$$ lines first contains a single integer $$$n_i$$$ ($$$1 \leq n_i \leq 5\,000$$$), the number of integers in box $$$i$$$. Then the same line contains $$$n_i$$$ integers $$$a_{i,1}, \ldots, a_{i,n_i}$$$ ($$$|a_{i,j}| \leq 10^9$$$), the integers in the $$$i$$$-th box.  It is guaranteed that all $$$a_{i,j}$$$ are distinct.

If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output $$$k$$$ lines. The $$$i$$$-th of these lines should contain two integers $$$c_i$$$ and $$$p_i$$$. This means that Ujan should pick the integer $$$c_i$$$ from the $$$i$$$-th box and place it in the $$$p_i$$$-th box afterwards. If there are multiple solutions, output any of those. You can print each letter in any case (upper or lower).

NoteIn the first sample, Ujan can put the number $$$7$$$ in the $$$2$$$nd box, the number $$$2$$$ in the $$$3$$$rd box, the number $$$5$$$ in the $$$1$$$st box and keep the number $$$10$$$ in the same $$$4$$$th box. Then the boxes will contain numbers $$$\{1,5,4\}$$$, $$$\{3, 7\}$$$, $$$\{8,2\}$$$ and $$$\{10\}$$$. The sum in each box then is equal to $$$10$$$.In the second sample, it is not possible to pick and redistribute the numbers in the required way.In the third sample, one can swap the numbers $$$-20$$$ and $$$-10$$$, making the sum in each box equal to $$$-10$$$.

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

void main ()
{
	int k;
	while (readf (" %s", &k) > 0)
	{
		int [long] boxByNum;
		long [] [] boxes;
		long [] boxSums;
		foreach (j; 0..k)
		{
			int len;
			readf (" %s", &len);
			auto line = readln.splitter.map !(to !(long)).array;
			foreach (ref c; line)
			{
				boxByNum[c] = j;
			}
			boxes ~= line;
			boxSums ~= line.sum;
		}

		long total = boxSums.sum;
		if (total % k != 0)
		{
			writeln ("No");
			continue;
		}
		long target = total / k;

		auto p2k = 1 << k;
		auto answer = new long [] [p2k];

		foreach (j; 0..k)
		{
			foreach (ref c; boxes[j])
			{
				long [] cur;
				cur.reserve (k + 1);
				int maskUsed = 0;
				int box = j;
				long num = c;
				bool ok = false;

				while (true)
				{
					maskUsed |= 1 << box;
					cur ~= num;

					long desired =
					    target - boxSums[box] + num;
					if (desired !in boxByNum)
					{
						break;
					}

					box = boxByNum[desired];
					num = desired;
					if (num == cur.front)
					{
						ok = true;
						break;
					}
					if (maskUsed & (1 << box))
					{
						break;
					}
				}

				if (ok)
				{
					answer[maskUsed] = cur.dup;
				}
			}
		}

		auto f = new int [p2k];
		f[0] = -1;
		for (int s = 0; s < p2k; s++)
		{
			for (int t = s; t > 0; t = (t - 1) & s)
			{
				if ((f[s ^ t] != 0) && (answer[t] !is null))
				{
					f[s] = t;
				}
			}
		}

		if (f[p2k - 1])
		{
			writeln ("Yes");
			auto numById = new long [k];
			auto toById = new int [k];
			int s = p2k - 1;
			while (s != 0)
			{
				auto t = f[s];
				foreach (i; 0..answer[t].length)
				{
					long num = answer[t][i];
					int box = boxByNum[num];
					long numNext = answer[t][(i + 1) % $];
					int boxNext = boxByNum[numNext];
					numById[boxNext] = numNext;
					toById[boxNext] = box;
				}
				s ^= t;
			}
			foreach (j; 0..k)
			{
				writeln (numById[j], " ", toById[j] + 1);
			}
		}
		else
		{
			writeln ("No");
		}
	}
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.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 K = readInt();
      auto N = new int[K];
      auto A = new long[][K];
      foreach (u; 0 .. K) {
        N[u] = readInt();
        A[u] = new long[N[u]];
        foreach (j; 0 .. N[u]) {
          A[u][j] = readLong();
        }
      }

      Tuple!(int, "u", int, "j")[long] pos;
      foreach (u; 0 .. K) {
        foreach (j; 0 .. N[u]) {
          pos[A[u][j]] = tuple!("u", "j")(u, j);
        }
      }

      auto ss = new long[K];
      foreach (u; 0 .. K) {
        ss[u] = A[u].sum;
      }
      long s = ss.sum;
      if (s % K != 0) {
        writeln("No");
        continue;
      }
      s /= K;
      debug {
        writeln("s = ", s);
      }

      auto cycs = new Tuple!(int[], long[])[1 << K];
      foreach (t; 0 .. K) {
        foreach (i; 0 .. N[t]) {
          int used;
          int[] us;
          long[] as;
          for (int u = t, j = i; ; ) {
            used |= 1 << u;
            us ~= u;
            as ~= A[u][j];
            // ss[u] - A[u][j] + A[v][k] = s
            const a = s - ss[u] + A[u][j];
            if (!(a in pos)) {
              goto failed;
            }
            const vk = pos[a];
            const v = vk.u;
            const k = vk.j;
            if (used & 1 << v) {
              if (!(t == v && i == k)) {
                goto failed;
              }
              debug {
                writeln("cyc ", used, " ", us, " ", as);
              }
              cycs[used] = tuple(us, as);
              break;
            }
            u = v;
            j = k;
          }
         failed:
        }
      }

      auto prev = new int[1 << K];
      prev[0] = -1;
      foreach (p; 1 .. 1 << K) {
        for (int q = p; q; --q &= p) {
          if (cycs[q][0] && prev[p ^ q]) {
            prev[p] = q;
          }
        }
      }
      if (prev[$ - 1]) {
        auto ansC = new long[K];
        auto ansP = new int[K];
        for (int p = (1 << K) - 1; p; ) {
          const q = prev[p];
          const us = cycs[q][0];
          const as = cycs[q][1];
          const len = cast(int)(us.length);
          foreach (h; 0 .. len) {
            ansC[us[h]] = as[h];
            ansP[us[(h + 1) % len]] = us[h];
          }
          p ^= q;
        }
        writeln("Yes");
        foreach (u; 0 .. K) {
          writeln(ansC[u], " ", ansP[u] + 1);
        }
      } else {
        writeln("No");
      }
    }
  } catch (EOFException e) {
  }
}


Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.

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

void main() {

	string snum = readln.strip;

	int nomore = -1;
	foreach (idx, sdigit; snum) {
		if ((sdigit - '0') % 2 == 0) {
			if (sdigit < snum[$ - 1]) {
				auto s = snum.dup;
				swap(s[idx], s[$ - 1]);
				writeln(s);
				return;
			}
			else
				nomore = idx;
		}
	}

	if (nomore != -1) {
		auto s = snum.dup;
		swap(s[nomore], s[$ - 1]);
		writeln(s);
	}
	else
		writeln("-1");
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

string S;

void main(string[] args) {
	try {
	for (; ; ) {
		S = readToken;

		char[] cs = S.to!(char[]);
		char[] ans;
		foreach (x; "02468") {
			foreach (i, c; cs) if (c == x) {
				swap(cs[i], cs[$ - 1]);
				if (ans < cs) {
					ans = cs.dup;
				}
				swap(cs[i], cs[$ - 1]);
				break;
			}
			foreach_reverse (i, c; cs) if (c == x) {
				swap(cs[i], cs[$ - 1]);
				if (ans < cs) {
					ans = cs.dup;
				}
				swap(cs[i], cs[$ - 1]);
				break;
			}
		}
		if (ans == "") {
			writeln(-1);
		} else {
			writeln(ans);
		}

	}
	} catch (EOFException) {}
}

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

void main() {

	string snum = readln.strip;

	int nomore = -1;
	foreach (idx, sdigit; snum) {
		if ((sdigit - '0') % 2 == 0) {
			if (sdigit < snum[$ - 1]) {
				auto s = snum.dup;
				swap(s[idx], s[$ - 1]);
				writeln(s);
				return;
			}
			else
				nomore = idx;
		}
	}

	if (nomore != -1) {
		auto s = snum.dup;
		swap(s[nomore], s[$ - 1]);
		writeln(snum);
	}
	else
		writeln("-1");
}

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

void main() {

	string snum = readln.strip;

	string max = "0";
	foreach (idx, sdigit; snum) {
		if ((sdigit - '0') % 2 == 0) {
			auto s = snum.dup;
			swap(s[idx], s[$ - 1]);
			if (s > max)
				max = s.dup;
			if (s[idx] < s[$ - 1])
				break;
		}
	}

	writeln((max == "0") ? "-1" : max);
}


You are given two strings $$$s$$$ and $$$t$$$, both of length $$$n$$$. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions:   choose an occurrence of "ab" in $$$s$$$ and replace it with "ba";  choose an occurrence of "bc" in $$$s$$$ and replace it with "cb". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $$$s$$$ to make it equal to string $$$t$$$?

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line contains string $$$s$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The third line contains string $$$t$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase, print "YES" if you can change string $$$s$$$ to make it equal to string $$$t$$$ by performing an arbitrary amount of moves (possibly, zero). Otherwise, print "NO".

5

3

cab

cab

1

a

b

6

abbabc

bbaacb

10

bcaabababc

cbbababaac

2

ba

ab

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto S = scan;
      auto T = scan;

      if (S.array.sort != T.array.sort) return "NO";

      foreach(c; matchAll(S, regex(r"[ab]*[bc]*"))) {
        auto l = c.pre.length.to!int;
        auto r = l + c.hit.length.to!int;

        if (!match(T[l..r], regex(r"^[ab]*[bc]*$"))) return "NO";

        int sa, ta;
        int sc, tc;
        auto countS = new int[](3);
        auto countT = new int[](3);
        foreach(i; l..r) {
          countS[S[i] - 'a']++;
          countT[T[i] - 'a']++;
          if (S[i] == 'a') sa++;
          if (T[i] == 'a') ta++;
          if (S[i] == 'c') sc++;
          if (T[i] == 'c') tc++;
          if (ta > sa || sc > tc) return "NO";
        }

        if (countS != countT) return "NO";
      }

      return "YES";
    }

    foreach(i; 0..QN) {
      outputForAtCoder(&subSolve);
    }
  }

  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;
import std.regex;
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;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto S = scan;
      auto T = scan;

      if (S.array.sort != T.array.sort) return "NO";

      foreach(c; matchAll(S, regex(r"[ab]*b[bc]*"))) {
        auto l = c.pre.length.to!int;
        auto r = l + c.hit.length.to!int;

        if (!match(T[l..r], regex(r"^[ab]*[bc]*$"))) return "NO";

        int sa, ta;
        int sc, tc;
        auto countS = new int[](3);
        auto countT = new int[](3);
        foreach(i; l..r) {
          countS[S[i] - 'a']++;
          countT[T[i] - 'a']++;
          if (S[i] == 'a') sa++;
          if (T[i] == 'a') ta++;
          if (S[i] == 'c') sc++;
          if (T[i] == 'c') tc++;
          if (ta > sa || sc > tc) return "NO";
        }

        if (countS != countT) return "NO";
      }

      return "YES";
    }

    foreach(i; 0..QN) {
      outputForAtCoder(&subSolve);
    }
  }

  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;
import std.regex;
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;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto S = scan;
      auto T = scan;

      if (S.array.sort != T.array.sort) return "NO";

      foreach(c; matchAll(S, regex(r"[ab]*b[bc]*"))) {
        auto l = c.pre.length.to!int;
        auto r = l + c.hit.length.to!int;

        if (!match(T[l..r], regex(r"[ab]*b[bc]*"))) return "NO";

        int sa, ta; sa = ta = int.max;
        int sc, tc;
        auto countS = new int[](3);
        auto countT = new int[](3);
        foreach(i; l..r) {
          countS[S[i] - 'a']++;
          countT[T[i] - 'a']++;
          if (S[i] == 'a') sa = min(sa, i);
          if (T[i] == 'a') ta = min(ta, i);
          if (S[i] == 'c') sc = max(sc, i);
          if (T[i] == 'c') tc = max(tc, i);
        }

        if (countS != countT || ta < sa || tc > sc) return "NO";
      }

      return "YES";
    }

    foreach(i; 0..QN) {
      outputForAtCoder(&subSolve);
    }
  }

  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;
import std.regex;
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;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
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"];

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