Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.

If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.

NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating:  Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7.  With rating 1894 Limak is in the division 2. His rating increases by 5.  Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.

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 core.stdc.stdlib : system;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
alias mp=make_pair;
alias bins=binary_search;
alias orsq=orient_square;
immutable int mod=1000000007;
pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow 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 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;
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
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) if(is(A:X) && is(B:Y))
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(A,B)(in pair!(A,B) s_) const pure nothrow @safe if(is(typeof(s_.fi<fi)==bool) && is(typeof(s_.se<se)==bool))
	{
		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) make_pair(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
pure nothrow @property X sqr(X)(in X a_) {return a_*a_;}
pure nothrow @property X cub(X)(in X a_) {return a_*a_*a_;}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow 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 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 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 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;
}
pure nothrow V foldr(R,V,T)(R range,T arg,V nach) if(isFunction!T && isInputRange!R && is(typeof(arg(nach,R.front))==V))
{
	for(;!range.empty;range.popFront()) nach=arg(nach,range.front);
	return nach;
}
pure nothrow size_t countr(R,T)(R range,T fun) if(isFunction!T && isInputRange!R && is(typeof(fun(R.front))==bool))
{
	size_t nach;
	for(;!range.empty;range.popFront()) nach+=fun(range.front);
	return nach;
}
pure nothrow T orient_square(T)(pair!(T,T)[] figure...) if(is(typeof(figure.front*figure.front)==T))
{
	auto n=figure.front,t=figure.front;
	figure.popFront();
	T ans=0;
	for(;!figure.empty;figure.popFront())
	{
		ans+=(figure.front.fi-t.fi)*(figure.front.se+t.se);
		t=figure.front;
	}
	return ans+(n.fi-t.fi)*(n.se+t.se);
}
pure nothrow real square(T)(pair!(T,T)[] figure...) if(is(typeof(figure.front*figure.front)==T))
{
	return abs(orient_square(figure))/2.000000000000000;
}
struct Tree(T,alias arg="a+b")
{
	private alias fun=binaryFun!arg;
	private static const uint n=int.max;
	private T[uint] t;
	private void upd(uint v,uint vl,uint vr,uint i,T x)
	{
		if (vr - vl == 1)t[v] = x;
		uint vm = (vl + vr) >> 1;
		if(i<vm)upd(2*v,vl,vm,i,x);
		else upd(2*v+1,vm,vr,i,x);
		t[v]=fun(t[v*2],t[v*2+1]);
	}
	void upd(uint i,T x)
	{
		upd(1,0,n,i,x);
	}
	private T cel(uint v,uint vl,uint vr,uint l,uint r)
	{
		if(vl==l && r==vr) return t[v];
		uint vm=(vl+vr) >> 1;
		if(r<=vm) return cel(2*v,vl,vm,l,r);
		else if(l>=vm) return cel(2*v+1,vm,vr,l,r);
		else return fun(cel(2*v,vl,vm,l,vm),cel(2*v+1,vm,vr,vm,r));
	}
	T cel(uint l,uint r){return cel(1,0,n,l,r);}
};
//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 a=new pii[n];
		foreach_reverse(i;0..n)input(&a[i].fi,&a[i].se);
		int check(int r)
		{
			foreach(i;0..n)
			{
				r-=a[i].fi;
				if(a[i].se==2 && r>1899)return 1;
				else if(a[i].se==1 && r<1900) return -1;
			}
			return 0;
		}
		int l=int.min/2,r=int.max/2;
		while(r-l>1)
		{
			int m=(l+r)>>1;
			auto k=check(m);
			if(k==1) r=m;
			else l=m;
		}
		if(l>=int.max/2-1)writeln("Infinity");
		else if(check(l)!=0)writeln("Impossible");
		else writeln(l);
	}
	debug system("pause");
}

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)
	{
		int lo = int.min / 2;
		int hi = int.max / 2;
		int delta = 0;
		foreach (i; 0..n)
		{
			int c;
			int d;
			readf (" %s %s", &c, &d);
			if (d == 1)
			{ // rating + delta >= 1900
				lo = max (lo, 1900 - delta);
			}
			else if (d == 2)
			{ // rating + delta <= 1899
				hi = min (hi, 1899 - delta);
			}
			else
			{
				assert (false);
			}
			delta += c;
		}
		debug {writeln (lo, " ", hi);}
		if (hi > int.max / 4)
		{
			writeln ("Infinity");
		}
		else if (lo > hi)
		{
			writeln ("Impossible");
		}
		else
		{
			writeln (hi + delta);
		}
	}
}


A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $$$7$$$ days!In detail, she can choose any integer $$$k$$$ which satisfies $$$1 \leq k \leq r$$$, and set $$$k$$$ days as the number of days in a week.Alice is going to paint some $$$n$$$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has $$$4$$$ days and Alice paints $$$5$$$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes.    Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $$$n$$$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains two integers $$$n$$$, $$$r$$$ ($$$1 \le n \le 10^9, 1 \le r \le 10^9$$$).

For each test case, print a single integer  — the answer to the problem. Please note, that the answer for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

NoteIn the first test case, Alice can set $$$1,2,3$$$ or $$$4$$$ days as the number of days in a week.There are $$$6$$$ possible paintings shown in the picture, but there are only $$$4$$$ different shapes. So, the answer is $$$4$$$. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides.    In the last test case, be careful with the overflow issue, described in the output format.

import std.algorithm, std.conv, std.stdio, std.string;
void main () {
	foreach (i; 0..readln.strip.to!int) {
		int n, r;
		readf !(" %s %s") (n, r);
		int s = min (n, r + 1);
		writeln (s * (s - 1L) / 2 + (n <= r));
	}
}

import std.container: DList;
import std.algorithm: all, map, count, filter;
import std.range: iota;
import std.array: array;
import std.stdio;
import std.utf;

DList!string _words;
void read(T)(out T t)
{
  import std.stdio: readln;
  while(_words.empty)
    {
      import std.array: split;
      foreach(word; readln.split)
        {
          _words.insertBack(word);
        }
    }
  import std.conv: to;
  string word = _words.front;
  _words.removeFront;
  t = to!T(word);
}

void main()
{
  int t;
  read(t);
  while(t--)
    {
      long n, r;
      read(n), read(r);
      // k < n
      // k = 1: 1
      // k = 2: 2
      // k = 3: 3
      // ...
      // k = n - 1: n - 1
      // (n - 1)n / 2
      // k >= n
      // k = n: 1
      // k = n + 1: 1
      // ...
      // k = r: r - n
      // (r - n + 1)(r - n + 2) / 2

      if (r >= n)
        {
          writeln((n - 1)*n/2 + 1);
        }
      else
        {
          writeln(r * (r + 1) / 2);
        }
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto x = min(n-1, r);
		ans[ti] = x * (x+1) / 2;
		if (r >= n)
			++ans[ti];
	}

	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}


Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).You are given an $$$n \times m$$$ grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.

The first line contains $$$t$$$ ($$$1 \le t \le 100$$$), the number of test cases. In each test case, the first line will contain $$$n$$$ ($$$1 \le n \le 50$$$) and $$$m$$$ ($$$1 \le m \le 50$$$), the height and width of the grid respectively. The next $$$n$$$ lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'.

