Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number x, he might get soldiers of high strength. So, he decided to do the following operation k times:  Arrange all the rangers in a straight line in the order of increasing strengths. Take the bitwise XOR (is written as ) of the strength of each alternate ranger with x and update it's strength. Suppose, Jon has 5 rangers with strengths [9, 7, 11, 15, 5] and he performs the operation 1 time with x = 2. He first arranges them in the order of their strengths, [5, 7, 9, 11, 15]. Then he does the following:  The strength of first ranger is updated to , i.e. 7. The strength of second ranger remains the same, i.e. 7. The strength of third ranger is updated to , i.e. 11. The strength of fourth ranger remains the same, i.e. 11. The strength of fifth ranger is updated to , i.e. 13. The new strengths of the 5 rangers are [7, 7, 11, 11, 13]Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations k times. He wants your help for this task. Can you help him?

First line consists of three integers n, k, x (1 ≤ n ≤ 105, 0 ≤ k ≤ 105, 0 ≤ x ≤ 103) — number of rangers Jon has, the number of times Jon will carry out the operation and Jon's favourite number respectively. Second line consists of n integers representing the strengths of the rangers a1, a2, ..., an (0 ≤ ai ≤ 103).

Output two integers, the maximum and the minimum strength of the rangers after performing the operation k times.

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 = 10L ^^ 9 + 23;

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

    int [1 << 11][2] vals;

    readln.chomp.split.map!(to!int).each!(v => vals[0][v] += 1);

    debug { vals[0][0 .. 20].writeln; }

    foreach (i; 0 .. k) {
        int step = i & 1;
        vals[step ^ 1][] = 0;
        bool oddstart = true;
        foreach (v; 0 .. 1 << 11) {
            int cnt = vals[step][v];
            int modif = 0;
            if (cnt % 2 == 0) { modif = cnt / 2; }
            else {
                modif = cnt / 2 + (oddstart ? 1 : 0);
                oddstart ^= 1;
            }

            vals[step ^ 1][v ^ x] += modif;
            vals[step ^ 1][v] += cnt - modif;
        }
    }

    debug { vals[k & 1][1 .. 20].writeln; }

    int a, b;
    foreach (v; 0 .. 1 << 11) {
        if (vals[k & 1][v] > 0) { a = v; }
    }

    foreach_reverse (v; 0 .. 1 << 11) {
        if (vals[k & 1][v] > 0) { b = v; }
    }

    writeln(a, ' ', b);
}

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

immutable int limit = 1 << 10;

void main ()
{
	int n, k, x;
	while (readf (" %s %s %s", &n, &k, &x) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		int [limit] [2] c;
		int b = 0;
		foreach (v; a)
		{
			c[b][v] += 1;
		}

		foreach (step; 0..k)
		{
			b ^= 1;
			c[b][] = 0;
			int p = 0;
			foreach (v; 0..limit)
			{
				int d = c[!b][v] >> 1;
				c[b][v] += d;
				c[b][v ^ x] += d;
				if (c[!b][v] & 1)
				{
					c[b][v ^ (p ? 0 : x)] += 1;
					p ^= 1;
				}
			}
		}

		int lo = int.max;
		int hi = int.min;
		foreach (v; 0..limit)
		{
			if (c[b][v])
			{
				lo = min (lo, v);
				hi = max (hi, v);
			}
		}
		writeln (hi, " ", lo);
	}
}

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 = 10L ^^ 9 + 23;

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

    int [1 << 11][2] vals;

    readln.chomp.split.map!(to!int).each!(v => vals[0][v] += 1);

    debug { vals[0][1 .. 20].writeln; }

    foreach (i; 0 .. k) {
        int step = i & 1;
        vals[step ^ 1][] = 0;
        bool oddstart = true;
        foreach (v; 1 .. 1 << 11) {
            int cnt = vals[step][v];
            int modif = 0;
            if (cnt % 2 == 0) { modif = cnt / 2; }
            else {
                modif = cnt / 2 + (oddstart ? 1 : 0);
                oddstart ^= 1;
            }

            vals[step ^ 1][v ^ x] += modif;
            vals[step ^ 1][v] += cnt - modif;
        }
    }

    debug { vals[k & 1][1 .. 20].writeln; }

    int a, b;
    foreach (v; 1 .. 1 << 11) {
        if (vals[k & 1][v] > 0) { a = v; }
    }

    foreach_reverse (v; 1 .. 1 << 11) {
        if (vals[k & 1][v] > 0) { b = v; }
    }

    writeln(a, ' ', b);
}

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

immutable int limit = 1 << 10;

void main ()
{
	int n, k, x;
	while (readf (" %s %s %s", &n, &k, &x) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		int [limit] [2] c;
		int b = 0;
		foreach (v; a)
		{
			c[b][v] += 1;
		}

		foreach (step; 0..k)
		{
			b ^= 1;
			c[b][] = 0;
			int p = 0;
			foreach (v; 0..limit)
			{
				int d = c[!b][v] >> 1;
				c[b][v] += d;
				c[!b][v ^ x] += d;
				if (c[!b][v] & 1)
				{
					c[b][v ^ (p ? 0 : x)] += 1;
					p ^= 1;
				}
			}
		}

		int lo = int.max;
		int hi = int.min;
		foreach (v; 0..limit)
		{
			if (c[b][v])
			{
				lo = min (lo, v);
				hi = max (hi, v);
			}
		}
		writeln (hi, " ", lo);
	}
}


Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).Inserting an element in the same position he was erased from is also considered moving.Can Vasya divide the array after choosing the right element to move and its new position?

