This problem is given in two editions, which differ exclusively in the constraints on the number $$$n$$$.You are given an array of integers $$$a[1], a[2], \dots, a[n].$$$ A block is a sequence of contiguous (consecutive) elements $$$a[l], a[l+1], \dots, a[r]$$$ ($$$1 \le l \le r \le n$$$). Thus, a block is defined by a pair of indices $$$(l, r)$$$.Find a set of blocks $$$(l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)$$$ such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $$$(l_i, r_i)$$$ and $$$(l_j, r_j$$$) where $$$i \neq j$$$ either $$$r_i < l_j$$$ or $$$r_j < l_i$$$.  For each block the sum of its elements is the same. Formally, $$$$$$a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=$$$$$$ $$$$$$\dots =$$$$$$ $$$$$$a[l_k]+a[l_k+1]+\dots+a[r_k].$$$$$$  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $$$(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')$$$ satisfying the above two requirements with $$$k' > k$$$.     The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.

The first line contains integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given array. The second line contains the sequence of elements $$$a[1], a[2], \dots, a[n]$$$ ($$$-10^5 \le a_i \le 10^5$$$).

In the first line print the integer $$$k$$$ ($$$1 \le k \le n$$$). The following $$$k$$$ lines should contain blocks, one per line. In each line print a pair of indices $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the bounds of the $$$i$$$-th block. You can print blocks in any order. If there are multiple answers, print any of them.

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;

int n;
long[1500] staticA;
long[] a;

void main(string[] args)
{
  n = next!int;
  auto blockSum = new long[][](n + 1, n + 1);
  auto blockChainLength = new int[][](n + 1, n + 1);
  auto blockChainNext = new int[2][][](n + 1, n + 1);
  a = staticA[0 .. n];
  foreach(ref ai; a)
    ai = next!long;
  foreach(i; 0 .. n)
    blockSum[1][i] = a[i];
  foreach(len; 2 .. n + 1)
    foreach(i; 0 .. n + 1 - len) // i + len - 1 < n -> i < n - len + 1
      blockSum[len][i] = a[i] + blockSum[len - 1][i + 1];
  int[2][long] nearest;
  int[2] bestSeg;
  int bestSegLen;
  foreach_reverse(i; 0 .. n)
    {
      // i - len + 1 >= 0 len <= i + 1 len < i
      foreach(len; 1 .. i + 2)
	{
	  auto sum = blockSum[len][i - len + 1];
	  auto next = sum in nearest;
	  if (next !is null)
	    {
	      blockChainNext[len][i - len + 1] = *next;
	      blockChainLength[len][i - len + 1] = 1 + blockChainLength[(*next)[0]][(*next)[1]];
	    }
	  else
	    {
	      blockChainNext[len][i - len + 1] = [-1, -1];
	      blockChainLength[len][i - len + 1] = 1;
	    }
	  if (blockChainLength[len][i - len + 1] > bestSegLen)
	    {
	      bestSeg = [len, i - len + 1];
	      bestSegLen = blockChainLength[len][i - len + 1];
	    }
	}

      foreach_reverse(len; 1 .. n + 1 - i)
	{
	  auto sum = blockSum[len][i];
	  auto nst = sum in nearest;
	  if (nst is null)
	    {
	      nearest[sum] = [len, i];
	    }
	  else
	    {
	      if ((*nst)[1] + (*nst)[0] - 1 > i + len - 1)
		{
		  nearest[sum] = [len, i];
		}
	    }
	}
    }
  int[2] seg = bestSeg;
  bestSegLen.writeln;
  foreach(i; 0 .. bestSegLen)
    {
      writeln(seg[1] + 1, " ", seg[1] + seg[0]);
      seg = blockChainNext[seg[0]][seg[1]];
    }
}

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

int n;
long[1500] staticA;
long[] a;

void main(string[] args)
{
  n = next!int;
  auto blockSum = new long[][](n + 1, n + 1);
  auto blockChainLength = new int[][](n + 1, n + 1);
  auto blockChainNext = new int[2][][](n + 1, n + 1);
  a = staticA[0 .. n];
  foreach(ref ai; a)
    ai = next!long;
  foreach(i; 0 .. n)
    blockSum[1][i] = a[i];
  foreach(len; 2 .. n + 1)
    foreach(i; 0 .. n + 1 - len) // i + len - 1 < n -> i < n - len + 1
      blockSum[len][i] = a[i] + blockSum[len - 1][i + 1];
  int[2][long] nearest;
  int[2] bestSeg;
  int bestSegLen;
  foreach_reverse(i; 0 .. n)
    {
      // i - len + 1 >= 0 len <= i + 1 len < i
      foreach(len; 1 .. i + 2)
	{
	  auto sum = blockSum[len][i - len + 1];
	  auto next = sum in nearest;
	  if (next !is null)
	    {
	      blockChainNext[len][i - len + 1] = *next;
	      blockChainLength[len][i - len + 1] = 1 + blockChainLength[(*next)[0]][(*next)[1]];
	    }
	  else
	    {
	      blockChainNext[len][i - len + 1] = [-1, -1];
	      blockChainLength[len][i - len + 1] = 1;
	    }
	  if (blockChainLength[len][i - len + 1] > bestSegLen)
	    {
	      bestSeg = [len, i - len + 1];
	      bestSegLen = blockChainLength[len][i - len + 1];
	    }
	}

      foreach_reverse(len; 1 .. n + 1 - i)
	{
	  nearest[blockSum[len][i]] = [len, i];
	}
    }
  int[2] seg = bestSeg;
  bestSegLen.writeln;
  foreach(i; 0 .. bestSegLen)
    {
      writeln(seg[1] + 1, " ", seg[1] + seg[0]);
      seg = blockChainNext[seg[0]][seg[1]];
    }
}

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


Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size $$$n \times n$$$ is called prime if the following three conditions are held simultaneously:   all numbers on the square are non-negative integers not exceeding $$$10^5$$$;  there are no prime numbers in the square;  sums of integers in each row and each column are prime numbers. Sasha has an integer $$$n$$$. He asks you to find any prime square of size $$$n \times n$$$. Sasha is absolutely sure such squares exist, so just help him!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required size of a square.

For each test case print $$$n$$$ lines, each containing $$$n$$$ integers — the prime square you built. If there are multiple answers, print any.

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

void play(){
    int n;
    n = rd!int;
    auto mat = new ll[][](n, n);
    foreach(i; 0..n){
        mat[i][] = 0;
        mat[i][i] = 1;
        mat[i][(i + 1) % n] = 1;
    }
    foreach(i; 0..n){
        mat[i].each!(a => write(a, " "));
        writeln;
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
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)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, "x",  long, "y");
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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;

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

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

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

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

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

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

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}


