You are given two integers $$$x$$$ and $$$y$$$ (it is guaranteed that $$$x > y$$$). You may choose any prime integer $$$p$$$ and subtract it any number of times from $$$x$$$. Is it possible to make $$$x$$$ equal to $$$y$$$?Recall that a prime number is a positive integer that has exactly two positive divisors: $$$1$$$ and this integer itself. The sequence of prime numbers starts with $$$2$$$, $$$3$$$, $$$5$$$, $$$7$$$, $$$11$$$.Your program should solve $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ lines follow, each describing a test case. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le y < x \le 10^{18}$$$).

For each test case, print YES if it is possible to choose a prime number $$$p$$$ and subtract it any number of times from $$$x$$$ so that $$$x$$$ becomes equal to $$$y$$$. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).

NoteIn the first test of the example you may choose $$$p = 2$$$ and subtract it once.In the second test of the example you may choose $$$p = 5$$$ and subtract it twice. Note that you cannot choose $$$p = 7$$$, subtract it, then choose $$$p = 3$$$ and subtract it again.In the third test of the example you may choose $$$p = 3$$$ and subtract it $$$333333333333333333$$$ times.

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto x = RD;
		auto y = RD;
		auto d = x - y;
		if (d == 1)
			ans[i] = false;
		else
			ans[i] = true;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush();
	debug readln();
}


Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.

The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.

Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.

4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis

import std.stdio;
import std.string;
import std.conv;
//------------------
auto change(string s){
  return s[0] ~ (s.length-2).to!string ~ s[$-1];
}

void main(){
  auto n = readln.chomp.to!int;
  foreach(i; 0..n){
    auto word = readln.chomp;
    if(word.length <= 10){ word.writeln; }
    else{ change(word).writeln; }
  }
}

import std.stdio;
import std.conv;
import std.string;
void main() {
  auto n = to!int(readln().chomp());
  for (auto i = 0; i < n; i++) {
    auto w = strip(readln());
    if (w.length > 10) {
      writeln(to!string(w[0])~to!string(w.length-2)~to!string(w[$-1]));
    } else {
      writeln(w);
    }
  }
}

import std.stdio : writeln, stdin;
import std.conv : to;
import std.range : dropOne;

void main()
{
    foreach(word; stdin.byLine.dropOne)
    {
        writeln(word.length > 10 ? word[0]~to!string(word.length-2)~word[$-1] : word);
    }
}

import std.stdio;

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

    for (int i = 0; i < n; ++i) {
        string s;
        readf("%s\n", &s);

        if (s.length <= 10) {
            writeln(s);
        } else {
            writefln("%c%d%c", s[0], s.length-2, s[s.length-1]);
        }
    }
}

module main;
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,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	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;
	}
	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;
	}
	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;
	}
	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;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{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;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~'\n', ptrs)==ptrs.length;}
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.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;
	loop:while(read(&n))
	{
		foreach(i;0..n)
		{
			auto s=readln.strip;
			if(s.length<=10)writeln(s);
			else writeln(s[0],s.length-2,s[$-1]);
		}
	}

}

import std.stdio;
import std.conv;

int main(string[] argv)
{
	string nstr = stdin.readln();
	nstr.length -= 1;
	int n = to!int(nstr);
	for (int i = 0; i < n; i++)
	{
		string l = stdin.readln();
		if (l[l.length - 1] == '\n')
			l.length -= 1;
		if (l.length > 10)
		{
			string r = "" ~ l[0];
			r ~= to!string(l.length - 2);
			r ~= l[l.length - 1];
			writeln(r);
		} else {
			writeln(l);
		}
	}
    return 0;
}

// https://codeforces.com/problemset/problem/71/A
// basic string manipulation
import std.stdio;
import std.string;
import std.conv;

void main() {
    auto n = readln.chomp.to!int;
    foreach(i; 0..n) {
        auto s = readln.chomp;
        if(s.length > 10)
            writeln(s[0], s.length-2, s[$-1]);
        else
            writeln(s);
    }
}

// https://codeforces.com/problemset/problem/71/A
import std.stdio;
import std.string;