The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array. The second line contains n integers a1, a2... an (1 ≤ ai ≤ 109) — the elements of the array.

Print YES if Vasya can divide the array after moving one element. Otherwise print NO.

NoteIn the first example Vasya can move the second element to the end of the array.In the second example no move can make the division possible.In the third example Vasya can move the fourth element by one position to the left.

import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, 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;
    ll summ = 0;
    foreach(el; arr){
        summ += el;
    }
    if(summ % 2){
        writeln("NO");
        return;
    }
    bool[long] seen;
    seen[0] = 1;
    long req = (summ/2);
    ll cursum = 0;
    foreach(el; arr){
        cursum += el;
        if(cursum >= req && seen.get(cursum - req, 0) == 1){
            writeln("YES");
            return;
        }
        seen[el] = 1;
    }
    seen.clear;
    cursum = 0;
    foreach_reverse(el; arr){
        cursum += el;
        if(cursum >= req && seen.get(cursum - req, 0) == 1){
            writeln("YES");
            return;
        }
        seen[el] = 1;
    }
    writeln("NO");
}

int main(){
    long t = 1;
    while(t--) solve();
    stdout.flush;
    return 0;
}

import std.stdio, std.string;

bool ok(bool[long] c, long s, long ps)
{
    if (ps >= s - ps && ((ps - (s - ps)) & 1) == 0)
    {
        auto v = (ps - (s - ps)) >> 1;
        if (v in c)
        {
            return true;
        }
    }
    return false;
}

void solve(int[] a)
{
    auto n = cast(int)a.length;
    long s = 0;
    foreach (i; 0 .. n)
    {
        s += a[i];
    }
    long ps = a[0];
    for (int i = 1; i < n; ++ i)
    {
        if (ps == s - ps)
        {
            writeln("YES");
            return;
        }
        ps += a[i];
    }
    foreach (i; 0 .. n)
    {
        if (a[i] == s - a[i])
        {
            writeln("YES");
            return;
        }
    }
    bool[long] c;
    c[a[0]] = true;
    ps = a[0];
    for (int i = 1; i < n - 1; ++ i)
    {
        c[a[i]] = true;
        ps += a[i];
        if (ok(c, s, ps))
        {
            writeln("YES");
            return;
        }
    }
    c.clear();
    c[a[n - 1]] = true;
    ps = a[n - 1];
    for (int i = n - 2; i > 0; -- i)
    {
        c[a[i]] = true;
        ps += a[i];
        if (ok(c, s, ps))
        {
            writeln("YES");
            return;
        }
    }
    writeln("NO");
}

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;
        solve(a);
    }
    return 0;
}

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		auto a=arread!lint;
		RedBlackTree!lint q=new RedBlackTree!lint;
		q.insert(a[0]);
		long s=a[0];
		long sm=a.sum;
		if(sm&1){writeln("NO");continue loop;}
		sm/=2;
		foreach(i;1..n)
		{
			q.insert(a[i]);
			s+=a[i];
			if(!q.equalRange(s-sm).empty){writeln("YES");continue loop;}
		}
		s=0;
		q.clear;
		a.reverse;
		s=a[0];
		q.insert(a[0]);
		foreach(i;1..n)
		{
			q.insert(a[i]);
			s+=a[i];
			if(!q.equalRange(s-sm).empty){writeln("YES");continue loop;}
		}
		writeln("NO");

	}
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;