For an array $$$b$$$ of length $$$m$$$ we define the function $$$f$$$ as  $$$ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $$$ where $$$\oplus$$$ is bitwise exclusive OR.For example, $$$f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$$$You are given an array $$$a$$$ and a few queries. Each query is represented as two integers $$$l$$$ and $$$r$$$. The answer is the maximum value of $$$f$$$ on all continuous subsegments of the array $$$a_l, a_{l+1}, \ldots, a_r$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$) — the elements of the array. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 100\,000$$$) — the number of queries. Each of the next $$$q$$$ lines contains a query represented as two integers $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$).

Print $$$q$$$ lines — the answers for the queries.

NoteIn first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.In second sample, optimal segment for first query are $$$[3,6]$$$, for second query — $$$[2,5]$$$, for third — $$$[3,4]$$$, for fourth — $$$[1,2]$$$.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;

    auto B = new long[][](N, N);
    foreach (i; 0..N) B[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            B[l][r] = B[l+1][r] ^ B[l][r-1];
        }
    }

    auto dp = new long[][](N, N);
    foreach (i; 0..N) dp[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            dp[l][r] = B[l][r];
            dp[l][r] = max(dp[l][r], dp[l+1][r]);
            dp[l][r] = max(dp[l][r], dp[l][r-1]);
        }
    }

    auto Q = readln.chomp.to!int;
    while (Q--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        dp[a][b].writeln;
    }
}

import std.algorithm;
import std.array;
import std.conv;
import std.stdio;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		int [] [] a;
		a ~= readln.splitter.map !(to !(int)).array;
		foreach (i; 1..n)
		{
			auto b = new int [n - i];
			foreach (j; 0..n - i)
			{
				b[j] = a[i - 1][j] ^ a[i - 1][j + 1];
			}
			a ~= b;
		}
		foreach (i; 1..n + 1)
		{
			foreach (j; 0..n - i)
			{
				a[i][j] = max (a[i][j],
				    a[i - 1][j], a[i - 1][j + 1]);
			}
		}

		int q;
		readf (" %s", &q);
		foreach (v; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			l -= 1;
			r -= 1;
			writeln (a[r - l][l]);
		}
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;

    auto dp = new int[][](N, N);
    foreach (i; 0..N) dp[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            if (len == 2 || len % 2 == 1) {
                dp[l][r] = A[l] ^ A[r];
            } else {
                dp[l][r] = A[l] ^ A[l+1] ^ A[r-1] ^ A[r];
            }
            dp[l][r] = max(dp[l][r], dp[l+1][r]);
            dp[l][r] = max(dp[l][r], dp[l][r-1]);
        }
    }

    auto Q = readln.chomp.to!int;
    while (Q--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        dp[a][b].writeln;
    }
}


You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \le i \le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible:   initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$;  $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^4$$$) — the length of the array $$$a$$$. It is guaranteed that the number $$$n$$$ is divisible by $$$3$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$150\,000$$$.

For each test case, output one integer — the minimum number of moves that must be made for the $$$a$$$ array to make it have balanced remainders.