void main() {
    int n;
    readf!"%d"(n);
    readln;
    while(n--) {
        string s = readln.strip;
        if(s.length > 10)
            writeln(s[0], s.length-2, s[$-1]);
        else
            writeln(s);
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n;
    readf!"%d"(n);
    readln;
    while(n--){
        string s=readln.strip;
        if(s.length>10){
            writeln(s[0],s.length-2,s[$-1]);
        }
        else writeln(s);
    }
}

import std.stdio;
void main()
{
    int n;
    readf("%d\n",&n);
    string x;
    for(int i=1;i<=n;i++)
    {
       // writeln("%d\n",i);
        readf("%s\n",&x);
        if(x.length>10){
            writefln("%c%d%c",x[0],x.length-2,x[x.length-1]);
        }
        else writeln(x);
    }
}

import std.stdio;
void main()
{
    int n;
    readf("%d\n",&n);
    string x;
    for(int i=1;i<=n;i++)
    {
       // writeln("%d\n",i);
        readf("%s\n",&x);
        if(x.length>10){
            writefln("%c%d%c\n",x[0],x.length-2,x[x.length-1]);
        }
        else writeln(x);
    }
}

import std.stdio;
import std.string;

void main(string[] argv) {
	int n;
	readf("%s\n", &n);
	string buff;
	foreach(int i; 0..n) {
		buff = readln('\n');
		if(buff.length <= 11)
			write(buff);
		else {
			writeln(buff[0], buff.length-3, buff[$-2]);
		}
	}
	return;
}

import std.stdio;
import std.conv;
import std.string;
void main() {
  auto n = to!int(readln().chomp());
  writeln("n=",n);
  for (auto i = 0; i < n; i++) {
    auto w = strip(readln());
    if (w.length >= 10) {
      writeln(to!string(w[0])~to!string(w.length-2)~to!string(w[$-1]));
    } else {
      writeln(w);
    }
  }
}

import std.stdio;
import std.conv;
import std.string;
void main() {
  auto n = to!int(readln().chomp());
  for (auto i = 0; i < n; i++) {
    auto w = strip(readln());
    if (w.length >= 10) {
      writeln(to!string(w[0])~to!string(w.length-2)~to!string(w[$-1]));
    } else {
      writeln(w);
    }
  }
}

// https://codeforces.com/problemset/problem/71/A
import std.stdio;
import std.string;

void main() {
    int n;
    readf!"%d"(n);
    readln;
    while(n--) {
        string s = readln.strip;
        if(s.length > 10)
            writeln(s[0], s.length-1, s[$-1]);
        else
            writeln(s);
    }
}

import std.stdio;
void main()
{
    int n;
    readf("%d",&n);
    string x;
    for(int i=1;i<=n;i++)
    {
       // writeln("%d\n",i);
        readf("%s",&x);
        if(x.length>10){
            writefln("%c%d%c\n",x[0],x.length-2,x[x.length-1]);
        }
        else writeln(x),writeln("\n");
    }
}

import std.stdio;
import std.string;

void main(string[] argv) {
    int n;
    readf("%s\n", &n);
    string buff;
    foreach(int i; 0..n) {
        buff = readln('\n');
        if(buff.length < 10)
            write(buff);
        else {
            writeln(buff[0], buff.length-3, buff[$-2]);
        }
    }
    return;
}

import std.stdio;
import std.string;

void main(string[] argv) {
	int n;
	readf("%s\n", &n);
	string buff;
	foreach(int i; 0..n) {
		buff = readln('\n');
		if(buff.length <= 10)
			write(buff);
		else {
			writeln(buff[0], buff.length-3, buff[$-2]);
		}
	}
	return;
}


On the well-known testing system MathForces, a draw of $$$n$$$ rating units is arranged. The rating will be distributed according to the following algorithm: if $$$k$$$ participants take part in this event, then the $$$n$$$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain — it is not given to any of the participants.For example, if $$$n = 5$$$ and $$$k = 3$$$, then each participant will recieve an $$$1$$$ rating unit, and also $$$2$$$ rating units will remain unused. If $$$n = 5$$$, and $$$k = 6$$$, then none of the participants will increase their rating.Vasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.For example, if $$$n=5$$$, then the answer is equal to the sequence $$$0, 1, 2, 5$$$. Each of the sequence values (and only them) can be obtained as $$$\lfloor n/k \rfloor$$$ for some positive integer $$$k$$$ (where $$$\lfloor x \rfloor$$$ is the value of $$$x$$$ rounded down): $$$0 = \lfloor 5/7 \rfloor$$$, $$$1 = \lfloor 5/5 \rfloor$$$, $$$2 = \lfloor 5/2 \rfloor$$$, $$$5 = \lfloor 5/1 \rfloor$$$.Write a program that, for a given $$$n$$$, finds a sequence of all possible rating increments.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each line contains an integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the total number of the rating units being drawn.

Output the answers for each of $$$t$$$ test cases. Each answer should be contained in two lines. In the first line print a single integer $$$m$$$ — the number of different rating increment values that Vasya can get. In the following line print $$$m$$$ integers in ascending order — the values of possible rating increments.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		int [] ans;
		ans ~= 0;
		for (int d = 1; d * d <= n; d++)
		{
			ans ~= d;
			ans ~= n / d;
		}
		sort (ans);
		ans = ans.uniq.array;
		writeln (ans.length);
		writefln ("%(%s %)", ans);
	}
}

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

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