void main(string[] args)
{
  auto n = next!int;
  auto a = next!long(n);
  long rightSum = cast(long) a.sum;
  auto rightSet = redBlackTree!(true, long)(a);
  long leftSum = 0;
  auto leftSet = redBlackTree!(true, long)();
  foreach(i, ai; a)
    {
      rightSum -= ai;
      rightSet.removeKey(ai);
      leftSum += ai;
      leftSet.insert(ai);
      if (leftSum < rightSum)
	{
	  if ((rightSum - leftSum) % 2 == 0 &&
	      ((rightSum - leftSum) / 2) in rightSet)
	    return writeln("YES");
	}
      else if (leftSum > rightSum)
	{
	  if ((leftSum - rightSum) % 2 == 0 &&
	      ((leftSum - rightSum) / 2) in leftSet)
	    return writeln("YES");
	}
      else
	{
	  return writeln("YES");
	}
    }
  return writeln("NO");
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

import std.stdio, std.string;

bool ok(bool[long] c, long s, long ps)
{
    if (ps >= s - ps && ((ps - (s - ps)) & 1) == 0)
    {
        auto v = (ps - (s - ps)) >> 1;
        if (v in c)
        {
            return true;
        }
    }
    return false;
}

void solve(int[] a)
{
    auto n = cast(int)a.length;
    long s = 0;
    foreach (i; 0 .. n)
    {
        s += a[i];
    }
    long ps = a[0];
    for (int i = 1; i < n; ++ i)
    {
        if (ps == s - ps)
        {
            writeln("YES");
            return;
        }
        ps += a[i];
    }
    bool[long] c;
    c[a[0]] = true;
    ps = a[0];
    for (int i = 1; i < n - 1; ++ i)
    {
        c[a[i]] = true;
        ps += a[i];
        if (ok(c, s, ps))
        {
            writeln("YES");
            return;
        }
    }
    c.clear();
    c[a[n - 1]] = true;
    ps = a[n - 1];
    for (int i = n - 2; i > 0; -- i)
    {
        c[a[i]] = true;
        ps += a[i];
        if (ok(c, s, ps))
        {
            writeln("YES");
            return;
        }
    }
    writeln("NO");
}

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;
        solve(a);
    }
    return 0;
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  int n;
  @Dim("n") int[] a;

  void solve(long tc = -1)
  {
    auto prefix_set = redBlackTree!(true, int)();
    auto suffix_set = redBlackTree!(true, int)(a);
    int prefix_sum = 0;
    int suffix_sum = a.sum;
    foreach(i, ai; a)
      {
        prefix_set.insert(ai);
        suffix_set.removeKey(ai);
        prefix_sum += ai;
        suffix_sum -= ai;
        if (suffix_sum == prefix_sum)
          return writeln("YES");
        if ((suffix_sum - prefix_sum) % 2 == 0 &&
            (suffix_sum - prefix_sum) / 2 in suffix_set)
          return writeln("YES");
        if ((prefix_sum - suffix_sum) % 2 == 0 &&
            (prefix_sum - suffix_sum) / 2 in prefix_set)
          return writeln("YES");
      }
    writeln("NO");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    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;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  int n;
  @Dim("n") int[] a;

  void solve(long tc = -1)
  {
    auto prefix_set = redBlackTree!(true, int)();
    auto suffix_set = redBlackTree!(true, int)(a);
    long prefix_sum = 0;
    long suffix_sum = a.sum;
    foreach(i, ai; a)
      {
        prefix_set.insert(ai);
        suffix_set.removeKey(ai);
        prefix_sum += ai;
        suffix_sum -= ai;
        if (suffix_sum == prefix_sum)
          return writeln("YES");
        if ((suffix_sum - prefix_sum) % 2 == 0 &&
            cast(int)((suffix_sum - prefix_sum) / 2) in suffix_set)
          return writeln("YES");
        if ((prefix_sum - suffix_sum) % 2 == 0 &&
            cast(int)((prefix_sum - suffix_sum) / 2) in prefix_set)
          return writeln("YES");
      }
    writeln("NO");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    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;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  int n;
  @Dim("n") int[] a;

  void solve(long tc = -1)
  {
    auto prefix_set = redBlackTree!(true, int)();
    auto suffix_set = redBlackTree!(true, int)(a);
    long prefix_sum = 0;
    long suffix_sum = a.map!(ai => cast(long) ai).sum;
    foreach(i, ai; a)
      {
        prefix_set.insert(ai);
        suffix_set.removeKey(ai);
        prefix_sum += ai;
        suffix_sum -= ai;
        if (suffix_sum == prefix_sum)
          return writeln("YES");
        if ((suffix_sum - prefix_sum) % 2 == 0 &&
            cast(int)((suffix_sum - prefix_sum) / 2) in suffix_set)
          return writeln("YES");
        if ((prefix_sum - suffix_sum) % 2 == 0 &&
            cast(int)((prefix_sum - suffix_sum) / 2) in prefix_set)
          return writeln("YES");
      }
    writeln("NO");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    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;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}


Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that , where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments. Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.

The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.

In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.

NoteIn the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because .There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because . Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because .

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		a = 0 ~ a ~ 0;
		int [] x;
		int [] prev;
		int [] next;
		long [] s = [0L];
		long [] t = [0L];
		foreach (i, c; a)
		{
			if (c > 1)
			{
				x ~= c;
				int lo = i - 1;
				while (a[lo] == 1)
				{
					lo -= 1;
				}
				prev ~= i - lo - 1;
				int hi = i + 1;
				while (a[hi] == 1)
				{
					hi += 1;
				}
				next ~= hi - i - 1;
				s ~= s[$ - 1] + c;
				t ~= t[$ - 1] + prev[$ - 1];
			}
		}

		long res = 0;
		if (k == 1)
		{
			res += a.count (1);
		}
		foreach (int i; 0..x.length)
		{
			long cur = 1;
			for (int j = i; j < x.length &&
			    x[j] <= long.max / cur; j++)
			{
				cur *= x[j];
				if (cur % k == 0)
				{
					long needS = cur / k;
					long minS = s[j + 1] - s[i] +
					    t[j + 1] - t[i + 1];
					debug {writeln (minS, " ", needS);}
					long toAdd = needS - minS;
					long lo = prev[i];
					long hi = next[j];
					if (0 <= toAdd && toAdd <= lo + hi)
					{
						long minLo = max (0L,
						    toAdd - hi);
						long maxLo = min (lo,
						    toAdd);
						long value = maxLo - minLo + 1;
						debug {writeln ("+", value);}
						res += value;
					}
				}
			}
		}
		writeln (res);
	}
}


You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. 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 query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.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;

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