For each test case, output "YES" if there is a valid grid or "NO" if there is not. If there is, output the grid on the next $$$n$$$ lines. If there are multiple answers, print any. In the output, the "YES"s and "NO"s are case-insensitive, meaning that outputs such as "yEs" and "nO" are valid. However, the grid is case-sensitive.

YES
WRWRWR
RWRWRW
WRWRWR
RWRWRW
NO
YES
R
W
R
W
R

NoteThe answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid.

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
multitest_end:
  while(tests--) {
    int n, m;
    readf!"%s %s\n"(n, m);
    char[][] grid;
    foreach(i; 0 .. n) {
      grid ~= readln.strip.dup;
    }
    foreach(k; 0 .. 2) {
      auto answer = new char[][](n, m);
      foreach(i; 0 .. n) {
        foreach(j; 0 .. m) {
          answer[i][j] = "RW"[(i + j + k) % 2];
        }
      }
      bool good = true;
      foreach(i; 0 .. n) {
        foreach(j; 0 .. m) {
          good &= (grid[i][j] == answer[i][j] || grid[i][j] == '.');
        }
      }
      if (good) {
        writefln!"YES\n%-(%s\n%)"(answer);
        continue multitest_end;
      }
    }
    writefln!"NO";
  }

} // main

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	int n = readInt!int;
	int m = readInt!int;
	auto mat = new char[][](n);
	foreach(i; 0 .. n)
	{
		mat[i] = cast(char[]) readString;
	}
	int color = 0;
	foreach(i; 0 .. n)
		foreach(j; 0 .. m)
			if (mat[i][j] != '.')
				color = ((i + j + (mat[i][j] == 'R')))%2;
	bool can = true;
	foreach(i; 0 .. n)
		foreach(j; 0 .. m)
			if (mat[i][j] != '.')
			{
				if ((mat[i][j] == 'R') != (i + j + color)%2)
				{
					can = false;
				}
			}
	if (!can) return "NO".writeln;
	"YES".writeln;
	foreach(i; 0 .. n)
	{
		foreach(j; 0 .. m)
		{
			if ((i + j + color)%2 == 0) "W".write;
			else "R".write;
		}
		writeln;
	}
}

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

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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

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

bool check(string[][] a, int n, int m, bool r11)
{
  foreach (i ; 0 .. n) {
    foreach (j ; 0 .. m) {
      string expected = ((i + j) % 2 == 0) == r11 ? "R" : "W";
      if (a[i][j] != expected && a[i][j] != ".")
        return false;
    }
  }
  return true;
}

void fill(string[][] a, int n, int m, bool r11)
{
  string c1, c2;
  if (r11) {
    c1 = "R";
    c2 = "W";
  } else {
    c1 = "W";
    c2 = "R";
  }
  foreach (i ; 0 .. n) {
    foreach (j ; 0 .. m) {
      a[i][j] = (i + j) % 2 == 0 ? c1 : c2;
    }
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, m;
    readf!" %d %d "(n, m);
    string[][] a;
    foreach (i ; 0 .. n) {
      a ~= readln.strip.split("").array;
    }
    if (check(a, n, m, true)) {
      writeln("YES");
      fill(a, n, m, true);
      foreach (i ; 0 .. n) { writeln(a[i].join("")); }
    } else if (check(a, n, m, false)) {
      writeln("YES");
      fill(a, n, m, false);
      foreach (i ; 0 .. n) { writeln(a[i].join("")); }
    } else {
      writeln("NO");
    }
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		char [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.dup;
		}
		foreach (k; 0..2)
		{
			auto answer = new char [] [] (rows, cols);
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					answer[row][col] =
					    "RW"[(row ^ col ^ k) & 1];
				}
			}
			bool good = true;
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					if (answer[row][col] !=
					    board[row][col] &&
					    board[row][col] != '.')
					{
						good = false;
					}
				}
			}
			if (good)
			{
				writeln ("YES");
				writefln !("%-(%s\n%)") (answer);
				continue multitest_loop;
			}
		}
		writeln ("NO");
	}
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n, m;
    readf!"%s %s\n"(n, m);
    char[][] grid = new char[][n];
    foreach(ref str; grid) {
      str = readln.strip.dup;
    }
    int red = 0, white = 0;
    foreach(i; 0 .. n) {
      foreach(j; 0 .. m) {
        if (grid[i][j] == 'R') {
          red |= (1 << ((i + j) % 2));
        }
        else if (grid[i][j] == 'W') {
          white |= (1 << ((i + j) % 2));
        }
      }
    }
    if ((red & white) != 0) {
      "NO".writeln;
    }
    else {
      "YES".writeln;
      if (red == 0 && white == 0) {
        red = 1, white = 2;
      }
      else if (red == 0) {
        red = 3 - white;
      }
      else if (white == 0) {
        white = 3 - red;
      }
      foreach(i; 0 .. n) {
        foreach(j; 0 .. m) {
          if ((1 << ((i + j) % 2)) == red) {
            grid[i][j] = 'R';
          }
          else {
            grid[i][j] = 'W';
          }
        }
      }
      writefln!"%-(%s\n%)"(grid);
    }
  }

} // main


Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.

The first line of the input contains a string s (1 ≤ |s| ≤ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.

If there is no way of replacing '#' characters which leads to a beautiful string print  - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.

Note|s| denotes the length of the string s.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;
    int n = cast(int)s.count!"a == '#'";

    int[] ans;

    int x;
    int open, close;
    foreach (i, c; s) {
        if (c == '(') open++;
        else if (c == ')') close++;
        else {
            assert(c == '#');
            if (x == n - 1) {
                int d = open - close;
                foreach (j; i + 1 .. s.length) {
                    d += (s[j] == '(' ? 1 : -1);
                }
                if (d <= 0) {
                    writeln(-1);
                    return;
                } else {
                    ans ~= d;
                    close += d;
                }
            } else {
                ans ~= 1;
                close++;
                x++;
            }
        }
        if (open < close) {
            writeln(-1);
            return;
        }
    }
    writefln("%(%s\n%)", ans);
}

module main;

import std.stdio, std.string;

void solve(char[] s)
{
    int cl = 0, cr = 0, sl = 0, sr = 0, pos = -1, cnt = 0;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '(')
        {
            ++ sl;
        }
        else if (s[i] == ')')
        {
            ++ sr;
        }
        else
        {
            pos = i;
            ++ cnt;
        }
    }
    int add = 0;
    auto ans = new int[cnt];
    int idx = 0;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '(')
        {
            ++ cl;
        }
        else if (s[i] == ')')
        {
            ++ cr;
        }
        else
        {
            if (i == pos)
            {
                int need = sl - (sr + add);
                if (need <= 0)
                {
                    writeln(-1);
                    return;
                }
                ans[idx] = need;
                add += need;
            }
            else
            {
                ans[idx] = 1;
                ++ add;
            }
            ++ idx;
        }
        if (cr + add > cl)
        {
            writeln(-1);
            return;
        }
    }
    if (cr + add != cl)
    {
        writeln(-1);
    }
    else
    {
        foreach (i, val; ans)
        {
            writeln(ans[i]);
        }
    }
}