NoteThe first test case is explained in the statements.In the second test case, you need to make one move for $$$i=2$$$.The third test case you need to make three moves:   the first move: $$$i=9$$$;  the second move: $$$i=9$$$;  the third move: $$$i=2$$$. In the fourth test case, the values $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ initially equal to each other, so the array $$$a$$$ already has balanced remainders.

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new int[](3);
		foreach (i; 0..n)
		{
			++cnt[a[i]%3];
		}
		debug writeln("cnt:", cnt);

		auto y = n/3;
		bool done;
		while (!done)
		{
			done = true;
			foreach (i; 0..3)
			{
				if (cnt[i] > y)
				{
					done = false;
					auto x = cnt[i] - y;
					cnt[i] = y;
					ans[ti] += x;
					cnt[(i+1)%3] += x;
				}
			}
			debug writeln("cnt:", cnt);
		}
	}

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

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] AA; get(AA);
        int[3] cs;
        foreach (a; AA) ++cs[a % 3];
        int r;
        foreach (i; 0..4) {
            auto d = max(0, cs[i % 3] - N / 3);
            cs[i % 3] -= d;
            r += d;
            cs[(i + 1) % 3] += d;
        }
        writeln(r);
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto c = new int [3];
		foreach (ref x; a)
		{
			c[x % 3] += 1;
		}
		int res = 0;
		foreach (j; 0..2)
		{
			foreach (i; 0..3)
			{
				while (c[i] > n / 3)
				{
					c[i] -= 1;
					c[(i + 1) % 3] += 1;
					res += 1;
				}
			}
		}
		writeln (res);
	}
}


Let's call some positive integer classy if its decimal representation contains no more than $$$3$$$ non-zero digits. For example, numbers $$$4$$$, $$$200000$$$, $$$10203$$$ are classy and numbers $$$4231$$$, $$$102306$$$, $$$7277420000$$$ are not.You are given a segment $$$[L; R]$$$. Count the number of classy integers $$$x$$$ such that $$$L \le x \le R$$$.Each testcase contains several segments, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of segments in a testcase. Each of the next $$$T$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$1 \le L_i \le R_i \le 10^{18}$$$).

Print $$$T$$$ lines — the $$$i$$$-th line should contain the number of classy integers on a segment $$$[L_i; R_i]$$$.

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

int[] transform(long num)
{
    int[] res;
    while (num)
    {
        res ~= (num % 10);
        num /= 10;
    }
    reverse(res);
    return res;
}

int saiki(int idx, int cnt, int flag, int[][][] dp, int[] d)
{
    if (dp[idx][cnt][flag] != -1) return dp[idx][cnt][flag];
    if (idx == cast(int)d.length)
    {
        dp[idx][cnt][flag] = 1;
        return 1;
    }
    dp[idx][cnt][flag] = 0;
    auto bound = flag == 0 ? d[idx] : 9;
    foreach (i; 0 .. bound + 1)
    {
        if (i == 0 || cnt < 3)
        {
            auto nextFlag = i < d[idx] ? 1 : flag;
            auto ret = saiki(idx + 1, cnt + (i != 0), nextFlag, dp, d);
            dp[idx][cnt][flag] += ret;
        }
    }
    return dp[idx][cnt][flag];
}

void solve(long left, long right)
{
    auto dl = transform(left - 1);
    auto dr = transform(right);
    auto m = max(dl.length, dr.length);
    auto dp = new int[][][](m + 1, 4, 2);
    foreach (i; 0 .. m + 1)
    {
        foreach (j; 0 .. 4) fill(dp[i][j], -1);
    }
    auto cl = saiki(0, 0, 0, dp, dl);
    foreach (i; 0 .. m + 1)
    {
        foreach (j; 0 .. 4) fill(dp[i][j], -1);
    }
    auto cr = saiki(0, 0, 0, dp, dr);
    writeln(cr - cl);
}