void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		long n = rint;
		long[] ans;
		long i;
		for(i = 0; i * i <= n; i ++) ans ~= i;
		for(i -= 1; i >= 1; i --) if(ans[$ - 1] != n / i) ans ~= n / i;
		ans.length.writeln;
		ans.map!(to!string).array.join(" ").writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (i; 0..t)
	{
		auto n = RD;
		long[long] set;
		for (long j = 1; j*j <= n; ++j)
		{
			auto x = n / j;
			auto y = set.get(x, 0);
			set[x] = max(y, j);
			auto z = set.get(j, 0);
			set[j] = max(z, x);
		}
		auto keys = set.keys;
		ans[i].length = keys.length + 1;
		ans[i][0] = 0;
		foreach (j, key; keys)
		{
			ans[i][j+1] = set[key];
		}
		ans[i].sort();
	}

	foreach (i; 0..t)
	{
		writeln(ans[i].length);
		ans[i].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


Bertown is a city with $$$n$$$ buildings in a straight line.The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length $$$n$$$, where the $$$i$$$-th character is "1" if there is a mine under the building number $$$i$$$ and "0" otherwise.Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered $$$x$$$ is activated, it explodes and activates two adjacent mines under the buildings numbered $$$x-1$$$ and $$$x+1$$$ (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes $$$a$$$ coins. He can repeat this operation as many times as you want.Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes $$$b$$$ coins. He can also repeat this operation as many times as you want.The sapper can carry out operations in any order.You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city.

The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 1000$$$) — the cost of activating and placing one mine, respectively. The next line contains a map of mines in the city — a string consisting of zeros and ones. The sum of the string lengths for all test cases does not exceed $$$10^5$$$.

For each test case, output one integer — the minimum number of coins that the sapper will have to pay.

NoteIn the second test case, if we place a mine under the fourth building and then activate it, then all mines on the field are activated. The cost of such operations is six, $$$b=1$$$ coin for placing a mine and $$$a=5$$$ coins for activating.

import std.algorithm, std.container, std.range, std.array, std.ascii, std.bigint, std.conv, std.format, std.math, std.random, std.stdio, std.string, std.typecons;

void main() {
  long t, a, b;
  string s;
  t.readf!" %d";
  while (t--) {
    a.readf!" %d";
    b.readf!" %d";
    s.readf!" %s\n";

    long total, zeros;
    bool can_connect;
    foreach (i, c; s) {
      if (c == '1') {
        if (i == 0) {
          total += a;
        } else if (s[i - 1] == '1') {
          continue;
        } else {
          assert(zeros > 0);
          total += can_connect ? min(a, zeros * b) : a;
        }
        can_connect = true;
        zeros = 0;
      } else {
        zeros++;
      }
    }
    total.writeln;
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int l = -1, r;
		foreach (i; 0..n)
		{
			if (s[i] == '1')
			{
				l = i;
				break;
			}
		}
		foreach_reverse (i; 0..n)
		{
			if (s[i] == '1')
			{
				r = i+1;
				break;
			}
		}
		if (l == -1) continue;

		ans[ti] = a;
		int cnt;
		foreach (i; l..r)
		{
			debug writeln("ans:", ans[ti]);
			if (s[i] == '0')
				++cnt;
			else
			{
				ans[ti] += min(a, b*cnt);
				cnt = 0;
			}
		}
	}

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


One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.A positive integer $$$a$$$ is initially on the screen. The player can put a coin into the machine and then add $$$1$$$ to or subtract $$$1$$$ from any two adjacent digits. All digits must remain from $$$0$$$ to $$$9$$$ after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add $$$1$$$ to $$$9$$$, to subtract $$$1$$$ from $$$0$$$ and to subtract $$$1$$$ from the leading $$$1$$$. Once the number on the screen becomes equal to $$$b$$$, the player wins the jackpot. $$$a$$$ and $$$b$$$ have the same number of digits.Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) standing for the length of numbers $$$a$$$ and $$$b$$$. The next two lines contain numbers $$$a$$$ and $$$b$$$, each one on a separate line ($$$10^{n-1} \le a, b < 10^n$$$).

If it is impossible to win the jackpot, print a single integer $$$-1$$$. Otherwise, the first line must contain the minimal possible number $$$c$$$ of coins the player has to spend. $$$\min(c, 10^5)$$$ lines should follow, $$$i$$$-th of them containing two integers $$$d_i$$$ and $$$s_i$$$ ($$$1\le d_i\le n - 1$$$, $$$s_i = \pm 1$$$) denoting that on the $$$i$$$-th step the player should add $$$s_i$$$ to the $$$d_i$$$-th and $$$(d_i + 1)$$$-st digits from the left (e. g. $$$d_i = 1$$$ means that two leading digits change while $$$d_i = n - 1$$$ means that there are two trailing digits which change). Please notice that the answer may be very big and in case $$$c > 10^5$$$ you should print only the first $$$10^5$$$ moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.

NoteIn the first example, we can make a +1 operation on the two first digits, transforming number $$$\textbf{22}3$$$ into $$$\textbf{33}3$$$, and then make a -1 operation on the last two digits, transforming $$$3\textbf{33}$$$ into $$$3\textbf{22}$$$.It's also possible to do these operations in reverse order, which makes another correct answer.In the last example, one can show that it's impossible to transform $$$35$$$ into $$$44$$$.

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 A = readToken();
      const B = readToken();

      auto ds = new long[N];
      foreach (i; 0 .. N) {
        ds[i] = B[i] - A[i];
      }
      foreach (i; 0 .. N - 1) {
        ds[i + 1] -= ds[i];
      }
      debug {
        writeln("ds = ", ds);
      }
      if (ds[N - 1] == 0) {
        long total;
        foreach (i; 0 .. N - 1) {
          total += abs(ds[i]);
        }
        writeln(total);
        auto as = new int[N];
        foreach (i; 0 .. N) {
          as[i] = A[i] - '0';
        }
        auto oks = new bool[N - 1];
        auto set = new RedBlackTree!int;
        void check(int i) {
          if (0 <= i && i < N - 1) {
            if (ds[i] > 0) {
              oks[i] = (as[i] < 9 && as[i + 1] < 9);
            } else if (ds[i] < 0) {
              oks[i] = (as[i] > ((i == 0) ? 1 : 0) && as[i + 1] > 0);
            } else {
              oks[i] = false;
            }
            if (oks[i]) {
              set.insert(i);
            } else {
              set.removeKey(i);
            }
          }
        }
        foreach (i; 0 .. N - 1) {
          check(i);
        }
        foreach (iter; 0 .. min(total, 10^^5)) {
          debug {
            writeln("oks = ", oks);
          }
          assert(!set.empty);
          const i = set.front;
          if (ds[i] > 0) {
            writeln(i + 1, " ", 1);
            --ds[i];
            ++as[i];
            ++as[i + 1];
          } else if (ds[i] < 0) {
            writeln(i + 1, " ", -1);
            ++ds[i];
            --as[i];
            --as[i + 1];
          } else {
            assert(false);
          }
          check(i - 1);
          check(i);
          check(i + 1);
        }
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}


Harry, Ron and Hermione have figured out that Helga Hufflepuff's cup is a horcrux. Through her encounter with Bellatrix Lestrange, Hermione came to know that the cup is present in Bellatrix's family vault in Gringott's Wizarding Bank. The Wizarding bank is in the form of a tree with total n vaults where each vault has some type, denoted by a number between 1 to m. A tree is an undirected connected graph with no cycles.The vaults with the highest security are of type k, and all vaults of type k have the highest security.There can be at most x vaults of highest security. Also, if a vault is of the highest security, its adjacent vaults are guaranteed to not be of the highest security and their type is guaranteed to be less than k.Harry wants to consider every possibility so that he can easily find the best path to reach Bellatrix's vault. So, you have to tell him, given the tree structure of Gringotts, the number of possible ways of giving each vault a type such that the above conditions hold.

The first line of input contains two space separated integers, n and m — the number of vaults and the number of different vault types possible. (1 ≤ n ≤ 105, 1 ≤ m ≤ 109). Each of the next n - 1 lines contain two space separated integers ui and vi (1 ≤ ui, vi ≤ n) representing the i-th edge, which shows there is a path between the two vaults ui and vi. It is guaranteed that the given graph is a tree. The last line of input contains two integers k and x (1 ≤ k ≤ m, 1 ≤ x ≤ 10), the type of the highest security vault and the maximum possible number of vaults of highest security.

Output a single integer, the number of ways of giving each vault a type following the conditions modulo 109 + 7.

NoteIn test case 1, we cannot have any vault of the highest security as its type is 1 implying that its adjacent vaults would have to have a vault type less than 1, which is not allowed. Thus, there is only one possible combination, in which all the vaults have type 2.

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

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

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

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

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

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

int N, M, K, X;
int[] U, V;

int[][] G;
Mint[][][] dp;

void dfs(int u, int p) {
  auto crt = new Mint[][](X + 1, 3);
  crt[0][0] = 1;
  foreach (i; G[u]) {
    const v = U[i] ^ V[i] ^ u;
    if (v != p) {
      dfs(v, u);
      auto nxt = new Mint[][](X + 1, 3);
      foreach (x; 0 .. X + 1) foreach (y; 0 .. 3) {
        if (crt[x][y]) {
          foreach (dx; 0 .. X - x + 1) {
            nxt[x + dx][max(y, 0)] += crt[x][y] * dp[v][dx][0];
            nxt[x + dx][max(y, 2)] += crt[x][y] * dp[v][dx][1];
            nxt[x + dx][max(y, 1)] += crt[x][y] * dp[v][dx][2];
          }
        }
      }
      crt = nxt;
    }
  }
  foreach (x; 0 .. X + 1) {
    dp[u][x][0] = (crt[x][0] + crt[x][1] + crt[x][2]) * (K - 1);
    if (x >= 1) {
      dp[u][x][1] = crt[x - 1][0];
    }
    dp[u][x][2] = (crt[x][0] + crt[x][1]) * (M - K);
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      U = new int[N - 1];
      V = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
      }
      K = readInt();
      X = readInt();

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[U[i]] ~= i;
        G[V[i]] ~= i;
      }

      dp = new Mint[][][](N, X + 1, 3);
      dfs(0, -1);
      Mint ans;
      foreach (x; 0 .. X + 1) foreach (y; 0 .. 3) {
        ans += dp[0][x][y];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 < i2 < i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.

The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.

Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.

NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.typecons;

void main() {
  auto input1 = readln().split().map!(to!long);
  long n = input1[0], k = input1[1];
  long[] a = readln().split().map!(to!long).array;
  long[long][3] dp;
  foreach (v; a) {
    if (v % k == 0) {
      dp[2][v] += dp[1].get(v / k, 0);
      dp[1][v] += dp[0].get(v / k, 0);
    }
    dp[0][v] = dp[0].get(v, 0) + 1;
  }
  writeln(sum(dp[2].values));
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    if (K == 1) {
        long[long] cnt;
        foreach (a; A) {
            if (a in cnt) cnt[a]++;
            else cnt[a] = 1;
        }
        long ans = 0;
        foreach (v; cnt.values)
            if (v >= 3)
                ans += v * (v-1) * (v-2) / 6;
        writeln(ans);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
    }

    ans.writeln;
}

import std.stdio, std.string;

void solve(int[] a, int n, int k)
{
    int[long] cnt;
    auto lcnt = new int[n];
    foreach (i; 0 .. n)
    {
        lcnt[i] = 0;
        if (a[i] % k == 0)
        {
            auto v = a[i] / k;
            if (v in cnt)
            {
                lcnt[i] = cnt[v];
            }
        }
        if (!(a[i] in cnt))
        {
            cnt[a[i]] = 1;
        }
        else
        {
            ++ cnt[a[i]];
        }
    }
    cnt.clear();
    auto rcnt = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        rcnt[i] = 0;
        auto v = cast(long)a[i] * k;
        if (v in cnt)
        {
            rcnt[i] = cnt[v];
        }
        if (!(a[i] in cnt))
        {
            cnt[a[i]] = 1;
        }
        else
        {
            ++ cnt[a[i]];
        }
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lcnt[i] * rcnt[i];
    }
    writeln(ans);
}

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

import std.stdio, std.string;
import std.random;

class Treap(T)
{
    class Node
    {
        Node left;
        Node right;
        T val;
        int priority;
        int cnt;

        this()
        {
            left = right = null;
        }

        //int opCmp(Node node)
        //{
            //return this.priority - node.priority;
        //}

        int cmpPriority(int priority)
        {
            if (this.priority == priority) return 0;
            return this.priority < priority ? -1 : 1;
        }

        int cmpVal(T val)
        {
            if (this.val == val) return 0;
            return this.val < val ? -1 : 1;
        }
    }

    protected Node root;
    protected Xorshift rnd;

    public this()
    {
        root = null;
        rnd = Xorshift(1234567891);
    }

    protected void leftRotate(ref Node node)
    {
        if (!node.right) return;
        auto rightNode = node.right;
        if (rightNode)
        {
            node.right = rightNode.left;
            rightNode.left = node;
            node = rightNode;
        }
    }

    protected void rightRotate(ref Node node)
    {
        if (!node.left) return;
        auto leftNode = node.left;
        if (leftNode)
        {
            node.left = leftNode.right;
            leftNode.right = node;
            node = leftNode;
        }
    }

    protected Node find(T val)
    {
        return _find(root, val);
    }

    protected Node _find(Node node, T val)
    {
        if (!node) return null;
        auto ret = node.cmpVal(val);
        if (ret == 0) return node;
        if (ret == -1) return _find(node.right, val);
        return _find(node.left, val);
    }

    public void insert(T val)
    {
        _insert(root, val);
    }

    protected void _insert(ref Node node, T val)
    {
        if (!node)
        {
            node = new Node();
            node.val = val;
            node.priority = this.rnd.front;
            node.cnt = 1;
            this.rnd.seed(unpredictableSeed);
            return;
        }
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            ++ node.cnt;
            return;
        }
        if (ret == 1)
        {
            _insert(node.left, val);
            if (node.left.priority > node.priority)
            {
                rightRotate(node);
            }
        }
        else if (ret == -1)
        {
            _insert(node.right, val);
            if (node.right.priority > node.priority)
            {
                leftRotate(node);
            }
        }
    }

    public void remove(T val)
    {
        _remove(root, val);
    }

    protected void _remove(ref Node node, T val)
    {
        if (!node) return;
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            if (!node.left && !node.right)
            {
                node = null;
                return;
            }
            if (!node.left)
            {
                node = node.right;
                return;
            }
            if (!node.right)
            {
                node = node.left;
                return;
            }
            if (node.left.cmpPriority(node.right.priority) == 1)
            {
                rightRotate(node);
                _remove(node.right, val);
            }
            else
            {
                leftRotate(node);
                _remove(node.left, val);
            }
            return;
        }
        if (ret == -1)
        {
            _remove(node.right, val);
        }
        else
        {
            _remove(node.left, val);
        }
    }

    public void travel()
    {
        _travel(root);
    }

    protected void _travel(Node node)
    {
        if (!node) return;
        _travel(node.left);
        writeln(node.val);
        _travel(node.right);
    }

    public void clear()
    {
        while (root)
        {
            remove(root.val);
        }
    }

    public int getCount(T val)
    {
        auto node = find(val);
        if (!node) return 0;
        return node.cnt;
    }
}