int main(string[] args)
{
    char[] s;
    while (stdin.readln(s))
    {
        solve(chomp(s));
    }
	return 0;
}

module main;

import std.stdio, std.string;

void solve(char[] s)
{
    int[] ans;
    int pos = -1;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '#')
        {
            ans ~= 1;
            pos = i;
        }
    }
    int cl = 0, cr = 0;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '(')
        {
            ++ cl;
        }
        else
        {
            ++ cr;
        }
        if (cr > cl)
        {
            writeln(-1);
            return;
        }
    }
    ans[$ - 1] += cl - cr;
    cl = cr = 0;
    int idx = 0;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '(')
        {
            ++ cl;
        }
        else if (s[i] == ')')
        {
            ++ cr;
        }
        else
        {
            cr += ans[idx];
            ++ idx;
        }
        if (cr > cl)
        {
            writeln(-1);
            return;
        }
    }
    foreach (i, val; ans)
    {
        writeln(val);
    }
}

int main(string[] args)
{
    char[] s;
    while (stdin.readln(s))
    {
        solve(chomp(s));
    }
    return 0;
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;
    int n = cast(int)s.count!"a == '#'";

    int[] ans;

    int x;
    int open, close;
    foreach (i, c; s) {
        if (c == '(') open++;
        else if (c == ')') close++;
        else {
            assert(c == '#');
            if (x == n - 1) {
                int d = open - close;
                foreach (j; i + 1 .. s.length) {
                    d += (s[j] == '(' ? 1 : -1);
                }
                if (d <= 0) {
                    writeln(-1);
                    return;
                } else {
                    ans ~= d;
                }
            } else {
                ans ~= 1;
                close++;
                x++;
            }
        }
    }

    writefln("%(%s\n%)", ans);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    auto s = readln.chomp;
    int n = cast(int)s.count!"a == '#'";

    int[] ans;

    int x;
    int open, close;
    foreach (i, c; s) {
        if (c == '(') open++;
        else if (c == ')') close++;
        else {
            assert(c == '#');
            if (x == n - 1) {
                int d = open - close;
                foreach (j; i + 1 .. s.length) {
                    d += (s[j] == '(' ? 1 : -1);
                }
                if (d <= 0) {
                    writeln(-1);
                    return;
                } else {
                    ans ~= d;
                }
            } else {
                ans ~= 1;
                close++;
                x++;
            }
        }
    }

    x = 0; open = 0; close = 0;
    foreach (i, c; s) {
        if (c == '(') open++;
        else if (c == ')') close++;
        else {
            assert(c == '#');
            close += ans[x];
        }
        if (open < close) {
            writeln(-1); return;
        }
    }

    writefln("%(%s\n%)", ans);
}

module main;

import std.stdio, std.string;

void solve(char[] s)
{
    int[] ans;
    int pos = -1;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '#')
        {
            ans ~= 1;
            pos = i;
        }
    }
    int cl = 0, cr = 0;
    foreach (i; 0 .. s.length)
    {
        if (s[i] == '(')
        {
            ++ cl;
        }
        else
        {
            ++ cr;
        }
        if (cr > cl)
        {
            writeln(-1);
            return;
        }
    }
    ans[$ - 1] += cl - cr;
    foreach (i, val; ans)
    {
        writeln(val);
    }
}

int main(string[] args)
{
    char[] s;
    while (stdin.readln(s))
    {
        solve(chomp(s));
    }
    return 0;
}


Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \{1, 4, 3\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \{1, 3, 4, 4, 5, 7, 8\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line which contains $$$7$$$ integers $$$b_1, b_2, \dots, b_7$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$).  Additional constraint on the input: there exists at least one array $$$a$$$ which yields this array $$$b$$$ as described in the statement.

For each test case, print $$$3$$$ integers — $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$. If there can be several answers, print any of them.

NoteThe subsequence of the array $$$a$$$ is a sequence that can be obtained from $$$a$$$ by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $$$3$$$ has exactly $$$7$$$ different non-empty subsequences.

immutable multi = true;

void solve(int tc)
{
  auto b = ma(7, readInt!int);
  auto bs = redBlackTree!(true, int)(b);
  int[3] a;
  a[0] = b[0];
  a[1] = b[1];
  bs.removeKey(a[0]);
  bs.removeKey(a[1]);
  bs.removeKey(a[0] + a[1]);
  a[2] = bs.front;
  foreach(ai; a) write(ai, " ");
  writeln;
}

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

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

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

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

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto b = readln.splitter.map!(to!int).array;
    writefln("%d %d %d", b[0], b[1], b.back - b[0] - b[1]);
  }
}

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

void solve(){
    auto arr = scanArray;
    auto summ = arr[6];
    long a = summ - arr[5];
    long b = summ - arr[4];
    long c = summ - a - b;
    writeln(a, " ", b, " ", c);
}

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

/**************    *****    That's All Folks!    *****    **************/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
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");


Given an array $$$a$$$ of $$$n$$$ integers, find a range of values $$$[x, y]$$$ ($$$x \le y$$$), and split $$$a$$$ into exactly $$$k$$$ ($$$1 \le k \le n$$$) subarrays in such a way that:  Each subarray is formed by several continuous elements of $$$a$$$, that is, it is equal to $$$a_l, a_{l+1}, \ldots, a_r$$$ for some $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$).  Each element from $$$a$$$ belongs to exactly one subarray.  In each subarray the number of elements inside the range $$$[x, y]$$$ (inclusive) is strictly greater than the number of elements outside the range. An element with index $$$i$$$ is inside the range $$$[x, y]$$$ if and only if $$$x \le a_i \le y$$$.  Print any solution that minimizes $$$y - x$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3 \cdot 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$ and the number of subarrays required in the partition. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print $$$k+1$$$ lines. In the first line, print $$$x$$$ and $$$y$$$ — the limits of the found range. Then print $$$k$$$ lines, the $$$i$$$-th should contain $$$l_i$$$ and $$$r_i$$$ ($$$1\leq l_i \leq r_i \leq n$$$) — the limits of the $$$i$$$-th subarray. You can print the subarrays in any order.