int main(string[] drgs)
{
    auto T = to!int(readln.strip);
    foreach (i; 0 .. T)
    {
        auto p = map!(to!long)(readln.strip.split(' '));
        solve(p[0], p[1]);
    }
    return 0;
}

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 t;
    readf("%s", &t);
    readln;

    while (t--) {
        long le, r;
        readf("%s %s", &le, &r);
        readln;

        long go(string x) {
            int xlen = x.length.to!int;

            long getAns(bool alwaysSmaller, int pos, int nonZeroLeft, int allLeft) {
                if (pos >= xlen) { return 1; }

                if (alwaysSmaller) {
                    if (pos == 0) { //nonZeroLeft  and allLeft always > 0
                        return 9 * getAns(true, pos+1, nonZeroLeft-1, allLeft-1);
                    }

                    long ret = 0;
                    foreach (nrs; 0 .. nonZeroLeft + 1) {
                        if (nrs > allLeft) { continue; }

                        if (nrs == 0) { ret += 1; }
                        if (nrs == 1) { ret += 9 * allLeft; }
                        if (nrs == 2) { ret += 9 ^^ 2 * allLeft * (allLeft-1) / 2; }
                    }

                    return ret;
                }

                long ret = 0;
                int curDig = x[pos] - '0';

                if (pos > 0) { ret += getAns(curDig > 0, pos+1, nonZeroLeft, allLeft-1); }

                if (nonZeroLeft > 0 && curDig > 0) {
                    if (curDig > 1) {
                        int start = 1;
                        int end = x[pos] - '0' - 1;
                        int span = end - start + 1;
                        ret += span * getAns(true, pos+1, nonZeroLeft-1, allLeft-1);
                    }

                    ret += getAns(false, pos+1, nonZeroLeft-1, allLeft-1);
                }

                return ret;
            }

            long ans = getAns(false, 0, 3, xlen);
            foreach (digs; 1 .. xlen) { ans += getAns(true, 0, 3, digs); }

            return ans;
        }

        auto ans = go(r.to!string) - go((le-1).to!string);
        ans.writeln;
    }
}

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long nn) {
      auto n = digit(nn);
      auto dp = new long[][][](n.length + 1, 2, 20);
      dp[0][0][0] = 1;
      foreach (i; 0 .. n.length) {
        foreach (l; 0 .. 2) {
          foreach (c; 0 .. 19) {
            auto d = l ? 9 : n[i];
            for (int digit = 0; digit <= d; digit++) {
              auto less = l || (digit < d);
              auto count = c + (digit > 0);
              dp[i + 1][less][count] += dp[i][l][c];
            }
          }
        }
      }
      long ret = 0;
      foreach (l; 0 .. 2) {
        for (int c = 0; c <= 3; c++) {
          ret += dp[n.length][l][c];
        }
      }
      return ret;
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

int[] digit(long x) {
  int[] ret;
  do {
    ret = x % 10 ~ ret;
    x /= 10;
  }
  while (x);
  return ret;
}

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

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

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long s) {
      int[] n;
      do {
        n = s % 10 ~ n;
        s /= 10;
      }
      while (s);
      auto memo = new long[][][](n.length + 1, 2, n.length + 1);
      foreach (i; 0 .. (n.length + 1))
        foreach (j; 0 .. 2)
          foreach (k; 0 .. (n.length + 1))
            memo[i][j][k] = -1;
      long f(size_t i, bool less, int count) {
        if (i == n.length) {
          return count <= 3;
        } else {
          if (memo[i][less][count] >= 0)
            return memo[i][less][count];
          long ret = 0;
          auto digit = less ? 9 : n[i];
          for (int d = 0; d <= digit; d++) {
            auto l = less || (d < digit);
            auto c = count + (d > 0);
            ret += f(i + 1, l, c);
          }
          return memo[i][less][count] = ret;
        }
      }

      return f(0, 0, 0);
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

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

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

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long nn) {
      auto n = digit(nn);
      auto dp = new long[][][](n.length + 1, 2, 4);
      dp[0][0][0] = 1;
      foreach (i; 0 .. n.length) {
        foreach (l; 0 .. 2) {
          foreach (c; 0 .. 4) {
            auto d = l ? 9 : n[i];
            for (int digit = 0; digit <= d; digit++) {
              auto less = l || (digit < d);
              auto count = max(3, c + (digit > 0));
              dp[i + 1][less][count] += dp[i][l][c];
            }
          }
        }
      }
      long ret = 0;
      foreach (l; 0 .. 2) {
        for (int c = 0; c <= 3; c++) {
          ret += dp[n.length][l][c];
        }
      }
      return ret;
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

int[] digit(long x) {
  int[] ret;
  do {
    ret = x % 10 ~ ret;
    x /= 10;
  }
  while (x);
  return ret;
}

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

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


There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.

The first line of the input contains two space-separated integers n and p (3 ≤ n ≤ 100 000, 2 ≤ p ≤ 109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark — two space-separated integers li and ri (1 ≤ li ≤ ri ≤ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.

Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0·s1 = 420, s1·s2 = 176576400, and s2·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000  (1, 421, 420421): total is 0.  (2, 420, 420420): total is 6000.  (2, 420, 420421): total is 6000.  (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.

import std.stdio,std.conv;
double[100000] pp;
double ans;
long n,p,l,r;
void main()
{
	scanf(" %d %d",&n,&p);
	for(int i=0;i<n;++i)
	{
		scanf(" %d %d",&l,&r);
		pp[i]=(to!double((r/p-(l-1)/p)))/(r-l+1);
	}
	int t=to!int(n-1);
	ans=(pp[0]+pp[t]-pp[0]*pp[t])*1000;
	for(int i=1;i<n;++i)
	{
		ans+=(pp[i]+pp[i-1]-pp[i]*pp[i-1])*1000;
	}
	writef("%.10f",ans*2);
}

import std.stdio;

void main() {
  int n, p;
  readf(" %s %s", &n, &p);
  auto l = new int[n];
  auto r = new int[n];
  foreach (i; 0..n) {
    readf(" %s %s", &l[i], &r[i]);
  }
  real exp = 0;
  foreach (i; 0..n) {
    int j = (i + 1) % n;
    int ci = r[i] / p - (l[i] - 1) / p;
    int cj = r[j] / p - (l[j] - 1) / p;
    exp += 1.0 * cj / (r[j] - l[j] + 1);
    exp += 1.0 * ci / (r[i] - l[i] + 1);
    exp -= 1.0 * ci * cj / (r[i] - l[i] + 1) / (r[j] - l[j] + 1);
  }
  writeln(exp * 2000);
}

import std.stdio;

void main() {
  int n, p;
  readf(" %s %s", &n, &p);
  auto l = new int[n];
  auto r = new int[n];
  foreach (i; 0..n) {
    readf(" %s %s", &l[i], &r[i]);
  }
  real exp = 0;
  foreach (i; 0..n) {
    int j = (i + 1) % n;
    real denom = 1.0 * (r[i] - l[i] + 1) * (r[j] - l[j] + 1);
    int ci = r[i] / p - (l[i] - 1) / p;
    int cj = r[j] / p - (l[j] - 1) / p;
    exp += cj * (r[i] - l[i] + 1) / denom;
    exp += ci * (r[j] - l[j] + 1) / denom;
    exp -= ci * cj / denom;
  }
  writeln(exp * 2000);
}

import std.stdio,std.conv;
double[100000] pp;
double ans;
long n,p,l,r;
void main()
{
	scanf(" %d %d",&n,&p);
	for(int i=0;i<n;++i)
	{
		scanf(" %d %d",&l,&r);
		pp[i]=(to!double((r/p-(l-1)/p)))/(r-l+1);
	}
	int t=to!int(n-1);
	ans=(pp[0]+pp[t]-pp[0]*pp[t])*1000;
	for(int i=1;i<n;++i)
	{
		ans+=(pp[i]+pp[i-1]-pp[i]*pp[i-1])*1000;
	}
	writeln(ans*2);
}


Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.There are $$$n$$$ solutions, the $$$i$$$-th of them should be tested on $$$a_i$$$ tests, testing one solution on one test takes $$$1$$$ second. The solutions are judged in the order from $$$1$$$ to $$$n$$$. There are $$$k$$$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.At any time moment $$$t$$$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $$$i$$$, then it is being tested on the first test from time moment $$$t$$$ till time moment $$$t + 1$$$, then on the second test till time moment $$$t + 2$$$ and so on. This solution is fully tested at time moment $$$t + a_i$$$, and after that the testing process immediately starts testing another solution.Consider some time moment, let there be exactly $$$m$$$ fully tested solutions by this moment. There is a caption "System testing: $$$d$$$%" on the page with solutions, where $$$d$$$ is calculated as$$$$$$d = round\left(100\cdot\frac{m}{n}\right),$$$$$$where $$$round(x) = \lfloor{x + 0.5}\rfloor$$$ is a function which maps every real to the nearest integer.Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $$$q$$$, and the caption says "System testing: $$$q$$$%". Find the number of interesting solutions.Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.

The first line contains two positive integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1000$$$, $$$1 \le k \le 100$$$) standing for the number of submissions and the number of testing processes respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 150$$$), where $$$a_i$$$ is equal to the number of tests the $$$i$$$-th submission is to be run on.

Output the only integer — the number of interesting submissions.

NoteConsider the first example. At time moment $$$0$$$ both solutions start testing. At time moment $$$49$$$ the first solution is fully tested, so at time moment $$$49.5$$$ the second solution is being tested on the test $$$50$$$, and the caption says "System testing: $$$50$$$%" (because there is one fully tested solution out of two). So, the second solution is interesting.Consider the second example. At time moment $$$0$$$ the first and the second solutions start testing. At time moment $$$32$$$ the first solution is fully tested, the third solution starts testing, the caption says "System testing: $$$25$$$%". At time moment $$$32 + 24.5 = 56.5$$$ the third solutions is being tested on test $$$25$$$, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment $$$32 + 33 = 65$$$, the fourth solution is fully tested at time moment $$$65 + 1 = 66$$$. The captions becomes "System testing: $$$75$$$%", and at time moment $$$74.5$$$ the second solution is being tested on test $$$75$$$. So, this solution is also interesting. Overall, there are two interesting solutions.

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

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

  struct S {
    int cur, end, idx;
  }

  S[] q;
  foreach (i; 0 .. min(n, k)) {
    q ~= S(0, a[i], i);
  }
  alias cmp = (l, r) => (l.end - l.cur > r.end - r.cur);
  q.sort!(cmp);
  auto seen = new bool[](n);
  for (int t = 0, m = 0, i = k; m < n; t++) {
    auto r = round(100 * m, n);
    foreach (ref s; q) {
      s.cur++;
      if (s.cur == r) {
        seen[s.idx] = true;
      }
    }
    q.sort!(cmp);
    while (q.length > 0 && q[$ - 1].cur == q[$ - 1].end) {
      q.popBack;
      m++;
    }
    while (q.length < k && i < n) {
      q ~= S(0, a[i], i);
      i++;
    }
  }
  writeln(seen.count(true));
}

int round(int a, int b) {
  return (a * 2 + b) / (b * 2);
}

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

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

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

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

  struct S {
    int cur, end, idx;
  }

  S[] q;
  foreach (i; 0 .. k) {
    q ~= S(0, a[i], i);
  }
  alias cmp = (l, r) => (l.end - l.cur > r.end - r.cur);
  q.sort!(cmp);
  auto seen = new bool[](n);
  for (int t = 0, m = 0, i = k; q.length > 0; t++) {
    auto r = to!int(100.0 * m / n + 0.5);
    foreach (ref s; q) {
      s.cur++;
      if (s.cur == r) {
        seen[s.idx] = true;
      }
    }
    q.sort!(cmp);
    while (q.length > 0 && q[$ - 1].cur == q[$ - 1].end) {
      q.popBack;
      m++;
    }
    while (q.length < k && i < n) {
      q ~= S(0, a[i++], i);
    }
  }
  writeln(seen.count(true));
}