void solve(int[] a, int n, int k)
{
    auto treap = new Treap!long();
    auto lcnt = new int[n];
    foreach (i; 0 .. n)
    {
        lcnt[i] = 0;
        if (a[i] % k == 0)
        {
            auto v = a[i] / k;
            lcnt[i] = treap.getCount(v);
        }
        treap.insert(cast(long)a[i]);
    }
    treap.clear();
    auto rcnt = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        auto v = cast(long)a[i] * k;
        rcnt[i] = treap.getCount(v);
        treap.insert(a[i]);
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lcnt[i] * rcnt[i];
    }
    writeln(ans);
}

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

import std.stdio, std.string;
import std.random;

class Treap(T)
{
    class Node
    {
        Node left;
        Node right;
        T val;
        int priority;
        int cnt;

        this()
        {
            left = right = null;
        }

        //int opCmp(Node node)
        //{
            //return this.priority - node.priority;
        //}

        int cmpPriority(int priority)
        {
            if (this.priority == priority) return 0;
            return this.priority < priority ? -1 : 1;
        }

        int cmpVal(T val)
        {
            if (this.val == val) return 0;
            return this.val < val ? -1 : 1;
        }
    }

    protected Node root;
    protected Xorshift rnd;

    public this()
    {
        root = null;
        rnd = Xorshift(1234567891);
    }