void solve(){
	int q = rint;
	foreach(_; 0 .. q){
		int n = rint;
		long[] as = rlong(n);
		long s;
		foreach(a; as) if(a <= 2048) s += a;

		if(s >= 2048) "Yes".writeln;
		else "No".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 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 q = RD!int;
	auto ans = new bool[](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto s = RDA;
		//s.sort!"a > b"();
		auto heap = heapify!"a > b"(s);
		bool ok;
		long[] stack;
		while (!heap.empty)
		{
			auto x = heap.front; heap.removeFront;
			if (x == 2048)
			{
				ok = true;
				break;
			}
			if (stack.length != 2)
			{
				stack ~= x;
			}
			debug writeln(stack);
			if (stack.length == 2)
			{
				if (stack[0] == stack[1])
				{
					heap.insert(stack[0] * 2);
					stack = [];
				}
				else
				{
					stack = stack[1..$];
				}
			}
		}
		ans[i] = ok;
	}

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


Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum  is maximally possible, where A' is already rearranged array.

First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B. Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A. Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.

Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.

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;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = readln.split.map!(to!int).array;
    auto C = new Tuple!(int, int)[](N);
    auto D = new int[](N);

    A.sort!"a > b"();
    foreach (i; 0..N) C[i] = tuple(B[i], i);
    C.sort!"a[0] < b[0]"();

    foreach (i; 0..N) {
        D[C[i][1]] = A[i];
    }

    D.map!(d => d.to!string).join(" ").writeln;
}

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 M = readInt();
      auto A = new long[M];
      foreach (i; 0 .. M) {
        A[i] = readLong();
      }
      auto B = new long[M];
      foreach (i; 0 .. M) {
        B[i] = readLong();
      }

      auto as = new Tuple!(long, int)[M];
      auto bs = new Tuple!(long, int)[M];
      foreach (i; 0 .. M) {
        as[i] = tuple(A[i], i);
        bs[i] = tuple(B[i], i);
      }
      as.sort;
      bs.sort;

      auto ans = new long[M];
      foreach (i; 0 .. M) {
        ans[bs[i][1]] = as[M - 1 - i][0];
      }

      foreach (i; 0 .. M) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio, std.array, std.conv, std.string, std.algorithm;

auto gets() { return readln().chomp(); }
auto getV(T)() { return to!T(readln().chomp()); }
auto getVals(T)() { return to!(T[])(readln().chomp().split(" ")); }

auto isOdd(int p) { return p % 2 != 0; }

void main() {
    int n = getV!int();
    auto xs = getVals!int();
    auto ys = getVals!int();
    auto ix = new int[n];
    auto iy = new int[n];
    makeIndex!("a > b")(xs, ix);
    makeIndex!("a < b")(ys, iy);
    // writeln(ix.map!(a => xs[a]));
    // writeln(iy.map!(a => ys[a]));
    auto zs = new int[n];
    for (int i = 0; i < n; i++) {
        zs[iy[i]] = xs[ix[i]];
    }
    writeln(to!(string[])(zs).join(" "));
}


The store sells $$$n$$$ beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options):  And the following necklaces cannot be assembled from beads sold in the store:  The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace $$$k$$$-beautiful if, when it is turned clockwise by $$$k$$$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace.    As you can see, this necklace is, for example, $$$3$$$-beautiful, $$$6$$$-beautiful, $$$9$$$-beautiful, and so on, but it is not $$$1$$$-beautiful or $$$2$$$-beautiful.In particular, a necklace of length $$$1$$$ is $$$k$$$-beautiful for any integer $$$k$$$. A necklace that consists of beads of the same color is also beautiful for any $$$k$$$.You are given the integers $$$n$$$ and $$$k$$$, and also the string $$$s$$$ containing $$$n$$$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $$$k$$$-beautiful necklace you can assemble.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2000$$$). The second line of each test case contains the string $$$s$$$ containing $$$n$$$ lowercase English letters — the beads in the store. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2000$$$.

Output $$$t$$$ answers to the test cases. Each answer is a positive integer — the maximum length of the $$$k$$$-beautiful necklace you can assemble.

6
6 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec

NoteThe first test case is explained in the statement.In the second test case, a $$$6$$$-beautiful necklace can be assembled from all the letters.In the third test case, a $$$1000$$$-beautiful necklace can be assembled, for example, from beads "abzyo".

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 k = RD!int;
		auto s = RD!string;

		auto cnt = new int[](26);
		foreach (i; 0..n)
			++cnt[s[i]-'a'];
		cnt.sort!"a > b";
		ans[ti] = cnt.front;

		void f(int kk)
		{
			auto loop = n / kk;
			while (loop != 0)
			{
				auto len = loop * kk;
				foreach (e; cnt)
				{
					len -= e / loop * loop;
				}
				if (len <= 0)
				{
					ans[ti].chmax(loop * kk);
					break;
				}
				--loop;
			}
		}
		{
			bool[int] set;
			for (int i = 1; i*i <= k; ++i)
			{
				if (k % i) continue;
				set[i] = true;
				set[k/i] = true;
			}
			debug writeln(set.keys);
			foreach (key; set.keys)
			{
				f(key);
			}
		}
	}

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


While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem:Given an integer sequence a1, a2, ..., an. You should run q queries of two types:  Given two integers l and r (1 ≤ l ≤ r ≤ n), ask the sum of all elements in the sequence al, al + 1, ..., ar.  Given two integers l and r (1 ≤ l ≤ r ≤ n), let each element x in the sequence al, al + 1, ..., ar becomes x3. In other words, apply an assignments al = al3, al + 1 = al + 13, ..., ar = ar3. For every query of type 1, output the answer to it.Tiny himself surely cannot work it out, so he asks you for help. In addition, Tiny is a prime lover. He tells you that because the answer may be too huge, you should only output it modulo 95542721 (this number is a prime number).