int round(int a, int b) {
  return (a * 2 + b) / (b * 2);
}

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

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

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

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

  struct S {
    int cur, end, idx;
  }

  S[] q;
  foreach (i; 0 .. k) {
    q ~= S(0, a[i], i);
  }
  alias cmp = (l, r) => (l.end - l.cur > r.end - r.cur);
  q.sort!(cmp);
  auto seen = new bool[](n);
  for (int t = 0, m = 0, i = k; m < n; t++) {
    auto r = round(100 * m, n);
    foreach (ref s; q) {
      s.cur++;
      if (s.cur == r) {
        seen[s.idx] = true;
      }
    }
    q.sort!(cmp);
    while (q.length > 0 && q[$ - 1].cur == q[$ - 1].end) {
      q.popBack;
      m++;
    }
    while (q.length < k && i < n) {
      q ~= S(0, a[i++], i);
    }
  }
  writeln(seen.count(true));
}

int round(int a, int b) {
  return (a * 2 + b) / (b * 2);
}

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

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

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

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

  struct S {
    int cur, end, idx;
  }

  S[] q;
  foreach (i; 0 .. k) {
    q ~= S(0, a[i], i);
  }
  alias cmp = (l, r) => (l.end - l.cur > r.end - r.cur);
  q.sort!(cmp);
  auto seen = new bool[](n);
  for (int t = 0, m = 0, i = k; q.length > 0; t++) {
    auto r = round(100 * m, n);
    foreach (ref s; q) {
      if (s.cur + 1 == r) {
        seen[s.idx] = true;
      }
      s.cur++;
    }
    q.sort!(cmp);
    while (q.length > 0 && q[$ - 1].cur == q[$ - 1].end) {
      q.popBack;
      m++;
    }
    while (q.length < k && i < n) {
      q ~= S(0, a[i++], i);
    }
  }
  writeln(seen.count(true));
}