NoteIn the first test, there should be only one subarray, which must be equal to the whole array. There are $$$2$$$ elements inside the range $$$[1, 2]$$$ and $$$0$$$ elements outside, if the chosen range is $$$[1, 1]$$$, there will be $$$1$$$ element inside ($$$a_1$$$) and $$$1$$$ element outside ($$$a_2$$$), and the answer will be invalid.In the second test, it is possible to choose the range $$$[2, 2]$$$, and split the array in subarrays $$$(1, 3)$$$ and $$$(4, 4)$$$, in subarray $$$(1, 3)$$$ there are $$$2$$$ elements inside the range ($$$a_2$$$ and $$$a_3$$$) and $$$1$$$ element outside ($$$a_1$$$), in subarray $$$(4, 4)$$$ there is only $$$1$$$ element ($$$a_4$$$), and it is inside the range.In the third test, it is possible to choose the range $$$[5, 5]$$$, and split the array in subarrays $$$(1, 4)$$$, $$$(5, 7)$$$ and $$$(8, 11)$$$, in the subarray $$$(1, 4)$$$ there are $$$3$$$ elements inside the range and $$$1$$$ element outside, in the subarray $$$(5, 7)$$$ there are $$$2$$$ elements inside and $$$1$$$ element outside and in the subarray $$$(8, 11)$$$ there are $$$3$$$ elements inside and $$$1$$$ element outside.

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

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

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto A = readarray!int;

    int[] C = new int[N + 2];
    foreach (a; A) C[a]++;

    int[] S = new int[N + 3];
    for (int i = 0; i <= N+1; i++) {
        S[i + 1] = S[i] + C[i];
    }

    int cd = int.max;
    int[] range = [-1, -1];
    for (int x = 0; x <= N; x++) {
        int lb = x, ub = N + 1;
        bool check(int m) {
            return S[m] - S[x] >= K + (N - K + 1) / 2;
        }
        if (! check(ub)) continue;
        while (lb + 1 < ub) {
            int mid = (lb + ub) / 2;
            (check(mid) ? ub : lb) = mid;
        }
        int y = ub - 1;
        if (y - x < cd) {
            cd = y - x;
            range = [x, y];
        }
    }

    int x = range[0], y = range[1];
    assert(x >= 0 && y >= 0 && x <= y);

    Array!int ins, outs;
    int[] ans;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        if (x <= a && a <= y) {
            if (outs.empty) {
                ins ~= i;
            } else {
                outs.removeBack;
            }
        } else {
            if (ins.empty) {
                outs ~= i;
            } else {
                ins.removeBack;
            }
        }
        if (ins.length == 1) {
            ins.removeBack;
            ans ~= i;
            if (ans.length == K) break;
        }
    }
    writefln("%s %s", x, y);
    //writeln(ans);

    if (K == 1) {
        writefln("%s %s", 1, N);
    } else {
        for (int k = 0; k < K; k++) {
            int L, R;
            if (k == 0) {
                L = 0;
                R = ans[k];
            } else if (k == K - 1) {
                L = ans[k - 1] + 1;
                R = N - 1;
            } else {
                L = ans[k - 1] + 1;
                R = ans[k];
            }
            writefln("%s %s", L+1, R+1);
        }
    }

}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = a.dup;
		sort (b);

		int best = int.max;
		int bestX = -1;
		int bestY = -1;
		int num = 0;
		while (num < n - num + k)
		{
			num += 1;
		}
		foreach (val; num..n + 1)
		{
			auto x = b[val - num];
			auto y = b[val - 1];
			if (best > y - x)
			{
				best = y - x;
				bestX = x;
				bestY = y;
			}
		}

		int [] [] answer;
		int pos = 0;
		while (answer.length.to !(int) < k - 1)
		{
			answer ~= [pos + 1];
			int balance = 0;
			while (balance <= 0)
			{
				balance += (bestX <= a[pos] &&
				    a[pos] <= bestY) ? +1 : -1;
				pos += 1;
			}
			answer.back ~= pos;
		}
		answer ~= [pos + 1, n];

		writeln (bestX, " ", bestY);
		foreach (const ref line; answer)
		{
			writefln !("%(%s %)") (line);
		}
	}
}

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

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

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto A = readarray!int;

    int[] C = new int[N + 2];
    foreach (a; A) C[a]++;

    int[] S = new int[N + 3];
    for (int i = 0; i <= N+1; i++) {
        S[i + 1] = S[i] + C[i];
    }

    int cd = int.max;
    int[] range = [-1, -1];
    for (int x = 0; x <= N; x++) {
        int lb = x, ub = N + 1;
        bool check(int m) {
            return S[m] - S[x] >= K + (N - K + 1) / 2;
        }
        if (! check(ub)) continue;
        while (lb + 1 < ub) {
            int mid = (lb + ub) / 2;
            (check(mid) ? ub : lb) = mid;
        }
        int y = ub - 1;
        if (y - x < cd) {
            cd = y - x;
            range = [x, y];
        }
    }

    int x = range[0], y = range[1];
    assert(x >= 0 && y >= 0 && x <= y);

    Array!int ins, outs;
    int[] ans;
    for (int i = 0; i < N; i++) {
        int a = A[i];
        if (x <= a && a <= y) {
            if (outs.empty) {
                ins ~= i;
            } else {
                outs.removeBack;
            }
        } else {
            if (ins.empty) {
                outs ~= i;
            } else {
                ins.removeBack;
            }
        }
        if (ins.length == 1) {
            ins.removeBack;
            ans ~= i;
            if (ans.length == K) break;
        }
    }
    writefln("%s %s", x, y);
    //writeln(ans);

    for (int k = 0; k < K; k++) {
        int L, R;
        if (k == 0) {
            L = 0;
            R = ans[k];
        } else if (k == K - 1) {
            L = ans[k - 1] + 1;
            R = N - 1;
        } else {
            L = ans[k - 1] + 1;
            R = ans[k];
        }
        writefln("%s %s", L+1, R+1);
    }

}

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


This is the easy version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the example it's not possible to place ice spheres in any order so that Sage would buy $$$3$$$ of them. If the ice spheres are placed like this $$$(3, 1, 4, 2, 5)$$$, then Sage will buy two spheres: one for $$$1$$$ and one for $$$2$$$, because they are cheap.

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

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

void solve(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    arr.sort();
    ll[] res = new ll[](n);
    foreach(i; 0..n/2){
        res[2*i + 1] = arr[i];
    }
    foreach(i;(n/2)..n){
        res[2*(i - n/2)] = arr[i];
    }
    ll num = 0;
    foreach(i; 1..n-1){
        if(res[i] < res[i-1] && res[i] < res[i+1]){
            ++num;
        }
    }
    writeln(num);
    foreach(el; res){
        write(el, " ");
    }
    writeln;
}

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

// Vicfred
// https://codeforces.com/contest/1419/problem/D1
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.container;
import std.stdio;
import std.string;

void main() {
    long n = readln.chomp.to!long;

    long[] a = readln.split.map!(to!long).array;
    a.sort;

    auto dlist = DList!long(a);

    long[] solution;

    for(int i = 0; i < n; i++) {
        if(i % 2 == 0) {
            solution ~= dlist.back;
            dlist.removeBack;
        } else {
            solution ~= dlist.front;
            dlist.removeFront;
        }
    }

    int ans = 0;
    for(int i = 1; i + 1 < n; i++) {
        if(solution[i] < solution[i - 1] &&
           solution[i] < solution[i + 1])
            ans += 1;
    }
    ans.writeln;
    foreach(item; solution)
        writef("%s ", item);
    "".writeln;
}

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

void main()
{
    auto N = readln.chomp.to!int;
    auto AS = readln.split.to!(int[]);
    sort!"a > b"(AS);

    auto BS = new int[](N);
    int i, j;
    while (j < N) {
        BS[j] = AS[i];
        ++i;
        j += 2;
    }
    foreach (k; 0..N) if (BS[k] == 0) BS[k] = AS[i++];
    if (N%2 == 0) {
        int k = 1;
        while (k < N-1) {
            if (BS[k-1] > BS[k] && BS[k+1] > BS[k]) {
                k += 2;
                continue;
            }
            BS[$-1] = BS[k];
            BS[k] = AS[i-1];
            goto end;
        }
    }
    end:

    int r;
    foreach (k; 1..N-1) if (BS[k-1] > BS[k] && BS[k+1] > BS[k]) ++r;
    writeln(r);
    writeln(BS.to!(string[]).join(" "));
}

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 n = RD!int;
	auto a = RDA;
	a.sort();

	long[] ans;
	debug writeln(a);
	foreach (i; 0..n)
	{
		if (i % 2 == 0)
		{
			ans ~= a.back; a.popBack;
		}
		else
		{
			ans ~= a.front; a.popFront;
		}
		debug writeln(a);
	}

	writeln((ans.length-1) / 2);
	ans.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