    protected void leftRotate(ref Node node)
    {
        if (!node.right) return;
        auto rightNode = node.right;
        if (rightNode)
        {
            node.right = rightNode.left;
            rightNode.left = node;
            node = rightNode;
        }
    }

    protected void rightRotate(ref Node node)
    {
        if (!node.left) return;
        auto leftNode = node.left;
        if (leftNode)
        {
            node.left = leftNode.right;
            leftNode.right = node;
            node = leftNode;
        }
    }

    protected Node find(T val)
    {
        return _find(root, val);
    }

    protected Node _find(Node node, T val)
    {
        if (!node) return null;
        auto ret = node.cmpVal(val);
        if (ret == 0) return node;
        if (ret == -1) return _find(node.right, val);
        return _find(node.left, val);
    }

    public void insert(T val)
    {
        _insert(root, val);
    }

    protected void _insert(ref Node node, T val)
    {
        if (!node)
        {
            node = new Node();
            node.val = val;
            node.priority = this.rnd.front;
            node.cnt = 1;
            this.rnd.seed(unpredictableSeed);
            return;
        }
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            ++ node.cnt;
            return;
        }
        if (ret == 1)
        {
            _insert(node.left, val);
            if (node.left.priority > node.priority)
            {
                rightRotate(node);
            }
        }
        else if (ret == -1)
        {
            _insert(node.right, val);
            if (node.right.priority > node.priority)
            {
                leftRotate(node);
            }
        }
    }

    public void remove(T val)
    {
        _remove(root, val);
    }

    protected void _remove(ref Node node, T val)
    {
        if (!node) return;
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            if (!node.left && !node.right)
            {
                node = null;
                return;
            }
            if (!node.left)
            {
                node = node.right;
                return;
            }
            if (!node.right)
            {
                node = node.left;
                return;
            }
            if (node.left.cmpPriority(node.right.priority) == 1)
            {
                rightRotate(node);
                _remove(node.right, val);
            }
            else
            {
                leftRotate(node);
                _remove(node.left, val);
            }
            return;
        }
        if (ret == -1)
        {
            _remove(node.right, val);
        }
        else
        {
            _remove(node.left, val);
        }
    }

    public void travel()
    {
        _travel(root);
    }

    protected void _travel(Node node)
    {
        if (!node) return;
        _travel(node.left);
        writeln(node.val);
        _travel(node.right);
    }

    public void clear()
    {
        while (root)
        {
            remove(root.val);
        }
    }

    public int getCount(T val)
    {
        auto node = find(val);
        if (!node) return 0;
        return node.cnt;
    }
}

void solve(int[] a, int n, int k)
{
    auto treap = new Treap!long();
    auto lcnt = new int[n];
    foreach (i; 0 .. n)
    {
        lcnt[i] = 0;
        if (a[i] % k == 0)
        {
            auto v = a[i] / k;
            lcnt[i] = treap.getCount(v);
        }
        treap.insert(cast(long)a[i]);
    }
    //treap.clear();
    treap = new Treap!long();
    auto rcnt = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        auto v = cast(long)a[i] * k;
        rcnt[i] = treap.getCount(v);
        treap.insert(a[i]);
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lcnt[i] * rcnt[i];
    }
    writeln(ans);
}

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

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm2[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2))
            ans += acm2[a/K];
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && a/K in acm1) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    ans.writeln;
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    if (K == 1) {
        writeln(N-2);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    ans.writeln;
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    if (K == 1) {
        long[long] cnt;
        foreach (a; A) {
            if (a in cnt) cnt[a]++;
            else cnt[a] = 1;
        }
        long ans = 0;
        foreach (v; cnt.values)
            if (v >= 3)
                ans += v * (v-1) * (v-2) / 6;
        writeln(ans);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    ans.writeln;
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    ans.writeln;
}


Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.

The only line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the set and the desired bitwise-xor, respectively.

If there is no such set, print "NO" (without quotes). Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.

NoteYou can read more about the bitwise-xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XORFor the first sample .For the second sample .

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

immutable int INF = 10 ^^ 9 + 23;

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

    if (n == 1) {
        writeln("YES");
        writeln(x);
        return;
    }

    if (n == 2) {
        if (x == 0) {
            writeln("NO");
            return;
        }

        writeln("YES");
        writeln((1 << 17), ' ', (1 << 17) + x);
        return;
    }

    int[] ans;
    int cxor = 0;
    foreach (i; 0 .. n-2) {
        ans ~= i;
        cxor ^= i;
    }

    if (cxor == x) {
        ans.back = n-2;
        cxor ^= (n-3) ^ (n-2);
    }

    ans ~= (1 << 17) ^ cxor;
    ans ~= (1 << 17) ^ x;

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

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

immutable int INF = 10 ^^ 9 + 23;

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

    if (n == 1) {
        writeln("YES");
        writeln(x);
        return;
    }

    if (n == 2) {
        if (x == 0) {
            writeln("NO");
            return;
        }

        writeln("YES");
        writeln(1 << 17, ' ', 1 << 17 + x);
        return;
    }

    int[] ans;
    int cxor = 0;
    foreach (i; 0 .. n-2) {
        ans ~= i;
        cxor ^= i;
    }

    if (cxor == x) {
        ans.back = n-1;
        cxor ^= (n-2) ^ (n-1);
    }

    ans ~= (1 << 17) ^ cxor;
    ans ~= (1 << 17) ^ x;

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

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

immutable int INF = 10 ^^ 9 + 23;

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

    if (n == 1) {
        writeln("YES");
        writeln(x);
        return;
    }

    if (n == 2) {
        if (x == 0) {
            writeln("NO");
            return;
        }

        writeln("YES");
        writeln(1 << 17, ' ', 1 << 17 + x);
        return;
    }

    int[] ans;
    int cxor = 0;
    foreach (i; 0 .. n-2) {
        ans ~= i;
        cxor ^= i;
    }

    if (cxor == x) {
        ans.back = n-2;
        cxor ^= (n-3) ^ (n-2);
    }

    ans ~= (1 << 17) ^ cxor;
    ans ~= (1 << 17) ^ x;

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


RedDreamer has an array $$$a$$$ consisting of $$$n$$$ non-negative integers, and an unlucky integer $$$T$$$.Let's denote the misfortune of array $$$b$$$ having length $$$m$$$ as $$$f(b)$$$ — the number of pairs of integers $$$(i, j)$$$ such that $$$1 \le i < j \le m$$$ and $$$b_i + b_j = T$$$. RedDreamer has to paint each element of $$$a$$$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $$$c$$$ and $$$d$$$ so that all white elements belong to $$$c$$$, and all black elements belong to $$$d$$$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $$$f(c) + f(d)$$$ is minimum possible.For example:  if $$$n = 6$$$, $$$T = 7$$$ and $$$a = [1, 2, 3, 4, 5, 6]$$$, it is possible to paint the $$$1$$$-st, the $$$4$$$-th and the $$$5$$$-th elements white, and all other elements black. So $$$c = [1, 4, 5]$$$, $$$d = [2, 3, 6]$$$, and $$$f(c) + f(d) = 0 + 0 = 0$$$;  if $$$n = 3$$$, $$$T = 6$$$ and $$$a = [3, 3, 3]$$$, it is possible to paint the $$$1$$$-st element white, and all other elements black. So $$$c = [3]$$$, $$$d = [3, 3]$$$, and $$$f(c) + f(d) = 0 + 1 = 1$$$. Help RedDreamer to paint the array optimally!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$T$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le T \le 10^9$$$) — the number of elements in the array and the unlucky integer, respectively.  The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the array.  The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$n$$$ integers: $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (each $$$p_i$$$ is either $$$0$$$ or $$$1$$$) denoting the colors. If $$$p_i$$$ is $$$0$$$, then $$$a_i$$$ is white and belongs to the array $$$c$$$, otherwise it is black and belongs to the array $$$d$$$. If there are multiple answers that minimize the value of $$$f(c) + f(d)$$$, print any of them.

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		int pos;
		foreach (i; 0..n)
		{
			if (a[i]*2 == T)
			{
				ans[ti][i] = pos;
				pos ^= 1;
			}
			else if (a[i]*2 < T)
				ans[ti][i] = 0;
			else
				ans[ti][i] = 1;
		}
	}

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