int round(int a, int b) {
  return (a * 2 + b) / (b * 2);
}

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

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


You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is a vertex number $$$1$$$.A tree is a connected undirected graph with $$$n-1$$$ edges.You are given $$$m$$$ queries. The $$$i$$$-th query consists of the set of $$$k_i$$$ distinct vertices $$$v_i[1], v_i[2], \dots, v_i[k_i]$$$. Your task is to say if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. The next $$$m$$$ lines describe queries. The $$$i$$$-th line describes the $$$i$$$-th query and starts with the integer $$$k_i$$$ ($$$1 \le k_i \le n$$$) — the number of vertices in the current query. Then $$$k_i$$$ integers follow: $$$v_i[1], v_i[2], \dots, v_i[k_i]$$$ ($$$1 \le v_i[j] \le n$$$), where $$$v_i[j]$$$ is the $$$j$$$-th vertex of the $$$i$$$-th query. It is guaranteed that all vertices in a single query are distinct. It is guaranteed that the sum of $$$k_i$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5$$$).

For each query, print the answer — "YES", if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path and "NO" otherwise.

NoteThe picture corresponding to the example:Consider the queries.The first query is $$$[3, 8, 9, 10]$$$. The answer is "YES" as you can choose the path from the root $$$1$$$ to the vertex $$$u=10$$$. Then vertices $$$[3, 9, 10]$$$ belong to the path from $$$1$$$ to $$$10$$$ and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which also belongs to this path.The second query is $$$[2, 4, 6]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=2$$$. Then the vertex $$$4$$$ has distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$6$$$ has distance $$$1$$$ to the vertex $$$2$$$ which belongs to this path.The third query is $$$[2, 1, 5]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=5$$$ and all vertices of the query belong to this path.The fourth query is $$$[4, 8, 2]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=9$$$ so vertices $$$2$$$ and $$$4$$$ both have distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which belongs to this path.The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex $$$u$$$.

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 Query
{
  int k;
  @Dim("k") int[] v;
}
struct TestCase
{
  mixin prettyPrinting;

  int n, m;
  @Dim("n - 1") int[2][] edges;
  @Dim("m") Query[] queries;

  void solve(long tc = -1)
  {
    auto alist = new int[][n + 1];
    foreach(edge; edges)
      {
        alist[edge[0]] ~= edge[1];
        alist[edge[1]] ~= edge[0];
      }
    auto stInt = new Interval[n + 1];
    auto parent = new int[n + 1];
    int sti = 0;
    void dfs(int n, int p)
    {
      parent[n] = p;
      stInt[n].l = sti;
      foreach(nei; alist[n])
        if (nei != p)
          {
            sti++;
            dfs(nei, n);
          }
      stInt[n].h = sti;
    }
    dfs(1, 1);
    foreach(query; queries)
      writeln(query
              .v
              .map!(vi => stInt[parent[vi]])
              .fold!((a, b) => a.intersect(b))
              .empty? "NO" : "YES");
  }
}

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


Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a single integer — the maximum number of points that Alex can earn.

NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	long n;
	long nums;
	long[long] cnt;
	scanf("%d", &n);
	foreach (long i; 0..n)
	{
		scanf("%d", &nums);
		cnt[nums]++;
	}
	long maxk = 0;
	foreach (long k; cnt.byKey)
	{
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = 100005;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (uint k; 2..dp.length)
	{
		dp[k] = max(dp[k-1], dp[k-2] + cast(long)k * (k in cnt ? cnt[k] : cast(long)0));
	}
	write(dp[$-1]);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	long n;
	long nums;
	long[long] cnt;
	scanf("%d", &n);
	foreach (long i; 0..n)
	{
		scanf("%d", &nums);
		cnt[nums]++;
	}
	long maxk = 0;
	foreach (long k; cnt.byKey)
	{
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = cast(uint)(maxk + 5);
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (uint k; 2..dp.length)
	{
		dp[k] = max(dp[k-1], dp[k-2] + cast(long)k * (k in cnt ? cnt[k] : cast(long)0));
	}
	write(dp[$-1]);
	return 0;
}

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;

immutable int MAX_K = 100_005;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto b = new long [MAX_K];
		foreach (i; 0..n)
		{
			int x;
			readf (" %s", &x);
			b[x + 1]++;
		}

		auto f = new long [MAX_K];
		foreach_reverse (i; 0..MAX_K - 2)
		{
			f[i] = max (f[i + 1], f[i + 2] + (i + 1) * b[i + 2]);
		}

		writeln (f[0]);
	}
}

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

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

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

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

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

immutable LIM = 100_005;

int N;
int[] A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new int[N];
		foreach (i; 0 .. N) {
			A[i] = readInt;
		}

		long[] ps = new long[LIM];
		foreach (i; 0 .. N) {
			ps[A[i]] += A[i];
		}

		long[] dp = new long[LIM];
		foreach (x; 0 .. LIM) {
			dp[x] = ps[x];
			if (x - 1 >= 0) {
				chmax(dp[x], dp[x - 1]);
			}
			if (x - 2 >= 0) {
				chmax(dp[x], dp[x - 2] + ps[x]);
			}
		}

		writeln(dp[LIM - 1]);

	}
	} catch (EOFException) {}
}

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;

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

  void solve(long tc = -1)
  {
    long[100000 + 1] aps = 0;
    foreach(ai; a)
      aps.at(ai)++;
    long[100000 + 1] dp = 0;
    dp[0] = 0;
    foreach(i; 1 .. dp.length)
      {
        if (i >= 2)
          dp[i] = max(aps.at(i) * cast(long)i
                      + dp[i - 2],
                      dp[i - 1]);
        else
          dp[i] = max(aps.at(i) * cast(long)i, dp[i - 1]);
      }
    writeln(dp[100000]);
  }
}

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.stdio, std.conv, std.algorithm, std.range, std.math, std.string;

alias number = long;

void main() {
	int n;
	readf(" %s ", &n);
	assert(1 <= n && n <= 10^^5);
	auto a = new number[n];
	foreach (ref ai; a)
		readf(" %s ", &ai);
	number prev_max, cur_max;
	number last_used = -1;
	foreach (ref ri; a.sort.group) {
		number new_max;
		auto value = ri[0] * ri[1];
		if (last_used == ri[0] - 1) {
			if (cur_max >= prev_max + value) {
				new_max = cur_max;
			} else {
				last_used = ri[0];
				new_max = prev_max + value;
			}
		} else {
			last_used = ri[0];
			new_max = cur_max + value;
		}
		prev_max = cur_max;
		cur_max = new_max;
	}
	writeln(cur_max);
}

import std.algorithm;

static immutable MAXA = 100000 + 1;

ulong solve(const uint[] as) {
	auto sums = new ulong[](MAXA);
	auto dp = new ulong[][](MAXA, 2);

	foreach (a; as) {
		sums[a] += a;
	}

	foreach (i; 1..MAXA) {
		dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]);
		dp[i][1] = dp[i - 1][0] + sums[i];
	}

	return max(dp[$ - 1][0], dp[$ - 1][1]);
}

unittest {
	{
		uint[] as = [1, 2];
		assert(2 == solve(as));
	}

	{
		uint[] as = [1, 2, 3];
		assert(4 == solve(as));
	}

	{
		uint[] as = [1, 2, 1, 3, 2, 2, 2, 2, 3];
		assert(10 == solve(as));
	}

	{
		uint[] as = [2, 3, 2, 2, 2, 2, 3];
		assert(10 == solve(as));
	}

	{
		uint[] as = [2, 3, 2, 2, 2, 2, 3, 3, 3];
		assert(12 == solve(as));
	}

	{
		uint[] as = [666];
		assert(666 == solve(as));
	}

	{
		uint[] as = [1];
		assert(1 == solve(as));
	}

	{
		uint[] as = [100000];
		assert(100000 == solve(as));
	}

	{
		uint[] as = [99999, 100000];
		assert(100000 == solve(as));
	}

	{
		uint[] as = [99999, 99999, 100000];
		assert(199998 == solve(as));
	}
}