// Vicfred
// https://codeforces.com/contest/1419/problem/D1
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.container;
import std.stdio;
import std.string;

void main() {
    long n = readln.chomp.to!long;

    long[] a = readln.split.map!(to!long).array;
    a.sort;

    auto dlist = DList!long(a);

    long[] solution;

    for(int i = 0; i < n; i++) {
        if(i % 2 == 0) {
            solution ~= dlist.back;
            dlist.removeBack;
        } else {
            solution ~= dlist.front;
            dlist.removeFront;
        }
    }

    (n/2).writeln;
    foreach(item; solution) {
        writef("%s ", item);
    } "".writeln;
}


CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example:  Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example:  $$$7 \mod 3=1$$$, because $$$7 = 3 \cdot 2 + 1$$$,  $$$15 \mod 4=3$$$, because $$$15 = 4 \cdot 3 + 3$$$.

The input consists of multiple test cases.  The first line contains an integer $$$t (t \geq 1)$$$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \leq n \leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$

For each test case, print the answer in a single line.

import std.algorithm, std.array, std.container, std.conv, std.math, std.numeric, std.random, std.range, std.stdio, std.string, std.typecons, core.bitop;
import std.algorithm, std.array, std.ascii, std.base64, std.bigint, std.bitmanip, std.compiler, std.complex, std.concurrency, std.container, std.conv, std.csv, std.datetime, std.demangle, std.digest, std.encoding, std.exception, std.file, std.format, std.functional, std.getopt, std.json, std.math, std.mathspecial, std.meta, std.mmfile, std.numeric, std.parallelism, std.path, std.process, std.random, std.range, std.regex, std.signals, std.stdint, std.stdio, std.string, std.system, std.traits, std.typecons, std.uni, std.uri, std.utf, std.uuid, std.variant, std.zip, std.zlib;

const long MAXN = 200000;
const long m = 1000000007;

void main()
{
  long[] factorial;
  factorial ~= 1;
  factorial ~= 1;
  factorial ~= 1;
  for (int i = 3; i <= MAXN; i++)
    factorial ~= factorial[i - 1] * i % m;

  long t;
  readf(" %d ", &t);
  while (t--) {
    int n;
    readf(" %d ", &n);
    writeln(factorial[2 * n]);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = 1;
		foreach (i; 2..n*2)
			ans[ti].modm(i+1);
	}

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


Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.

The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 ≤ ai ≤ 104) — elements of array a. The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 — the binary representation of number m. Number m equals .

Print a single integer — the maximum value of function f(x) for all .

NoteIn the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.

import std.stdio;
import std.algorithm.comparison;

__gshared int[100_100] lastone;
__gshared long[100_100] cumsum;
__gshared int[100_100] arr;

long solvit(int idx) {
    if (lastone[idx] == -1) return 0;
    if (lastone[idx] == 0) return cumsum[0];
    return max(cumsum[lastone[idx] - 1],
               arr[lastone[idx]] + solvit(lastone[idx] - 1));
}

int main() {
    debug stdin = File("in.txt", "r");

    char[100_100] bin;
    long binrep = 0, aml = 0;
    int n;
    readf(" %s\n", &n);
    foreach (i; 0 .. n) {
        readf(" %s", &arr[i]);
    }
    char[] pbin = bin;
    string dummy = readln;
    readln(pbin);
    cumsum[0] = arr[0];
    if (bin[0] == '1') lastone[0] = 0;
    else lastone[0] = -1;
    foreach (i; 1 .. n) {
        cumsum[i] = arr[i] + cumsum[i-1];
        if (bin[i] == '1') lastone[i] = i;
        else lastone[i] = lastone[i-1];
    }
    writeln(solvit(n - 1));

    return 0;
}

import std.stdio;
import std.algorithm.comparison;

__gshared int[100_100] lastone;
__gshared long[100_100] cumsum;
__gshared int[100_100] arr;

long solvit(int idx) {
    if (lastone[idx] == -1) return 0;
    if (lastone[idx] == 0) return cumsum[0];
    return max(cumsum[lastone[idx] - 1],
               arr[lastone[idx]] + solvit(lastone[idx] - 1));
}

int main() {
    debug stdin = File("in.txt", "r");

    int n;
    readf(" %s\n", &n);
    foreach (i; 0 .. n) {
        readf(" %s", &arr[i]);
    }
    string dummy = readln;
    string bin = readln();
    cumsum[0] = arr[0];
    if (bin[0] == '1') lastone[0] = 0;
    else lastone[0] = -1;
    foreach (i; 1 .. n) {
        cumsum[i] = arr[i] + cumsum[i-1];
        if (bin[i] == '1') lastone[i] = i;
        else lastone[i] = lastone[i-1];
    }
    writeln(solvit(n - 1));

    return 0;
}

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

void solve(int[] a, int[] s, int n)
{
    auto acc = new int[n];
    acc[0] = a[0];
    foreach (i; 1 .. n)
    {
        acc[i] = acc[i - 1] + a[i];
    }
    auto ans = 0, sum = 0;
    foreach (i; 0 .. n)
    {
        if (s[i] == 1)
        {
            if (n - i - 2 >= 0)
            {
                auto val = sum + acc[n - i - 2];
                ans = max(ans, val);
            }
            sum += a[n - i - 1];
        }
    }
    ans = max(ans, sum);
    writeln(ans);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        auto str = readln().strip();
        auto s = new int[n];
        foreach (i; 0 .. n)
        {
            s[i] = str[i] - '0';
        }
        s = s.reverse;
        solve(a, s, n);
    }
    return 0;
}

import std.stdio;
import std.algorithm.comparison;

int main() {
    debug stdin = File("in.txt", "r");

    int[100_100] arr;
    char[100_100] bin;
    long binrep = 0, aml = 0;
    int n;
    readf(" %s\n", &n);
    foreach (i; 0 .. n) {
        readf(" %s", &arr[i]);
    }
    char[] pbin = bin;
    string dummy = readln;
    readln(pbin);
    int lastone = -1;
    foreach (i; 0 .. n) {
        if (bin[i] == '1') lastone = i;
    }
    if (lastone == -1) {
        writeln("0");
        return 0;
    }
    foreach (i; 0 .. lastone) {
        if (bin[i] == '1') binrep += arr[i];
        aml += arr[i];
    }
    binrep += arr[lastone];
    writeln(max(binrep, aml));

    return 0;
}


There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters.  Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries:  Add xi liters of water to the pi-th vessel;  Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.