You have matrix a of size n × n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions:   for any numbers i, j (1 ≤ i, j ≤ n) the following inequality holds: aij ≥ 0;  . Matrix b is strictly positive, if for any numbers i, j (1 ≤ i, j ≤ n) the inequality bij > 0 holds. You task is to determine if there is such integer k ≥ 1, that matrix ak is strictly positive.

The first line contains integer n (2 ≤ n ≤ 2000) — the number of rows and columns in matrix a. The next n lines contain the description of the rows of matrix a. The i-th line contains n non-negative integers ai1, ai2, ..., ain (0 ≤ aij ≤ 50). It is guaranteed that .

If there is a positive integer k ≥ 1, such that matrix ak is strictly positive, print "YES" (without the quotes). Otherwise, print "NO" (without the quotes).

import std.algorithm, std.stdio;

void main ()
{
	stdin.setvbuf (16_384, _IOFBF);
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.stdio;

extern (C) nothrow int scanf (const char *, ...);

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		int m = (n + 31) / 32;
		auto a1 = new uint [] [] (n, m);
		auto a2 = new uint [] [] (n, m);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
				{
					a1[i][j >> 5] |= 1u << (j & 31);
					a2[j][i >> 5] |= 1u << (i & 31);
				}
			}

		auto b = new bool [n];
		uint [] [] a;

		void recur (int v)
		{
			b[v] = true;
			foreach (u; 0..n)
				if (!b[u] && (a[v][u >> 5] & (1u << (u & 31))))
					recur (u);
		}

		bool ok = true;

		b[] = false;
		a = a1;
		recur (0);
		ok &= all !("a == true") (b[]);

		b[] = false;
		a = a2;
		recur (0);
		ok &= all !("a == true") (b[]);

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.string;

extern (C) nothrow int printf (const char *, ...);
extern (C) nothrow int scanf (const char *, ...);

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		printf (toStringz (ok ? "YES\n" : "NO\n"));
	}
}

import std.algorithm, std.stdio;

extern (C) nothrow int printf (const char *, ...);

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}

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 (scanf (" %d", &n) > 0)
	{
		int m = (n + 31) / 32;
		auto a1 = new uint [] [] (n, m);
		auto a2 = new uint [] [] (n, m);
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
				{
					a1[i][j >> 5] |= 1u << (j & 31);
					a2[j][i >> 5] |= 1u << (i & 31);
				}
			}
		}

		auto b = new bool [n];
		uint [] [] a;

		void recur (int v)
		{
			b[v] = true;
			foreach (u; 0..n)
			{
				if (!b[u] && (a[v][u >> 5] & (1u << (u & 31))))
				{
					recur (u);
				}
			}
		}

		bool ok = true;

		b[] = false;
		a = a1;
		recur (0);
		ok &= all !("a == true") (b[]);

		b[] = false;
		a = a2;
		recur (0);
		ok &= all !("a == true") (b[]);

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.stdio;

void main ()
{
	stdin.setvbuf (16_384, _IOFBF);
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				scanf (" %d", &a[0][i][j]);
				a[1][j][i] = a[0][i][j];
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new uint [] [] [] (2, n, (n + 31) / 32);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
				{
					a[0][i][j >> 5] |= 1u << (j & 31);
					a[1][j][i >> 5] |= 1u << (i & 31);
				}
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] &&
					    (g[v][u >> 5] & (1u << (u & 31))))
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				scanf (" %d", &a[0][i][j]);
				a[1][j][i] = a[0][i][j];
			}

		bool ok = true;
		foreach (g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		writeln (ok ? "YES" : "NO");
	}
}


Marian is at a casino. The game at the casino works like this.Before each round, the player selects a number between $$$1$$$ and $$$10^9$$$. After that, a dice with $$$10^9$$$ faces is rolled so that a random number between $$$1$$$ and $$$10^9$$$ appears. If the player guesses the number correctly their total money is doubled, else their total money is halved. Marian predicted the future and knows all the numbers $$$x_1, x_2, \dots, x_n$$$ that the dice will show in the next $$$n$$$ rounds. He will pick three integers $$$a$$$, $$$l$$$ and $$$r$$$ ($$$l \leq r$$$). He will play $$$r-l+1$$$ rounds (rounds between $$$l$$$ and $$$r$$$ inclusive). In each of these rounds, he will guess the same number $$$a$$$. At the start (before the round $$$l$$$) he has $$$1$$$ dollar.Marian asks you to determine the integers $$$a$$$, $$$l$$$ and $$$r$$$ ($$$1 \leq a \leq 10^9$$$, $$$1 \leq l \leq r \leq n$$$) such that he makes the most money at the end.Note that during halving and multiplying there is no rounding and there are no precision errors. So, for example during a game, Marian could have money equal to $$$\dfrac{1}{1024}$$$, $$$\dfrac{1}{128}$$$, $$$\dfrac{1}{2}$$$, $$$1$$$, $$$2$$$, $$$4$$$, etc. (any value of $$$2^t$$$, where $$$t$$$ is an integer of any sign).

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2\cdot 10^5$$$) — the number of rounds. The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^9$$$), where $$$x_i$$$ is the number that will fall on the dice in the $$$i$$$-th round. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output three integers $$$a$$$, $$$l$$$, and $$$r$$$ such that Marian makes the most amount of money gambling with his strategy. If there are multiple answers, you may output any of them.