The first line contains an integer n (1 ≤ n ≤ 105), representing the length of the sequence. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109). The third line contains an integer q (1 ≤ q ≤ 105), representing the number of queries. Then follow q lines. Each line contains three integers ti (1 ≤ ti ≤ 2), li, ri (1 ≤ li ≤ ri ≤ n), where ti stands for the type of the query while li and ri is the parameters of the query, correspondingly.

For each 1-type query, print the answer to it per line. You should notice that each printed number should be non-negative and less than 95542721.

import std.stdio, std.algorithm;

immutable MOD = 95542721, P = 48;

int cb(int x) {
    return 1L * x * x % MOD * x % MOD;
}

class T {
    int[P] d;
    int l, r, sh, lz;
    T lt, rt;

    this(int L, int R, int[] a) {
        l = L; r = R;
        if (l + 1 == r) {
            d[0] = a[l];
            foreach (i; 1..P) d[i] = cb(d[i - 1]);
            return;
        }
        int m = l + (r - l >> 1);
        lt = new T(l, m, a); rt = new T(m, r, a);
        pu;
    }

    void pd() {
        if (lz) {
            (sh += lz) %= P;
            if (lt !is null) {
                (lt.lz += lz) %= P;
                (rt.lz += lz) %= P;
            }
            lz = 0;
        }
    }

    void pu() {
        sh = 0;
        foreach (i; 0..P)
            d[i] = (lt.d[(i + lt.sh) % P] + rt.d[(i + rt.sh) % P]) % MOD;
    }

    int q(int L, int R) {
        if (R <= l || r <= L) return 0;
        pd;
        if (L <= l && r <= R) return d[sh];
        return (lt.q(L, R) + rt.q(L, R)) % MOD;
    }

    void u(int L, int R) {
        if (L <= l && r <= R) {
            (lz += 1) %= P;
            pd;
            return;
        }
        pd;
        if (R <= l || r <= L) return;
        lt.u(L, R); rt.u(L, R);
        pu;
    }
}

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

    auto a = new int[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    T tr = new T(0, n, a);

    int q;
    readf(" %d", &q);
    foreach (i; 0..q) {
        int t, l, r;
        scanf(" %d %d %d", &t, &l, &r);
        --l;
        if (t == 1) printf("%d\n", tr.q(l, r));
        else tr.u(l, r);
    }
}

import std.stdio, std.algorithm;

immutable M = 95542721, P = 48;

int cb(int x) {
    return 1L * x * x % M * x % M;
}

class T {
    int[P] d;
    int l, r, sh, lz;
    T lt, rt;

    this(int L, int R, int[] a) {
        l = L; r = R;
        if (l + 1 == r) {
            d[0] = a[l];
            foreach (i; 1..P) d[i] = cb(d[i - 1]);
            return;
        }
        int m = l + (r - l >> 1);
        lt = new T(l, m, a); rt = new T(m, r, a);
        pu;
    }

    void pu() {
        foreach (i; 0..P)
            d[i] = (lt.d[(i + lt.lz) % P] + rt.d[(i + rt.lz) % P]) % M;
    }

    int q(int L, int R, int LZ = 0) {
        if (R <= l || r <= L) return 0;
        if (L <= l && r <= R) return d[(LZ + lz) % P];
        return (lt.q(L, R, LZ + lz) + rt.q(L, R, LZ + lz)) % M;
    }

    void u(int L, int R) {
        if (L <= l && r <= R) {
            (lz += 1) %= P;
            return;
        }
        if (R <= l || r <= L) return;
        lt.u(L, R); rt.u(L, R);
        pu;
    }
}

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

    auto a = new int[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    T tr = new T(0, n, a);

    int q;
    readf(" %d", &q);
    foreach (i; 0..q) {
        int t, l, r;
        scanf(" %d %d %d", &t, &l, &r);
        --l;
        if (t == 1) printf("%d\n", tr.q(l, r));
        else tr.u(l, r);
    }
}

import std.stdio, std.algorithm;

immutable M = 95542721, P = 48;

int cb(int x) {
    return 1L * x * x % M * x % M;
}

class T {
    int[P] d;
    int l, r, lz;
    T lt, rt;

    this(int L, int R, int[] a) {
        l = L; r = R;
        if (l + 1 == r) {
            d[0] = a[l];
            foreach (i; 1..P) d[i] = cb(d[i - 1]);
            return;
        }
        int m = l + (r - l >> 1);
        lt = new T(l, m, a); rt = new T(m, r, a);
        pu;
    }

    void pu() {
        foreach (i; 0..P)
            d[i] = (lt.d[(i + lt.lz) % P] + rt.d[(i + rt.lz) % P]) % M;
    }

    int q(int L, int R, int LZ = 0) {
        if (R <= l || r <= L) return 0;
        if (L <= l && r <= R) return d[(LZ + lz) % P];
        return (lt.q(L, R, LZ + lz) + rt.q(L, R, LZ + lz)) % M;
    }

    void u(int L, int R) {
        if (L <= l && r <= R) {
            (lz += 1) %= P;
            return;
        }
        if (R <= l || r <= L) return;
        lt.u(L, R); rt.u(L, R);
        pu;
    }
}

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

    auto a = new int[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    T tr = new T(0, n, a);

    int q;
    readf(" %d", &q);
    foreach (i; 0..q) {
        int t, l, r;
        scanf(" %d %d %d", &t, &l, &r);
        --l;
        if (t == 1) printf("%d\n", tr.q(l, r));
        else tr.u(l, r);
    }
}