The first line contains integer n — the number of vessels (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an — the vessels' capacities (1 ≤ ai ≤ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m — the number of queries (1 ≤ m ≤ 2·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1 pi xi", the query of the second type is represented as "2 ki" (1 ≤ pi ≤ n, 1 ≤ xi ≤ 109, 1 ≤ ki ≤ n).

For each query, print on a single line the number of liters of water in the corresponding vessel.

import std.algorithm;
import std.stdio;
import std.bigint;
import std.container;
import std.functional;
import std.math;
import std.complex;
import std.range;
import std.string;

alias RedBlackTree!(int) IntSet;

void main() {
    int n, m;
    int [] a, amt;
    while (readf(" %d", &n)) {
        a = new int[](n);
        amt = new int[](n);
        amt[0..n] = 0;
        IntSet S = new IntSet(-1, -2);
        foreach(i; 0..n) {
            readf(" %d", &a[i]);
            S.insert(i);
        }
        readf(" %d", &m);
        foreach(i ; 0..m) {
            int t;
            readf(" %d", &t);
            if (t == 1) {
                int p, x;
                readf(" %d %d", &p, &x);
                --p;
                int f = min(x, a[p] - amt[p]);
                x -= f;
                amt[p] += f;
                if (amt[p] == a[p]) S.removeKey(p);
                if (x > 0) {
                    auto next = S.upperBound(p);
                    while (!next.empty() && x > 0) {
                        f = min(x, a[next.front()] - amt[next.front()]);
                        x -= f;
                        amt[next.front()] += f;
                        if (amt[next.front()] == a[next.front()]) S.removeKey(next.front());
                        next = S.upperBound(next.front());
                    }
                }
            } else {
                int k;
                readf(" %d", &k);
                writeln(amt[--k]);
            }
        }
    }
}

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)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto next = n.iota.map !(a => a + 1).array;
		a ~= 0;
		next ~= n;
		auto b = new int [n + 1];
		b[] = 0;
		int m;
		readf (" %s", &m);
		foreach (j; 0..m)
		{
			int t;
			readf (" %s", &t);
			if (t == 1)
			{
				int p, x;
				readf (" %s %s", &p, &x);
				p--;
				b[p] += x;
				while (p < n && b[p] > a[p])
				{
					b[next[p]] += b[p] - a[p];
					int q = next[p];
					if (b[next[p]] >= a[next[p]])
					{
						next[p] = next[next[p]];
					}
					b[p] = a[p];
					p = q;
				}
			}
			else if (t == 2)
			{
				int k;
				readf (" %s", &k);
				k--;
				writeln (b[k]);
			}
			else
			{
				enforce (false);
			}
		}
	}
}

import std.algorithm;
import std.stdio;
import std.bigint;
import std.container;
import std.functional;
import std.math;
import core.memory;
import std.complex;
import std.range;
import std.string;

alias RedBlackTree!(int) IntSet;

void main() {
    int n, m;
    int [] a, amt;
    while (readf(" %d", &n)) {
        a = new int[](n);
        amt = new int[](n);
        amt[0..n] = 0;
        IntSet S = new IntSet(-1, -2);
        foreach(i; 0..n) {
            readf(" %d", &a[i]);
            S.insert(i);
        }
        readf(" %d", &m);
        foreach(i ; 0..m) {
            int t;
            readf(" %d", &t);
            if (t == 1) {
                int p, x;
                readf(" %d %d", &p, &x);
                --p;
                int f = min(x, a[p] - amt[p]);
                x -= f;
                amt[p] += f;
                if (amt[p] == a[p]) S.removeKey(p);
                if (x > 0) {
                    auto next = S.upperBound(p);
                    foreach (j; next) {
                        if (x == 0) break;
                        f = min(x, a[j] - amt[j]);
                        x -= f;
                        amt[j] += f;
                        if (amt[j] == a[j]) S.removeKey(j);
                    }
                }
            } else {
                int k;
                readf(" %d", &k);
                --k;
                writeln(amt[k]);
            }
        }
    }
}

import std.algorithm;
import std.stdio;
import std.bigint;
import std.container;
import std.functional;
import std.math;
import std.complex;
import std.range;
import std.string;

alias RedBlackTree!(int) IntSet;

void main() {
    int n, m;
    int [] a, amt;
    while (readf(" %d", &n)) {
        a = new int[](n);
        amt = new int[](n);
        IntSet S = new IntSet;
        S.insert(-1);
        S.insert(-2);
        foreach(i; 0..n) {
            readf(" %d", &a[i]);
            S.insert(i);
        }
        readf(" %d", &m);
        foreach(i ; 0..m) {
            int t;
            readf(" %d", &t);
            if (t == 1) {
                int p, x;
                readf(" %d %d", &p, &x);
                --p;
                auto next = S.upperBound(p);
                int f = min(x, a[p] - amt[p]);
                x -= f;
                amt[p] += f;
                if (amt[p] == a[p] && !S.empty()) S.removeKey(p);
                if (x > 0) {
                    foreach (j; next) {
                        if (x == 0) break;
                        f = min(x, a[j] - amt[j]);
                        x -= f;
                        amt[j] += f;
                        if (amt[j] == a[j]) S.removeKey(j);
                    }
                }
            } else {
                int p;
                readf(" %d", &p);
                --p;
                writeln(amt[p]);
            }
        }
    }
}


Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of p·ai + q·aj + r·ak for given p, q, r and array a1, a2, ... an such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.

First line of input contains 4 integers n, p, q, r ( - 109 ≤ p, q, r ≤ 109, 1 ≤ n ≤ 105). Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≤ ai ≤ 109).

Output a single integer the maximum value of p·ai + q·aj + r·ak that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.

NoteIn the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.

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

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