NoteFor the first test case, the best choice is $$$a=4$$$, $$$l=1$$$, $$$r=5$$$, and the game would go as follows.   Marian starts with one dollar.  After the first round, he ends up with $$$2$$$ dollars because the numbers coincide with the chosen one.  After the second round, he ends up with $$$4$$$ dollars because the numbers coincide again.  After the third round, he ends up with $$$2$$$ dollars because he guesses $$$4$$$ even though $$$3$$$ is the correct choice.  After the fourth round, he ends up with $$$4$$$ dollars again.  In the final round, he ends up $$$8$$$ dollars because he again guessed correctly. There are many possible answers for the second test case, but it can be proven that Marian will not end up with more than $$$2$$$ dollars, so any choice with $$$l = r$$$ with the appropriate $$$a$$$ is acceptable.

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

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

    int[][int] P;
    for (int i = 0; i < N; i++) {
        int x = X[i];
        P[x] ~= i;
    }
    int a = -1, l = -1, r = -1;
    long c = 0;
    foreach (x, ks; P) {
        if (ks.length == 1) {
            if (1 > c) {
                a = x;
                l = ks[0];
                r = ks[0];
            }
            continue;
        }
        int lb = 0, ub = 0; // closed
        while (true) {
            int f() {
                int c = ub - lb + 1;
                int r = ks[ub];
                int l = ks[lb];
                int v = 2 * c - (r - l + 1);
                return v;
            }
            int v = f();
            //writefln("%s %s -> %s", lb, ub, v);
            if (v > c) {
                a = x;
                l = ks[lb];
                r = ks[ub];
                c = v;
            }
            if (v > 0) {
                ub++;
            } else {
                lb = ub;
            }
            if (ub == ks.length) break;
        }
    }
    writefln("%s %s %s", a, l+1, r+1);
}

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

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

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

    int[][int] P;
    for (int i = 0; i < N; i++) {
        int x = X[i];
        P[x] ~= i;
    }
    int a = -1, l = -1, r = -1;
    long c = 0;
    foreach (x, ks; P) {
        if (ks.length == 1) {
            if (1 > c) {
                a = x;
                l = ks[0];
                r = ks[0];
            }
            continue;
        }
        int lb = 0, ub = 0; // closed
        while (true) {
            int f() {
                int c = ub - lb + 1;
                int r = ks[ub];
                int l = ks[lb];
                int v = 2 * c - (r - l + 1);
                return v;
            }
            int v = f();
            //writefln("%s %s -> %s", lb, ub, v);
            if (v > c) {
                a = x;
                l = ks[lb];
                r = ks[ub];
                c = v;
            }
            if (v >= 0) {
                ub++;
            } else {
                lb = ub + 1;
                ub = lb;
            }
            if (ub == ks.length) break;
        }
    }
    writefln("%s %s %s", a, l+1, r+1);
}

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


Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $$$n$$$ boxes, arranged in a row. The $$$i$$$-th box contains $$$a_i$$$ magazines. Some of the boxes are covered with lids, others are not. Suddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the $$$i$$$-th box was covered with a lid initially, he can either move the lid from the $$$i$$$-th box to the box $$$(i-1)$$$ (if it exists), or keep the lid on the $$$i$$$-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak.You have to calculate the maximum number of magazines Monocarp can save from the rain.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of the testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of boxes. The second line contains a string of $$$n$$$ characters 0 and/or 1. If the $$$i$$$-th character is 1, the $$$i$$$-th box is initially covered with a lid. If the $$$i$$$-th character is 0, the $$$i$$$-th box is initially not covered. The third line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the number of magazines in the $$$i$$$-th box. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print one integer — the maximum number of magazines Monocarp can save from the rain.

NoteIn the first testcase of the example, Monocarp can move the lid from the second box to the first box, so the boxes $$$1$$$, $$$3$$$ and $$$4$$$ are covered, and $$$10 + 8 + 9 = 27$$$ magazines are saved.In the second testcase, Monocarp can move the lid from the second box to the first box, then from the third box to the second box, then from the fifth box to the fourth box, and then from the sixth box to the fifth box. The boxes $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$ will be covered, so $$$20 + 10 + 30 + 20 = 80$$$ magazines can be saved.There are no lids in the third testcase, so it's impossible to save even a single magazine.

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, std.functional;

// Lengths of sequences satisfying the condition (moving to the right)
int[] seq_length_right(alias less = "a < b", T)(T[] a)
{
  if (a.length == 0)
    return new int[](0);
  auto tmp = new int[](a.length);
  int count = 1;
  tmp[$ - 1] = count;
  foreach_reverse (i ; 0 .. a.length - 1) {
    if (binaryFun!less(a[i], a[i + 1]))
      count++;
    else
      count = 1;
    tmp[i] = count;
  }
  return tmp;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = "0" ~ readln.strip;
    auto a = [0] ~ readln.splitter.map!(to!int).array;

    int[] x = seq_length_right!((a, b) => a == b)(s);

    long ans;
    size_t i = 0;
    while (i < x.length) {
      if (x[i] >= 1 && s[i] == '1') {
        ans += a[i - 1 .. i - 1 + x[i] + 1].sum - a[i - 1 .. i - 1 + x[i] + 1].minElement;
      }
      i += x[i];
    }
    writeln(ans);
  }
}

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;
import std.functional;

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

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 solve() {
    int n = read!int;
    char[] c = readln.strip.dup.to!(char[]);
    auto a = readarray!int;
    long res;
    for(int i = 0; i < n; i++) {
        int minV;
        if (c[i] == '0') {
            minV = a[i];
            int j = i + 1;
            if (j == n) {
                res += minV;
                break;
            }
            while(c[j] != '0') {
                if (a[j] < minV)
                    minV = a[j];
                j++;
                if (j == n)
                    break;
            }
            res += minV;
        }
    }
    writeln(sum(a) - res);
}

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

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 main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

enum long INF = 1L<<50;