import std.stdio;

immutable M = 95542721, P = 48;

int cb(int x) {
    return 1L * x * x % M * x % M;
}

class T {
    int[P] d;
    int l, r, lz;
    T lt, rt;

    this(int L, int R, int[] a) {
        l = L; r = R;
        if (l + 1 == r) {
            d[0] = a[l];
            foreach (i; 1..P) d[i] = cb(d[i - 1]);
            return;
        }
        int m = l + (r - l >> 1);
        lt = new T(l, m, a); rt = new T(m, r, a);
        pu;
    }

    void pu() {
        foreach (i; 0..P)
            d[i] = (lt.d[(i + lt.lz) % P] + rt.d[(i + rt.lz) % P]) % M;
    }

    int q(int L, int R, int LZ = 0) {
        if (R <= l || r <= L) return 0;
        if (L <= l && r <= R) return d[(LZ + lz) % P];
        return (lt.q(L, R, LZ + lz) + rt.q(L, R, LZ + lz)) % M;
    }

    void u(int L, int R) {
        if (R <= l || r <= L) return;
        if (L <= l && r <= R) { (lz += 1) %= P; return; }
        lt.u(L, R); rt.u(L, R);
        pu;
    }
}

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

    auto a = new int[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    T tr = new T(0, n, a);

    int q;
    readf(" %d", &q);
    foreach (i; 0..q) {
        int t, l, r;
        scanf(" %d %d %d", &t, &l, &r);
        --l;
        if (t == 1) printf("%d\n", tr.q(l, r));
        else tr.u(l, r);
    }
}

import std.stdio, std.algorithm;

immutable MOD = 95542721, P = 48;

int cb(int x) {
    return 1L * x * x % MOD * x % MOD;
}

class T {
    int[P] d;
    int l, r, lz;
    T lt, rt;

    this(int L, int R, int[] a) {
        l = L; r = R;
        if (l + 1 == r) {
            d[0] = a[l];
            foreach (i; 1..P) d[i] = cb(d[i - 1]);
            return;
        }
        int m = l + (r - l >> 1);
        lt = new T(l, m, a); rt = new T(m, r, a);
        pu;
    }

    void pu() {
        lz = 0;
        foreach (i; 0..P) d[i] = (lt.d[(i + lt.lz) % P] + rt.d[(i + rt.lz) % P]) % MOD;
    }

    int q(int L, int R, int LZ = 0) {
        if (R <= l || r <= L) return 0;
        if (L <= l && r <= R) return d[(LZ + lz) % P];
        return (lt.q(L, R, LZ + lz) + rt.q(L, R, LZ + lz)) % MOD;
    }

    void u(int L, int R, int LZ = 1) {
        if (L <= l && r <= R) {
            (lz += LZ) %= P;
            return;
        }
        if (R <= l || r <= L) return;
        lt.u(L, R, LZ + lz); rt.u(L, R, LZ + lz);
        pu;
    }
}

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

    auto a = new int[n];
    foreach (i; 0..n) scanf(" %d", &a[i]);

    T tr = new T(0, n, a);

    int q;
    readf(" %d", &q);
    foreach (i; 0..q) {
        int t, l, r;
        scanf(" %d %d %d", &t, &l, &r);
        --l;
        if (t == 1) printf("%d\n", tr.q(l, r));
        else tr.u(l, r);
    }
}


One Saturday afternoon Egor was playing his favorite RPG game. While discovering new lands and territories, he came across the following sign:  Egor is a passionate player, but he is an algorithmician as well. That's why he instantly spotted four common letters in two words on the sign above — if we permute the letters "R", "E", "G", "O" from the first word, we can obtain the letters "O", "G", "R", "E". Egor got inspired by the sign and right away he came up with a problem about permutations.You are given a permutation of length $$$n$$$. You have to split it into some non-empty subsequences so that each element of the permutation belongs to exactly one subsequence. Each subsequence must be monotonic — that is, either increasing or decreasing.Sequence is called to be a subsequence if it can be derived from permutation by deleting some (possibly none) elements without changing the order of the remaining elements.The number of subsequences should be small enough — let $$$f(n)$$$ be the minimum integer $$$k$$$ such that every permutation of length $$$n$$$ can be partitioned into at most $$$k$$$ monotonic subsequences.You need to split the permutation into at most $$$f(n)$$$ monotonic subsequences.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. You can only use $$$t = 1$$$ in hacks. Next, descriptions of $$$t$$$ test cases come, each of them in the following format. The first line of a single test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \leq a_i \leq n$$$) — the permutation itself. The sum of the values of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the answer in the following format: In the first line print $$$k$$$ ($$$1 \leq k \leq f(n)$$$) — the number of the subsequences in the partition. In the next $$$k$$$ lines, print the descriptions of found subsequences. Each description should start with a number $$$l_i$$$ ($$$1 \leq l_i \leq n$$$) — the length of the corresponding subsequence, followed by $$$l_i$$$ integers — the values of this subsequence in the order in which they occur in the permutation. Each subsequence you output must be either increasing or decreasing.  In case there are multiple possible answers, print any of them.

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

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 readToken().to!int; }
long readLong() { return readToken().to!long; }
real readReal() { return readToken().to!real; }

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(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) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