int main(string[] argv) {
	import std.stdio;
	uint n = 0;
	readf(" %s", &n);
	auto as = new uint[](n);
	foreach (i; 0..n) {
		readf(" %s", &(as[i]));
	}
	writeln(solve(as));
    return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
	}
	int[] keys = cnt.keys;
	keys.sort!((x, y) => cnt[x] > cnt[y]);
	int sum1 = 0;
	int sum2 = 0;
	int pk1 = -2;
	int pk2 = -2;
	foreach (int i; 0..keys.length)
	{
		if (keys[i] + 1 != pk1 && keys[i] - 1 != pk1)
		{
			pk1 = keys[i];
			sum1 += cnt[keys[i]];
		} else
		if (keys[i] +1 != pk2 && keys[i] - 1 != pk2)
		{
			pk2 = keys[i];
			sum2 += cnt[keys[i]];
		}
	}
	write(sum1 > sum2 ? sum1 : sum2);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int maxk = 0;
	foreach (int k; cnt.byKey)
	{
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = maxk+2;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (int k; 2..(maxk+2))
	{
		dp[k] = max(dp[k-1], dp[k-2] + k * (k in cnt ? cnt[k] : 0));
	}
	write(dp[maxk+1]);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

int max(int a, int b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int maxk = 0;
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
		if (k > maxk) maxk = k;
	}

	int[] dp; dp.length = maxk+2;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (int k; 2..(maxk+2))
	{
		dp[k] = max(dp[k-1], dp[k-2] + (k in cnt ? cnt[k] : 0));
	}
	write(dp[maxk+1]);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
	}
	int[] keys = cnt.keys;
	keys.sort!((x, y) => cnt[x] > cnt[y]);
	int sum1 = 0;
	int sum2 = 0;
	bool[int] sumk1;
	bool[int] sumk2;
	foreach (int i; 0..keys.length)
	{
		if (!(keys[i] in sumk1))
		{
			sum1 += cnt[keys[i]];
			sumk1[keys[i]] = true;
			sumk1[keys[i]-1] = true;
			sumk1[keys[i]+1] = true;
		} else
		if (!(keys[i] in sumk2))
		{
			sum2 += cnt[keys[i]];
			sumk2[keys[i]] = true;
			sumk2[keys[i]-1] = true;
			sumk2[keys[i]+1] = true;
		}
	}
	write(sum1 > sum2 ? sum1 : sum2);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int sum_1 = 0;
	int sum_2 = 0;
	foreach (int i; 0..(n/2 + 1))
	{
		int idx1 = 2*i;
		int idx2 = 2*i+1;
		sum_1 += idx1 * (idx1 in cnt ? cnt[idx1] : 0);
		sum_2 += idx2 * (idx2 in cnt ? cnt[idx2] : 0);
	}
	write(sum_1 > sum_2 ? sum_1 : sum_2);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int maxk = 0;
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = maxk+2;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (int k; 2..(maxk+2))
	{
		dp[k] = max(dp[k-1], dp[k-2] + (k in cnt ? cnt[k] : 0));
	}
	write(dp[maxk+1]);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int points = 0;
	bool canPick = true;
	while (canPick)
	{
		int max = int.min;
		int p = -1;
		foreach (int k; cnt.byKey)
		{
			int lm = (k-1) in cnt ? (k-1) * cnt[k-1] : 0;
			lm += (k+1) in cnt ? (k+1) * cnt[k+1] : 0;
			lm = k * cnt[k] - lm;
			if (lm > max)
			{
				max = lm;
				p = k;
			}
		}

		points += p; cnt[p]--;
		cnt.remove(p-1);
		cnt.remove(p+1);
		canPick = cnt[p] != 0;
		if (!canPick)
		{
			cnt.remove(p);
			foreach (int k; cnt.byKey)
				if (cnt[k] != 0)
				{
					canPick = true;
					break;
				}
		}
	}
	write(points);
	return 0;
}

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

void main() {
	int n;
	readf(" %s ", &n);
	assert(1 <= n && n <= 10^^5);
	auto a = new int[n];
	foreach (ref ai; a)
		readf(" %s ", &ai);
	int prev_max, cur_max;
	int last_used = -1;
	foreach (ref ri; a.sort.group) {
		int new_max;
		int value = ri[0] * ri[1];
		if (last_used == ri[0] - 1) {
			if (cur_max >= prev_max + value) {
				new_max = cur_max;
			} else {
				last_used = ri[0];
				new_max = prev_max + value;
			}
		} else {
			last_used = ri[0];
			new_max = cur_max + value;
		}
		prev_max = cur_max;
		cur_max = new_max;
	}
	writeln(cur_max);
}