void solve() {
    int N = read!int;
    auto S = read!string;
    auto A = readarray!long;

    auto f = new long[][](2, N+1);
    f[0][N] = 0; f[1][N] = -INF;
    for (int k = N - 1; k >= 0; k--) {
        f[0][k] = max(f[1][k+1] + A[k], f[0][k+1] + A[k] * (S[k] == '1'));
        if (S[k] == '1') {
            f[1][k] = max(f[1][k+1] + A[k], f[0][k+1]);
        } else {
            f[1][k] = -INF;
        }
    }
    writeln(max(f[0][0], f[1][0]));
}

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 n = readln.strip.to!int;
    auto s = readln.strip;
    auto a = readln.splitter.map!(to!int).array;
    auto h = redBlackTree!("a>b", true, int)();
    long ans;
    size_t j = 0;
    foreach (i ; 0 .. s.length) {
      if (s[i] != '0') {
        while (j <= i)
          h.insert(a[j++]);
        ans += h.front;
        h.removeFront;
      }
    }
    writeln(ans);
  }
}

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 n = readln.strip.to!int;
    auto s = readln.strip;
    auto pos = redBlackTree!("a<b", true, int)();
    foreach (i ; 0 .. s.length)
      if (s[i] != '0')
        pos.insert(cast(int)i);
    auto a = readln.splitter.map!(to!long).array;
    auto b = zip(a, iota(n)).array.sort!((x, y) => x[0] == y[0] ? x[1] < y[1] : x[0] > y[0]).array;
    long ans;
    foreach (x ; b) {
      auto tmp = pos.upperBound(x[1] - 1);
      if (tmp.empty)
        continue;
      ans += x[0];
      pos.removeKey(tmp.front);
    }
    writeln(ans);
  }
}

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 n = readln.strip.to!int;
    auto s = readln.strip;
    auto pos = redBlackTree!("a<b", true, int)();
    foreach (i ; 0 .. s.length)
      if (s[i] != '0')
        pos.insert(cast(int)i);
    auto a = readln.splitter.map!(to!long).array;
    auto b = zip(a, iota(n)).array.sort!((x, y) => x[0] == y[0] ? x[1] > y[1] : x[0] > y[0]).array;
    long ans;
    foreach (x ; b) {
      auto tmp = pos.upperBound(x[1] - 1);
      if (tmp.empty)
        continue;
      ans += x[0];
      pos.removeKey(tmp.front);
    }
    writeln(ans);
  }
}

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 n = readln.strip.to!int;
    auto s = readln.strip;
    auto pos = redBlackTree!("a<b", true, int)();
    foreach (i ; 0 .. s.length)
      if (s[i] != '0')
        pos.insert(cast(int)i);
    auto a = readln.splitter.map!(to!long).array;
    auto b = zip(a, iota(n)).array.sort!((x, y) => x[0] > y[0]).array;
    long ans;
    foreach (x ; b) {
      auto tmp = pos.upperBound(x[1] - 1);
      if (tmp.empty)
        continue;
      ans += x[0];
      pos.removeKey(tmp.front);
    }
    writeln(ans);
  }
}


Drazil is a monkey. He lives in a circular park. There are n trees around the park. The distance between the i-th tree and (i + 1)-st trees is di, the distance between the n-th tree and the first tree is dn. The height of the i-th tree is hi.Drazil starts each day with the morning run. The morning run consists of the following steps:  Drazil chooses two different trees  He starts with climbing up the first tree  Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it  Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees.If the two trees Drazil chooses are x-th and y-th, we can estimate the energy the morning run takes to him as 2(hx + hy) + dist(x, y). Since there are children on exactly one of two arcs connecting x and y, the distance dist(x, y) between trees x and y is uniquely defined.Now, you know that on the i-th day children play between ai-th tree and bi-th tree. More formally, if ai ≤ bi, children play around the trees with indices from range [ai, bi], otherwise they play around the trees with indices from .Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.

The first line contains two integer n and m (3 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting number of trees and number of days, respectively.  The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 109), the distances between consecutive trees. The third line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 109), the heights of trees. Each of following m lines contains two integers ai and bi (1 ≤ ai, bi ≤ n) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children.

For each day print the answer in a separate line.

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

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

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

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

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

immutable INF = 10L^^18 + 1;

int N, Q;
long[] D, H;
long[] DSum;

int segN;
Pair!(long, int)[] seg0, seg1;

Pair!(long, int) rangeMax(Pair!(long, int)[] seg, int a, int b) {
	Pair!(long, int) ret = pair(-INF, -1);
	for (a += segN, b += segN; a <= b; a >>= 1, b >>= 1) {
		if (  a & 1 ) chmax(ret, seg[a++]);
		if (!(b & 1)) chmax(ret, seg[b--]);
	}
	return ret;
}

long solve(int a, int b) {
debug{
writeln("solve ",a," ",b);
}
	long ret = -INF;
	const res0 = seg0.rangeMax(a, b);
	chmax(ret, res0.x + max(seg1.rangeMax(a, res0.y - 1).x, seg1.rangeMax(res0.y + 1, b).x));
	const res1 = seg1.rangeMax(a, b);
	chmax(ret, res1.x + max(seg0.rangeMax(a, res1.y - 1).x, seg0.rangeMax(res1.y + 1, b).x));
debug{
writeln("  ",res0," ",res1);
}
	return ret;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		Q = readInt;
		D = new long[N];
		foreach (i; 0 .. N) {
			D[i] = readLong;
		}
		H = new long[N];
		foreach (i; 0 .. N) {
			H[i] = readLong;
		}

		DSum = new long[N * 3];
		foreach (i; 0 .. N * 3 - 1) {
			DSum[i + 1] = DSum[i] + D[i % N];
		}
		H.length = N * 3;
		foreach (i; N .. N * 3) {
			H[i] = H[i % N];
		}

		for (segN = 1; segN < N * 3; segN <<= 1) {}
		seg0 = new Pair!(long, int)[segN * 2];
		seg1 = new Pair!(long, int)[segN * 2];
		foreach (i; 0 .. N * 3) {
			seg0[segN + i] = pair(2 * H[i] + DSum[i], i);
			seg1[segN + i] = pair(2 * H[i] - DSum[i], i);
		}
		foreach_reverse (a; 1 .. segN) {
			seg0[a] = max(seg0[a << 1], seg0[a << 1 | 1]);
			seg1[a] = max(seg1[a << 1], seg1[a << 1 | 1]);
		}
debug{
writeln("seg0 = ",seg0);
writeln("seg1 = ",seg1);
}

		foreach (q; 0 .. Q) {
			const a = readInt - 1;
			const b = readInt - 1;
			const res = (a <= b) ? solve(b + 1, a - 1 + N) : solve(b + 1, a - 1);
			writeln(res);
		}

	}
	} catch (EOFException) {}
}