class XRand {
  uint x = 314159265, y = 358979323, z = 846264338, w = 327950288;
  void setSeed(uint seed) { w ^= seed * 65535; }
  uint next() { uint t = x ^ x << 11; x = y; y = z; z = w; return w = w ^ w >> 19 ^ t ^ t >> 8; }
  uint nextInt(uint m) { return next() % m; }
  int nextInt(int a, int b) { return a + nextInt(b - a + 1); }
  real nextReal() { return next() / 4294967296.0; }
}

immutable LIM_N = 10^^5 + 10;
int[] K;

int[][] solve(int[] a) {
  debug {
    writefln("solve %s", a);
  }
  const n = cast(int)(a.length);
  if (n == 0) {
    return [];
  }

  auto dp = new int[n];
  int[] lis;
  foreach (i; 0 .. n) {
    const pos = lis.lowerBound(a[i]);
    dp[i] = pos + 1;
    if (pos == lis.length) {
      lis ~= a[i];
    } else {
      lis[pos] = a[i];
    }
  }
  debug {
    writefln("  dp = %s", dp);
  }
  const mx = dp.maxElement;
  if (mx <= K[n]) {
    auto seqs = new int[][mx];
    foreach (i; 0 .. n) {
      seqs[dp[i] - 1] ~= a[i];
    }
// foreach(seq;seqs)foreach(h;1..seq.length)assert(seq[h-1]>seq[h]);
    return seqs;
  } else {
    auto used = new int[n];
    int[] seq, rem;
    int j = mx;
    foreach_reverse (i; 0 .. n) {
      if (dp[i] == j) {
        used[i] = true;
        seq ~= a[i];
        --j;
      }
    }
    seq.reverse;
    debug {
      writefln("  seq = %s", seq);
    }
// foreach(h;1..seq.length)assert(seq[h-1]<seq[h]);
    foreach (i; 0 .. n) {
      if (!used[i]) {
        rem ~= a[i];
      }
    }
    return seq ~ solve(rem);
  }
}

int N;
int[] A;

void main() {
  K = new int[LIM_N];
  for (int k = 1; k * (k + 1) / 2 <= LIM_N; ++k) {
    K[k * (k + 1) / 2 .. min((k + 1) * (k + 2) / 2, LIM_N)] = k;
  }
  debug {
    writefln("K = %s", K[0 .. 18]);
  }

  foreach (tc; 0 .. readInt()) {
    N = readInt();
    A = new int[N];
    foreach (i; 0 .. N) {
      A[i] = readInt();
    }
    auto ans = solve(A);
    writeln(ans.length);
    foreach (seq; ans) {
      writeln(seq.length, " ", seq.map!(to!string).join(" "));
    }
  }
}

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

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 readToken().to!int; }
long readLong() { return readToken().to!long; }
real readReal() { return readToken().to!real; }

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(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) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

class XRand {
  uint x = 314159265, y = 358979323, z = 846264338, w = 327950288;
  void setSeed(uint seed) { w ^= seed * 65535; }
  uint next() { uint t = x ^ x << 11; x = y; y = z; z = w; return w = w ^ w >> 19 ^ t ^ t >> 8; }
  uint nextInt(uint m) { return next() % m; }
  int nextInt(int a, int b) { return a + nextInt(b - a + 1); }
  real nextReal() { return next() / 4294967296.0; }
}

immutable LIM_N = 10^^5 + 10;
int[] K;

int N;
int[] A;

int[][] solve(int[] a) {
  debug {
    writefln("solve %s", a);
  }
  const n = cast(int)(a.length);
  if (n == 0) {
    return [];
  }

  auto dp = new int[n];
  int[] lis;
  foreach (i; 0 .. n) {
    const pos = lis.lowerBound(A[i]);
    dp[i] = pos + 1;
    if (pos == lis.length) {
      lis ~= A[i];
    } else {
      lis[pos] = A[i];
    }
  }
  debug {
    writefln("  dp = %s", dp);
  }
  const mx = dp.maxElement;
  if (mx <= K[n]) {
    auto seqs = new int[][mx];
    foreach (i; 0 .. n) {
      seqs[dp[i] - 1] ~= a[i];
    }
foreach(seq;seqs)foreach(h;1..seq.length)assert(seq[h-1]>seq[h]);
    return seqs;
  } else {
    auto used = new int[n];
    int[] seq, rem;
    int j = mx;
    foreach_reverse (i; 0 .. n) {
      if (dp[i] == j) {
        used[i] = true;
        seq ~= a[i];
        --j;
      }
    }
    seq.reverse;
    foreach (i; 0 .. n) {
      if (!used[i]) {
        rem ~= a[i];
      }
    }
    return seq ~ solve(rem);
  }
}

void main() {
  K = new int[LIM_N];
  for (int k = 1; k * (k + 1) / 2 <= LIM_N; ++k) {
    K[k * (k + 1) / 2 .. min((k + 1) * (k + 2) / 2, LIM_N)] = k;
  }
  debug {
    writefln("K = %s", K[0 .. 18]);
  }

  foreach (tc; 0 .. readInt()) {
    N = readInt();
    A = new int[N];
    foreach (i; 0 .. N) {
      A[i] = readInt();
    }
    auto ans = solve(A);
    writeln(ans.length);
    foreach (seq; ans) {
      writeln(seq.length, " ", seq.map!(to!string).join(" "));
    }
  }
}

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

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 readToken().to!int; }
long readLong() { return readToken().to!long; }
real readReal() { return readToken().to!real; }

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(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) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