void main()
{
	int n, p, q, r;
	loop: while (read(n, p, q, r))
	{
		auto a = arread!int;
		auto mapr = a.cumulativeFold!(max).array, masu = a.retro.cumulativeFold!(max).array;
		auto mipr = a.cumulativeFold!(min).array, misu = a.retro.cumulativeFold!(min).array;
		reverse(misu);
		reverse(masu);
		debug
		{
			writeln(a);
			writeln(mipr);
			writeln(mapr);
			writeln(misu);
			writeln(masu);
		}
		long ans = long.min;
		foreach (i; 0 .. n)
		{
			long x = q * 1L * a[i];
			if (p < 0)
				x += mipr[i] * 1L * p;
			else
				x += mapr[i] * 1L * p;
			if (r < 0)
				x += misu[i] * 1L * r;
			else
				x += masu[i] * 1L * r;
			ans = max(ans, x);
		}
		writeln(ans);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const P = readLong();
      const Q = readLong();
      const R = readLong();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      auto ls = new long[N + 1];
      auto rs = new long[N + 1];
      ls[0] = long.min;
      foreach (i; 0 .. N) {
        ls[i + 1] = max(ls[i], P * A[i]);
      }
      rs[N] = long.min;
      foreach_reverse (i; 0 .. N) {
        rs[i] = max(R * A[i], rs[i + 1]);
      }

      long ans = long.min;
      foreach (i; 0 .. N) {
        chmax(ans, ls[i + 1] + Q * A[i] + rs[i]);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


In an ICPC contest, balloons are distributed as follows:   Whenever a team solves a problem, that team gets a balloon.  The first team to solve a problem gets an additional balloon.  A contest has 26 problems, labelled $$$\textsf{A}$$$, $$$\textsf{B}$$$, $$$\textsf{C}$$$, ..., $$$\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.

For each test case, output a single integer — the total number of balloons that the teams received.

6

3

ABA

1

A

3

ORZ

5

BAAAA

4

BKPT

10

CODEFORCES

NoteIn the first test case, $$$5$$$ balloons are given out:   Problem $$$\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.  Problem $$$\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{B}$$$.  Problem $$$\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\textsf{A}$$$.  The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        int n;
        scanf("%d", &n);
        getchar();
        long res;
        auto s = readln.strip.to!(char[]);
        bool[char] solved;
        foreach(p; s) {
            auto tmp = (p in solved);
            if (tmp is null) {
                res += 2;
                solved[p] = true;
            }
            else {
                res += 1;
            }
        }
        writeln(res);
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;
		auto t = s.dup;
		writeln (s.length + t.byChar.sort.uniq.walkLength);
	}
}


A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game:  the game may result in a tie, then both teams get $$$1$$$ point;  one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case is described by one line containing one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of teams.

For each test case, print $$$\frac{n(n - 1)}{2}$$$ integers describing the results of the games in the following order: the first integer should correspond to the match between team $$$1$$$ and team $$$2$$$, the second — between team $$$1$$$ and team $$$3$$$, then $$$1$$$ and $$$4$$$, ..., $$$1$$$ and $$$n$$$, $$$2$$$ and $$$3$$$, $$$2$$$ and $$$4$$$, ..., $$$2$$$ and $$$n$$$, and so on, until the game between the team $$$n - 1$$$ and the team $$$n$$$. The integer corresponding to the game between the team $$$x$$$ and the team $$$y$$$ should be $$$1$$$ if $$$x$$$ wins, $$$-1$$$ if $$$y$$$ wins, or $$$0$$$ if the game results in a tie. All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.

NoteIn the first test case of the example, both teams get $$$1$$$ point since the game between them is a tie.In the second test case of the example, team $$$1$$$ defeats team $$$2$$$ (team $$$1$$$ gets $$$3$$$ points), team $$$1$$$ loses to team $$$3$$$ (team $$$3$$$ gets $$$3$$$ points), and team $$$2$$$ wins against team $$$3$$$ (team $$$2$$$ gets $$$3$$$ points).

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (n % 2)
		{
			foreach (i; 0..n*(n-1)/2)
			{
				if (i % 2 == 0)
					ans[ti] ~= 1;
				else
					ans[ti] ~= -1;
			}
		}
		else
		{
			auto draw = n-1;
			foreach (i; 0..n)
			{
				foreach (j; i+1..n)
				{
					auto x = i + j;
					if (j > draw)
						++x;
					if (j == draw)
						ans[ti] ~= 0;
					else if (x % 2)
						ans[ti] ~= 1;
					else
						ans[ti] ~= -1;

				}
				--draw;
			}
		}
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		int k = (n + 1) / 2;
		int [] ans;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				int d = j - i;
				ans ~= (d < k ? 1 : n - d < k ? -1 : 0);
			}
		}
		writefln !("%(%s %)") (ans);
	}
}


It is the hard version of the problem. The only difference is that in this version $$$1 \le n \le 300$$$.In the cinema seats can be represented as the table with $$$n$$$ rows and $$$m$$$ columns. The rows are numbered with integers from $$$1$$$ to $$$n$$$. The seats in each row are numbered with consecutive integers from left to right: in the $$$k$$$-th row from $$$m (k - 1) + 1$$$ to $$$m k$$$ for all rows $$$1 \le k \le n$$$. $$$1$$$$$$2$$$$$$\cdots$$$$$$m - 1$$$$$$m$$$$$$m + 1$$$$$$m + 2$$$$$$\cdots$$$$$$2 m - 1$$$$$$2 m$$$$$$2m + 1$$$$$$2m + 2$$$$$$\cdots$$$$$$3 m - 1$$$$$$3 m$$$$$$\vdots$$$$$$\vdots$$$$$$\ddots$$$$$$\vdots$$$$$$\vdots$$$$$$m (n - 1) + 1$$$$$$m (n - 1) + 2$$$$$$\cdots$$$$$$n m - 1$$$$$$n m$$$ The table with seats indices There are $$$nm$$$ people who want to go to the cinema to watch a new film. They are numbered with integers from $$$1$$$ to $$$nm$$$. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $$$i$$$-th person has the level of sight $$$a_i$$$. Let's define $$$s_i$$$ as the seat index, that will be given to $$$i$$$-th person. You want to give better places for people with lower sight levels, so for any two people $$$i$$$, $$$j$$$ such that $$$a_i < a_j$$$ it should be satisfied that $$$s_i < s_j$$$.After you will give seats to all people they will start coming to their seats. In the order from $$$1$$$ to $$$nm$$$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: $$$m = 5$$$, the person has the seat $$$4$$$ in the first row, the seats $$$1$$$, $$$3$$$, $$$5$$$ in the first row are already occupied, the seats $$$2$$$ and $$$4$$$ are free. The inconvenience of this person will be $$$2$$$, because he will go through occupied seats $$$1$$$ and $$$3$$$.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 300$$$) — the number of rows and places in each row respectively. The second line of each test case contains $$$n \cdot m$$$ integers $$$a_1, a_2, \ldots, a_{n \cdot m}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the sight level of $$$i$$$-th person. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal total inconvenience that can be achieved.

NoteIn the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is $$$1$$$.In the second test case the optimal seating looks like this:   In the third test case the optimal seating looks like this:   The number in a cell is the person's index that sits on this place.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = iota (n * m).map !(i => tuple (a[i], i)).array;
		sort (b);
		foreach (row; 0..n)
		{
			b[row * m..row * m + m]
			    .schwartzSort !(c => tuple (c[0], -c[1]));
		}
//		b.schwartzSort !(c => tuple (c[0], c[1]));
		debug {writeln (b);}

		long res = 0;
		foreach (row; 0..n)
		{
			auto d = b[row * m..row * m + m];
			foreach (i; 0..m)
			{
				foreach (j; i + 1..m)
				{
					res += (d[i][1] < d[j][1]);
				}
			}
		}
		writeln (res);
	}
}

immutable multi = true;

void solve(int)
{
	auto n = readInt!int;
	auto m = readInt!int;
	auto a = ma(n*m, readInt!int);
	int[2][][int] poss;
	int[int] cnt;
	foreach(i, ai; a) cnt[ai]++;
	auto sa = a.dup; sort(sa);
	auto ua = sa.uniq.array;
	foreach(i; 0 .. n)
	{
		foreach(j; 0 .. m)
		{
			assert(cnt[ua[0]] > 0);
			require(poss, ua[0], null) ~= [i, -j];
			cnt[ua[0]]--;
			if (cnt[ua[0]] == 0) ua = ua[1 .. $];
		}
	}
	auto used = new FenwickTree[](n);
	foreach(ref usedi; used)
		usedi = FenwickTree(m);
	long ans = 0;

	foreach(ai, ref pos; poss)
		sort(pos);
	debug writeln(poss);
	foreach(i, ai; a)
	{
		auto pos = poss[ai][0];
		poss[ai] = poss[ai][1 .. $];
		auto pi = pos[0];
		auto pj = -pos[1];
		ans += used[pi].sum(pj-1);
		used[pi].add(pj, 1);
	}
	ans.writeln;
}
struct FenwickTree {
	int[] bit;
	int n;