class XRand {
  uint x = 314159265, y = 358979323, z = 846264338, w = 327950288;
  void setSeed(uint seed) { w ^= seed * 65535; }
  uint next() { uint t = x ^ x << 11; x = y; y = z; z = w; return w = w ^ w >> 19 ^ t ^ t >> 8; }
  uint nextInt(uint m) { return next() % m; }
  int nextInt(int a, int b) { return a + nextInt(b - a + 1); }
  real nextReal() { return next() / 4294967296.0; }
}

immutable LIM_N = 10^^5 + 10;
int[] K;

int[][] solve(int[] a) {
  debug {
    writefln("solve %s", a);
  }
  const n = cast(int)(a.length);
  if (n == 0) {
    return [];
  }

  auto dp = new int[n];
  int[] lis;
  foreach (i; 0 .. n) {
    const pos = lis.lowerBound(a[i]);
    dp[i] = pos + 1;
    if (pos == lis.length) {
      lis ~= A[i];
    } else {
      lis[pos] = A[i];
    }
  }
  debug {
    writefln("  dp = %s", dp);
  }
  const mx = dp.maxElement;
  if (mx <= K[n]) {
    auto seqs = new int[][mx];
    foreach (i; 0 .. n) {
      seqs[dp[i] - 1] ~= a[i];
    }
// foreach(seq;seqs)foreach(h;1..seq.length)assert(seq[h-1]>seq[h]);
    return seqs;
  } else {
    auto used = new int[n];
    int[] seq, rem;
    int j = mx;
    foreach_reverse (i; 0 .. n) {
      if (dp[i] == j) {
        used[i] = true;
        seq ~= a[i];
        --j;
      }
    }
    seq.reverse;
    debug {
      writefln("  seq = %s", seq);
    }
// foreach(h;1..seq.length)assert(seq[h-1]<seq[h]);
    foreach (i; 0 .. n) {
      if (!used[i]) {
        rem ~= a[i];
      }
    }
    return seq ~ solve(rem);
  }
}

int N;
int[] A;

void main() {
  K = new int[LIM_N];
  for (int k = 1; k * (k + 1) / 2 <= LIM_N; ++k) {
    K[k * (k + 1) / 2 .. min((k + 1) * (k + 2) / 2, LIM_N)] = k;
  }
  debug {
    writefln("K = %s", K[0 .. 18]);
  }

  foreach (tc; 0 .. readInt()) {
    N = readInt();
    A = new int[N];
    foreach (i; 0 .. N) {
      A[i] = readInt();
    }
    auto ans = solve(A);
    writeln(ans.length);
    foreach (seq; ans) {
      writeln(seq.length, " ", seq.map!(to!string).join(" "));
    }
  }
}

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

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 readToken().to!int; }
long readLong() { return readToken().to!long; }
real readReal() { return readToken().to!real; }

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

int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = cast(int)(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) => (a < val)); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) => (a <= val)); }

class XRand {
  uint x = 314159265, y = 358979323, z = 846264338, w = 327950288;
  void setSeed(uint seed) { w ^= seed * 65535; }
  uint next() { uint t = x ^ x << 11; x = y; y = z; z = w; return w = w ^ w >> 19 ^ t ^ t >> 8; }
  uint nextInt(uint m) { return next() % m; }
  int nextInt(int a, int b) { return a + nextInt(b - a + 1); }
  real nextReal() { return next() / 4294967296.0; }
}

immutable LIM_N = 10^^5 + 10;
int[] K;

int N;
int[] A;

int[][] solve(int[] a) {
  debug {
    writefln("solve %s", a);
  }
  const n = cast(int)(a.length);
  if (n == 0) {
    return [];
  }

  auto dp = new int[n];
  int[] lis;
  foreach (i; 0 .. n) {
    const pos = lis.lowerBound(A[i]);
    dp[i] = pos + 1;
    if (pos == lis.length) {
      lis ~= A[i];
    } else {
      lis[pos] = A[i];
    }
  }
  debug {
    writefln("  dp = %s", dp);
  }
  const mx = dp.maxElement;
  if (mx <= K[n]) {
    auto seqs = new int[][mx];
    foreach (i; 0 .. n) {
      seqs[dp[i] - 1] ~= a[i];
    }
    return seqs;
  } else {
    auto used = new int[n];
    int[] seq, rem;
    int j = mx;
    foreach_reverse (i; 0 .. n) {
      if (dp[i] == j) {
        used[i] = true;
        seq ~= a[i];
        --j;
      }
    }
    seq.reverse;
    foreach (i; 0 .. n) {
      if (!used[i]) {
        rem ~= a[i];
      }
    }
    return seq ~ solve(rem);
  }
}

void main() {
  K = new int[LIM_N];
  for (int k = 1; k * (k + 1) / 2 <= LIM_N; ++k) {
    K[k * (k + 1) / 2 .. min((k + 1) * (k + 2) / 2, LIM_N)] = k;
  }
  debug {
    writefln("K = %s", K[0 .. 18]);
  }

  foreach (tc; 0 .. readInt()) {
    N = readInt();
    A = new int[N];
    foreach (i; 0 .. N) {
      A[i] = readInt();
    }
    auto ans = solve(A);
    writeln(ans.length);
    foreach (seq; ans) {
      writeln(seq.length, " ", seq.map!(to!string).join(" "));
    }
  }
}