	this(int n) {
		this.n = n;
		bit = new int[](n);
	}

	int sum(int r) {
		int ret = 0;
		for (; r >= 0; r = (r & (r + 1)) - 1)
			ret += bit[r];
		return ret;
	}

	int sum(int l, int r) {
		return sum(r) - sum(l - 1);
	}

	void add(int idx, int delta) {
		for (; idx < n; idx = idx | (idx + 1))
			bit[idx] += delta;
	}
}
//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

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

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

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

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


You are given $$$n$$$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each $$$1 \le i \le n$$$ the color of the right cell of the $$$i$$$-th domino is different from the color of the left cell of the $$$((i \bmod n)+1)$$$-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of dominoes. The next $$$n$$$ lines describe dominoes. Each line contains two characters which represent the left and the right cell. Character B means that the corresponding cell is black, character W means that the corresponding cell is white, and ? means that the cell is yet to be colored.

Print a single integer — the answer to the problem.

NoteIn the first test case, there is only one domino, and we need the color of its right cell to be different from the color of its left cell. There is only one way to achieve this.In the second test case, there are only $$$2$$$ such colorings:BB WW and WB WB.

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

immutable long limit = 10 ^^ 5 + 3;
immutable long mod = 998_244_353;

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

long invMod (long a)
{
	return powMod (a, mod - 2);
}

long [] f;
long [] fi;

long choose (int n, int k)
{
	if (k < 0 || k > n)
	{
		return 0;
	}
	long res = f[n];
	res = (res * 1L * fi[k]) % mod;
	res = (res * 1L * fi[n - k]) % mod;
	return res;
}

void prepare ()
{
	long cur = 1;
	f = [];
	fi = [];
	foreach (i; 0..limit)
	{
		cur = (cur * 1L * (i + !i)) % mod;
		f ~= cur;
		fi ~= invMod (cur);
	}
}

void main ()
{
	prepare ();
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		int [3] [3] c;
		foreach (i; 0..n)
		{
			auto s = readln.strip;
			auto x = "BW?".countUntil (s.front).to !(int);
			auto y = "BW?".countUntil (s.back).to !(int);
			c[x][y] += 1;
		}

		auto q0 = c[2][0] + c[2][1] + c[2][2];
		auto q1 = c[0][2] + c[1][2] + c[2][2];
		auto b0 = c[0][0] + c[0][1] + c[0][2];
		auto w1 = c[0][1] + c[1][1] + c[2][1];
		long res = 0;
		foreach (k; 0..n + 1)
		{ // k "B*" and k "*W"
			int x = k - b0;
			int y = k - w1;
			long u = choose (q0, x);
			long v = choose (q1, y);
			long cur = (u * 1L * v) % mod;
//			writeln (k, ": ", x, " ", y, " ", u, " ", v, " ", cur);
			res = (res + cur) % mod;
		}

		long bad = 0;
		foreach (k; 1..n)
		{ // k "BW" and (n-k) "WB"
			if (c[0][0] > 0 || c[1][1] > 0)
			{
				break;
			}
			int x = k - c[0][2] - c[0][1];
			int y = (n - k) - c[1][2] - c[1][0];
			if (x < 0 || y < 0)
			{
				continue;
			}
			long cur = choose (c[2][2], x);
			bad = (bad + cur) % mod;
		}

		writeln ((res + mod - bad) % mod);
	}
}

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

immutable int limit = 10 ^^ 5 + 3;
immutable int mod = 998_244_353;

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

int invMod (int a)
{
	return powMod (a, mod - 2);
}

int [] f;
int [] fi;

int choose (int n, int k)
{
	if (k < 0 || k > n)
	{
		return 0;
	}
	int res = f[n];
	res = (res * 1L * fi[k]) % mod;
	res = (res * 1L * fi[n - k]) % mod;
	return res;
}

void prepare ()
{
	int cur = 1;
	f = [];
	fi = [];
	foreach (i; 0..limit)
	{
		cur = (cur * 1L * (i + !i)) % mod;
		f ~= cur;
		fi ~= invMod (cur);
	}
}

void main ()
{
	prepare ();
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		int [3] [3] c;
		foreach (i; 0..n)
		{
			auto s = readln.strip;
			auto x = "BW?".countUntil (s.front).to !(int);
			auto y = "BW?".countUntil (s.back).to !(int);
			c[x][y] += 1;
		}

		auto q0 = c[2][0] + c[2][1] + c[2][2];
		auto q1 = c[0][2] + c[1][2] + c[2][2];
		auto b0 = c[0][0] + c[0][1] + c[0][2];
		auto w1 = c[0][1] + c[1][1] + c[2][1];
		int res = 0;
		foreach (k; 0..n + 1)
		{ // k "B*" and k "*W"
			int x = k - b0;
			int y = k - w1;
			int u = choose (q0, x);
			int v = choose (q1, y);
			int cur = (u * 1L * v) % mod;
//			writeln (k, ": ", x, " ", y, " ", u, " ", v, " ", cur);
			res = (res + cur) % mod;
		}

		int bad = 0;
		foreach (k; 1..n)
		{ // k "BW" and (n-k) "WB"
			if (c[0][0] > 0 || c[1][1] > 0)
			{
				break;
			}
			int x = k - c[0][2] - c[0][1];
			int y = (n - k) - c[1][2] - c[1][0];
			if (x < 0 || y < 0)
			{
				continue;
			}
			int cur = choose (c[2][2], x);
			bad = (bad + cur) % mod;
		}

		writeln ((res + mod - bad) % mod);
	}
}


And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }
        int read_int() {
                return read_string.to!int;
        }

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

double distance(int x1, int y1, int x2, int y2) {
        double dist = sqrt((x2.to!double - x1.to!double) ^^ 2 + (y1.to!double - y2.to!double) ^^ 2);
        return dist;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int vb = cin.read_int;
                int vs = cin.read_int;

                int[] arr = new int[n];
                double[] time_s = new double[n];

                time_s[0] = 999999999;
                foreach (ref i; arr) i = cin.read_int;

                int ux = cin.read_int;
                int uy = cin.read_int;

                for (int i = 1; i < n; i++) {
                        // writeln(distance(arr[i], 0, ux, uy));
                        time_s[i] = (distance(arr[i], 0, ux, uy)) / vs;
                        // writeln(time_s[i]);
                }
                double min_total_time = 999999999;
                for (int i = 1; i < n; i++) {
                        double total_time = (arr[i] / vb.to!double) + time_s[i];
                        // writeln(total_time);
                        min_total_time = min(min_total_time, total_time);
                }
                // writeln(min_total_time);
                int ans = 0;
                double min_time = 999999999.0;
                for (int i = 1; i < n; i++) {
                        if (abs((arr[i] / vb.to!double) + time_s[i] - min_total_time) < 0.00001) {
                                if (time_s[i] < min_time) {
                                        min_time = time_s[i];
                                        ans = i;
                                }
                        }
                }
                writeln(ans + 1);
        }
}