The sequence of integers $$$a_1, a_2, \dots, a_k$$$ is called a good array if $$$a_1 = k - 1$$$ and $$$a_1 > 0$$$. For example, the sequences $$$[3, -1, 44, 0], [1, -99]$$$ are good arrays, and the sequences $$$[3, 7, 8], [2, 5, 4, 1], [0]$$$ — are not.A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $$$[2, -3, 0, 1, 4]$$$, $$$[1, 2, 3, -3, -9, 4]$$$ are good, and the sequences $$$[2, -3, 0, 1]$$$, $$$[1, 2, 3, -3 -9, 4, 1]$$$ — are not.For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.

The first line contains the number $$$n~(1 \le n \le 10^3)$$$ — the length of the initial sequence. The following line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9)$$$ — the sequence itself.

In the single line output one integer — the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.

NoteIn the first test case, two good subsequences — $$$[a_1, a_2, a_3]$$$ and $$$[a_2, a_3]$$$.In the second test case, seven good subsequences — $$$[a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4]$$$ and $$$[a_3, a_4]$$$.

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

int saiki(int idx, int n, int[] a, int[] dp, int[][] c)
{
    if (dp[idx] != -1)
    {
        return dp[idx];
    }
    if (idx == n)
    {
        dp[idx] = 1;
        return 1;
    }
    if (a[idx] <= 0 || a[idx] > n - idx - 1)
    {
        dp[idx] = 0;
        return 0;
    }
    static const int mod = 998244353;
    auto res = 0;
    foreach (i; idx + a[idx] + 1 .. n + 1)
    {
        auto ret = saiki(i, n, a, dp, c);
        res += (cast(long)c[i - idx - 1][a[idx]] * ret) % mod;
        res %= mod;
    }
    dp[idx] = res;
    return res;
}

void solve(int[] a, int n)
{
    static const int mod = 998244353;
    auto c = new int[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(c[i], 0);
    }
    foreach (i; 0 .. n + 1)
    {
        c[i][0] = 1;
    }
    foreach (i; 1 .. n + 1)
    {
        foreach (j; 1 .. i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    auto dp = new int[n + 1];
    fill(dp, -1);
    auto res = 0;
    foreach (i; 0 .. n)
    {
        auto ret = saiki(i, n, a, dp, c);
        res = (res + ret) % mod;
    }
    writeln(res);
}

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

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1 .. n+1) {
        binom[nn][0] = 1;
        foreach (kk; 1 .. nn+1) {
            binom[nn][kk] = addmod(binom[nn-1][kk], binom[nn-1][kk-1]);
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp.fill(0);
    dp[n] = 1;

    long ans = 0;
    foreach_reverse (i; 0 .. n) {
        if (arr[i] <= 0) continue;

        auto k = arr[i] + 1;
        foreach (j; i + k-1 .. n) {
            auto opts = binom[j - i][k - 1];
            dp[i] = dp[i].addmod(opts * dp[j+1] % MOD);

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        ans = ans.addmod(dp[i]);

        debug { writeln(i, ' ', dp[i]); }
    }

    ans.writeln;
}

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

enum mod = 998244353;
alias M = Mod!(long, mod);
M[2000] fact;
M bin(int n, int k)
{
  if (k > n) return M(0);
  return fact[n] * (fact[n - k] * fact[k])^^-1;
}

void main(string[] args)
{
  fact[0] = M(1);
  foreach(i; 1 .. fact.length)
    fact[i] = M(i) * fact[i - 1];

  auto n = next!int;
  auto a = next!int(n);
  debug writeln("got ", a);
  auto noStartingIn = new M[](n);
  foreach_reverse(start; 0 .. n)
    {
      debug writeln("doing from start = ", start);
      if (a[start] <= 0) continue;
      noStartingIn[start] = bin(n - 1 - start, a[start]);
      foreach(otherStart; start + 1 .. n)
	{
	  noStartingIn[start] += bin(otherStart - start - 1, a[start]) * noStartingIn[otherStart];
	}
    }
  noStartingIn.sum.writeln;
  return;
}

auto noDigs(long num)
{
  auto res = int(0);
  while(num)
    {
      num /= 10;
      res++;
    }
  return res;
}

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;
  }
  this(Mod!(T, mod) other)
  {
    _rep = other._rep;
  }
  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 == "^^")
	 {
	   if (exp == -1) exp = mod - 2;
	   return pow(exp);
	 }
  mixin powMethod;
}

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

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

int saiki(int idx, int n, int[] a, int[] dp, int[][] c)
{
    if (dp[idx] != -1)
    {
        return dp[idx];
    }
    if (idx == n)
    {
        dp[idx] = 1;
        return 1;
    }
    if (a[idx] < 0 || a[idx] > n - idx - 1)
    {
        dp[idx] = 0;
        return 0;
    }
    static const int mod = 998244353;
    auto res = 0;
    foreach (i; idx + a[idx] + 1 .. n + 1)
    {
        auto ret = saiki(i, n, a, dp, c);
        res += (cast(long)c[i - idx - 1][a[idx]] * ret) % mod;
        res %= mod;
    }
    dp[idx] = res;
    return res;
}

void solve(int[] a, int n)
{
    static const int mod = 998244353;
    auto c = new int[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(c[i], 0);
    }
    foreach (i; 0 .. n + 1)
    {
        c[i][0] = 1;
    }
    foreach (i; 1 .. n + 1)
    {
        foreach (j; 1 .. i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    auto dp = new int[n + 1];
    fill(dp, -1);
    auto res = 0;
    foreach (i; 0 .. n)
    {
        auto ret = saiki(i, n, a, dp, c);
        res = (res + ret) % mod;
    }
    writeln(res);
}

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

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

void main()
{

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1..n+1) {
        foreach (kk; 0..n+1) {
            binom[nn][kk] = (binom[nn-1][kk] + (kk > 0 ? binom[nn-1][kk-1] : 0)) % MOD;
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp[n] = 0;

    foreach_reverse (i; 0 .. n) {
        auto k = arr[i];
        if (k < 1) continue;

        foreach (j; i + k .. n) {
            auto opts = k == 1 ? 1L : binom[j - 1 - i][k - 2];
            dp[i] = addmod(dp[i], addmod(opts, opts * dp[j+1] % MOD));

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        debug { writeln(i, ' ', dp[i]); }
    }

    auto ans = dp.fold!((a, b) => addmod(a, b));
    ans.writeln;
}

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1 .. n+1) {
        foreach (kk; 0 .. nn+1) {
            binom[nn][kk] = addmod(binom[nn-1][kk], kk > 0 ? binom[nn-1][kk-1] : 0L);
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp.fill(0);

    foreach_reverse (i; 0 .. n) {
        if (arr[i] <= 0) continue;

        auto k = arr[i] + 1;
        foreach (j; i + k-1 .. n) {
            auto opts = binom[j-1 - i][k - 2];
            dp[i] = dp[i].addmod(opts * addmod(dp[j+1], 1) % MOD);

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        dp[i] = dp[i].addmod(dp[i+1]);

        debug { writeln(i, ' ', dp[i]); }
    }

    dp[0].writeln;
}

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1 .. n+1) {
        foreach (kk; 0 .. nn+1) {
            binom[nn][kk] = addmod(binom[nn-1][kk], kk > 0 ? binom[nn-1][kk-1] : 0L);
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp.fill(0);

    foreach_reverse (i; 0 .. n) {
        if (arr[i] <= 0) continue;

        auto k = arr[i] + 1;
        foreach (j; i + k .. n) {
            auto opts = binom[j - i][k - 1];
            dp[i] = dp[i].addmod(opts * addmod(dp[j+1], 1) % MOD);

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        dp[i] = dp[i].addmod(dp[i+1]);

        debug { writeln(i, ' ', dp[i]); }
    }

    dp[0].writeln;
}

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

void main()
{

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1..n+1) {
        foreach (kk; 0..n+1) {
            binom[nn][kk] = addmod(binom[nn-1][kk], kk > 0 ? binom[nn-1][kk-1] : 0L);
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp[n] = 0;

    foreach_reverse (i; 0 .. n) {
        auto k = arr[i] + 1;
        if (k < 2) continue;

        foreach (j; i + k-1 .. n) {
            auto opts = binom[j-1 - i][k - 2];
            dp[i] = dp[i].addmod(opts * addmod(dp[j+1], 1) % MOD);

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        dp[i] = dp[i].addmod(dp[i+1]);

        debug { writeln(i, ' ', dp[i]); }
    }

    dp[0].writeln;
}

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

void main()
{

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1..n+1) {
        foreach (kk; 0..n+1) {
            binom[nn][kk] = addmod(binom[nn-1][kk], kk > 0 ? binom[nn-1][kk-1] : 0L);
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp[n] = 0;

    foreach_reverse (i; 0 .. n) {
        auto k = arr[i];
        if (k < 1) continue;

        foreach (j; i + k .. n) {
            auto opts = k == 1 ? 1L : binom[j - 1 - i][k - 2];
            dp[i] = addmod(dp[i], addmod(opts, opts * dp[j+1] % MOD));

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        dp[i] += dp[i+1];

        debug { writeln(i, ' ', dp[i]); }
    }

    dp[0].writeln;
}

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

immutable int MOD = 998244353;

long addmod(long a, long b) {
    long c = a + b;
    if (c > MOD) c -= MOD;
    return c;
}

void main()
{

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

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

    debug { arr.writeln; }

    auto binom = new long[][] (n+1, n+1);

    binom[0][0] = 1;
    foreach (nn; 1..n+1) {
        foreach (kk; 0..n+1) {
            binom[nn][kk] = addmod(binom[nn-1][kk], kk > 0 ? binom[nn-1][kk-1] : 0L);
        }
    }

    debug { binom.writeln; }

    auto dp = new long[] (n+1);
    dp[n] = 0;

    foreach_reverse (i; 0 .. n) {
        auto k = arr[i];
        if (k < 1) continue;

        foreach (j; i + k .. n) {
            auto opts = k == 1 ? 1L : binom[j - 1 - i][k - 2];
            dp[i] = dp[i].addmod(opts * addmod(dp[j+1], 1) % MOD);

            debug { writeln(i, ' ', j, ' ', opts, ' ', dp[j+1]); }
        }

        dp[i] = dp[i].addmod(dp[i+1]);

        debug { writeln(i, ' ', dp[i]); }
    }

    dp[0].writeln;
}


Three friends are going to meet each other. Initially, the first friend stays at the position $$$x = a$$$, the second friend stays at the position $$$x = b$$$ and the third friend stays at the position $$$x = c$$$ on the coordinate axis $$$Ox$$$.In one minute each friend independently from other friends can change the position $$$x$$$ by $$$1$$$ to the left or by $$$1$$$ to the right (i.e. set $$$x := x - 1$$$ or $$$x := x + 1$$$) or even don't change it.Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let $$$a'$$$, $$$b'$$$ and $$$c'$$$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $$$|a' - b'| + |a' - c'| + |b' - c'|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of test cases. The next $$$q$$$ lines describe test cases. The $$$i$$$-th test case is given as three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) — initial positions of the first, second and third friend correspondingly. The positions of friends can be equal.

For each test case print the answer on it — the minimum total pairwise distance (the minimum sum of distances between each pair of friends) if friends change their positions optimally. Each friend will move no more than once. So, more formally, you have to find the minimum total pairwise distance they can reach after one minute.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int q; get(q);
  while(q--)
    {
      long[] a =  new long[3]; get(a);
      auto sa = sort(a);
      auto res = 2 * (a[2] - a[0]);
      if (a[2] - a[0] <= 1)
	wr(0);
      else
	wr(res - 4);
    }

}

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

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto s = readln.split.map!(to!long);
        auto N = s[0];
        auto M = s[1];
        auto K = s[2];
        long ans = 1L << 59;
        foreach (i; -1..2) foreach (j; -1..2) foreach (k; -1..2) {
            auto a = N + i;
            auto b = M + j;
            auto c = K + k;
            ans = min(ans, abs(a - b) + abs(b - c) + abs(c - a));
        }
        ans.writeln;
    }
}

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

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

void solve(){
	int q = rint;
	foreach(_; 0 .. q){
		long a = rlong, b = rlong, c = rlong;
		long ans = (a + b + c) * 100;
		foreach(i; [a - 1, a, a + 1]) foreach(j; [b - 1, b, b + 1]) foreach(k; [c - 1, c, c + 1]){
			ans.chmin(abs(i - j) + abs(j - k) + abs(k - i));
		}
		ans.writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new int[](q);
	foreach (i; 0..q)
	{
		auto a = RD!int;
		auto b = RD!int;
		auto c = RD!int;
		if (max(a, b, c) - min(a, b, c) <= 2)
			continue;
		auto x = max(a, b, c) - min(a, b, c) - 2;
		ans[i] = x * 2;
	}

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

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

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

void solve(){
	int q = rint;
	foreach(_; 0 .. q){
		int a = rint, b = rint, c = rint;
		int ans = a + b + c;
		foreach(i; [a - 1, a, a + 1]) foreach(j; [b - 1, b, b + 1]) foreach(k; [c - 1, c, c + 1]){
			ans.chmin(abs(i - j) + abs(j - k) + abs(k - i));
		}
		ans.writeln;
	}
}


You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$.

The first line of the input contains integers $$$n$$$ ($$$1\le n \le 10^5$$$) and $$$k$$$ ($$$1 \le k \le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.

Print the only integer — the length of the longest good subsequence of string $$$s$$$.

NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$.

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto S = readln.chomp;

    auto cnt = new int[](26);
    foreach (i; 0..N) cnt[S[i]-'A'] += 1;

    int ans = 1 << 29;
    foreach (i; 0..K) ans = min(ans, cnt[i]);

    writeln(ans * K);
}

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

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

    auto s = readln.chomp;
    auto cnt = new int[k];
    foreach (e; s) ++cnt[e-'A'];

    auto ans = k * cnt.minElement;

    ans.writeln;
}

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

  int n, k; rd(n, k);
  auto s=readln.chomp.to!(char[]);

  int[char] freq;
  foreach(c; s){
    if(c in freq) freq[c]++;
    else freq[c]=1;
  }

  int mn=10^^9;
  for(char c='A'; c<'A'+k; c++){
    if(c in freq) mn=min(mn, freq[c]);
    else mn=min(mn, 0);
  }
  writeln(mn*k);

}

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


Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table).At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit").But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss". Help Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.

The first line of the input contains three integers: n, k and a (1 ≤ n, k, a ≤ 2·105) — the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other. The second line contains integer m (1 ≤ m ≤ n) — the number of Bob's moves. The third line contains m distinct integers x1, x2, ..., xm, where xi is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.

Print a single integer — the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1".

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

alias Seg = Tuple!(int, "l", int, "r");

void main() {
  auto input = readln().split().map!(to!int);
  int n = input[0], k = input[1], x = input[2];
  int m = readln().strip().to!int;
  int[] a = readln().split().map!(to!int).array;
  auto segs = redBlackTree!Seg();
  segs.insert(Seg(0, n));
  int calc(int l, int r) {
    int len = r - l;
    int ans = 0;
    if (len >= x) {
      ans++;
      len -= x;
    }
    ans += len / (x + 1);
    return ans;
  }
  int space = calc(0, n);
  int ans = -1;
  foreach (int i, p; a) {
    p--;
    auto r = segs.lowerBound(Seg(p, n + 1));
    assert(!r.empty());
    Seg s = r.back();
    assert(s.l <= p && p < s.r);
    segs.removeKey(s);
    space -= calc(s.l, s.r);
    Seg s1 = Seg(s.l, p);
    Seg s2 = Seg(p + 1, s.r);
    space += calc(s1.l, s1.r);
    space += calc(s2.l, s2.r);
    segs.insert(s1);
    segs.insert(s2);
    if (space < k) {
      ans = i + 1;
      break;
    }
  }
  writeln(ans);
}

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

alias Seg = Tuple!(int, "l", int, "r");

void main() {
  auto input = readln().split().map!(to!int);
  int n = input[0], k = input[1], x = input[2];
  int m = readln().strip().to!int;
  int[] a = readln().split().map!(to!int).array;
  auto segs = redBlackTree!Seg();
  segs.insert(Seg(0, n));
  int space = n / x;
  int ans = -1;
  foreach (int i, p; a) {
    p--;
    auto r = segs.lowerBound(Seg(p, n + 1));
    assert(!r.empty());
    Seg s = r.back();
    assert(s.l <= p && p < s.r);
    segs.removeKey(s);
    space -= (s.r - s.l) / x;
    Seg s1 = Seg(s.l, p);
    Seg s2 = Seg(p + 1, s.r);
    space += (s1.r - s1.l) / x;
    space += (s2.r - s2.l) / x;
    segs.insert(s1);
    segs.insert(s2);
    if (space < k) {
      ans = i + 1;
      break;
    }
  }
  writeln(ans);
}


You are given a positive integer $$$n$$$. Since $$$n$$$ may be very large, you are given its binary representation.You should compute the number of triples $$$(a,b,c)$$$ with $$$0 \leq a,b,c \leq n$$$ such that $$$a \oplus b$$$, $$$b \oplus c$$$, and $$$a \oplus c$$$ are the sides of a non-degenerate triangle. Here, $$$\oplus$$$ denotes the bitwise XOR operation.You should output the answer modulo $$$998\,244\,353$$$.Three positive values $$$x$$$, $$$y$$$, and $$$z$$$ are the sides of a non-degenerate triangle if and only if $$$x+y>z$$$, $$$x+z>y$$$, and $$$y+z>x$$$.

The first and only line contains the binary representation of an integer $$$n$$$ ($$$0 < n < 2^{200\,000}$$$) without leading zeros. For example, the string 10 is the binary representation of the number $$$2$$$, while the string 1010 represents the number $$$10$$$.

Print one integer — the number of triples $$$(a,b,c)$$$ satisfying the conditions described in the statement modulo $$$998\,244\,353$$$.

NoteIn the first test case, $$$101_2=5$$$.  The triple $$$(a, b, c) = (0, 3, 5)$$$ is valid because $$$(a\oplus b, b\oplus c, c\oplus a) = (3, 6, 5)$$$ are the sides of a non-degenerate triangle.  The triple $$$(a, b, c) = (1, 2, 4)$$$ is valid because $$$(a\oplus b, b\oplus c, c\oplus a) = (3, 6, 5)$$$ are the sides of a non-degenerate triangle. The $$$6$$$ permutations of each of these two triples are all the valid triples, thus the answer is $$$12$$$.In the third test case, $$$11\,011\,111\,101\,010\,010_2=114\,514$$$. The full answer (before taking the modulo) is $$$1\,466\,408\,118\,808\,164$$$.

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

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

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

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

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

enum MO = 998244353;
alias Mint = ModInt!MO;

void main() {
  debug {{
    foreach (n; 1 .. 8 + 1) {
      int cnt;
      foreach (a; 0 .. 1 << n) foreach (b; 0 .. 1 << n) foreach (c; 0 .. 1 << n) {
        const x = b ^ c;
        const y = c ^ a;
        const z = a ^ b;
        if (x > 0 && y > 0 && z > 0 && y + z > x && z + x > y && x + y > z) {
        } else {
          ++cnt;
          if (n <= 4) {
            writefln("%02d %02d %02d; %02d %02d %02d", a, b, c, x, y, z);
          }
          const okX = (x == y + z && !(y & z));
          const okY = (y == z + x && !(z & x));
          const okZ = (z == x + y && !(x & y));
          assert(okX || okY || okZ);
          if (n <= 4) {
            if ((okX ? 1 : 0) + (okY ? 1 : 0) + (okZ ? 1 : 0) >= 2) {
              stderr.writefln("%02d %02d %02d; %02d %02d %02d", a, b, c, x, y, z);
            }
          }
        }
      }
      stderr.writeln(n, ": ", cnt);
    }
  }}
  /*
1: 0
2: 0
3: 48
4: 960
5: 12480
6: 134400
7: 1306368
8: 11934720
  */

  Mint[8][8][2] trans;
  foreach (s; 0 .. 2) {
    foreach (p; 0 .. 8) {
      foreach (x; 0 .. 8) {
        bool ok = true;
        int q = p;
        foreach (j; 0 .. 3) {
          ok = ok && ((p >> j & 1) || ((x >> j & 1) <= s));
          if ((x >> j & 1) < s) {
            q |= 1 << j;
          }
        }
        const a = (x >> 0 & 1);
        const b = (x >> 1 & 1);
        const c = (x >> 2 & 1);
        ok = ok && ((b ^ c) == (c ^ a) + (a ^ b));
        if (ok) {
          debug {
            writeln(s, " ", p, " ", [a, b, c]);
          }
          trans[s][p][q] += 1;
        }
      }
    }
  }

  try {
    for (; ; ) {
      const S = readToken;
      const L = cast(int)(S.length);

      Mint n;
      foreach (i; 0 .. L) {
        n = n * 2 + (S[i] - '0');
      }
      debug {
        writeln("n = ", n);
      }

      // f1: smaller
      Mint[8] crt;
      crt[0] = 1;
      foreach (i; 0 .. L) {
        Mint[8] nxt;
        foreach (p; 0 .. 8) {
          foreach (q; 0 .. 8) {
            nxt[q] += crt[p] * trans[S[i] - '0'][p][q];
          }
        }
        crt = nxt;
      }

      Mint ans;
      foreach (p; 0 .. 8) {
        ans += crt[p];
      }
      debug {
        writeln("ans = ", ans);
      }
      ans *= 3;
      ans -= 3 * n * (n + 1);
      ans -= 2 * (n + 1);
      ans = (n + 1)^^3 - ans;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Nezzar has $$$n$$$ balls, numbered with integers $$$1, 2, \ldots, n$$$. Numbers $$$a_1, a_2, \ldots, a_n$$$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $$$a_i \leq a_{i+1}$$$ for all $$$1 \leq i < n$$$.Nezzar wants to color the balls using the minimum number of colors, such that the following holds.  For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls.  Note that a sequence with the length at most $$$1$$$ is considered as a strictly increasing sequence.Please help Nezzar determine the minimum number of colors.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases.  The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that $$$a_1 \leq a_2 \leq \ldots \leq a_n$$$.

For each test case, output the minimum number of colors Nezzar can use.

NoteLet's match each color with some numbers. Then:In the first test case, one optimal color assignment is $$$[1,2,3,3,2,1]$$$.In the second test case, one optimal color assignment is $$$[1,2,1,2,1]$$$.

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 last, c, max_c;
        foreach (a; readln.split.to!(int[])) {
            if (last != a) {
                max_c = max(max_c, c);
                c = 0;
            }
            last = a;
            ++c;
        }
        writeln(max(max_c, c));
    }
}

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

void theCode(){
    int n;
    n = scan!int;
    auto arr = scanArray;
    ll eq = 1, maxeq = 1;
    for(int i = 1; i < n; ++i){
        if(arr[i] == arr[i-1]){
            ++eq;
        }else{
            maxeq = max(eq, maxeq);
            eq = 1;
        }
    }
    maxeq = max(maxeq, eq);
    writeln(maxeq);
}

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

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

import std.algorithm;
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;
		sort (a);
		a.group.map !(q{a[1]}).maxElement.writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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(-1);

		auto cnt = new int[](n);
		foreach (e; a)
			++cnt[e];
		ans[ti] = cnt.maxElement;
	}

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


You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units.  Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0.

The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline.

NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below:  The optimal (and the only possible) pipeline for the third query is shown below:  The optimal pipeline for the fourth query is shown below:

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto T = RD!int;
	auto ans = new long[](T);
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto a = RD!int;
		auto b = RD!int;
		auto s = RD!string;
		auto dp = new long[][](n+1, 2);
		dp[0][0] = b;
		foreach (j; 0..n)
		{
			if (s[j] == '0')
			{
				if (dp[j][0] != 0)
				{
					dp[j+1][0] = dp[j][0] + a + b;
				}
				if (dp[j][1] != 0)
				{
					dp[j+1][1] = dp[j][1] + a + b*2;
					if (dp[j][0] == 0)
						dp[j+1][0] = dp[j][1] + a*2 + b*2;
				}
			}
			else
			{
				if (dp[j][0] == 0)
				{
					dp[j+1][1] = dp[j][1] + a + b*2;
				}
				else
				{
					auto c1 = dp[j][1] == 0 ? long.max : dp[j][1] + a + b*2;
					auto c2 = dp[j][0] + a*2 + b*2;
					dp[j+1][1] = min(c1, c2);
				}
			}
		}
		ans[i] = dp[n][0];
	}

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


You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile — then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.You would like to purify all n × n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.

The first line will contain a single integer n (1 ≤ n ≤ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.

If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.

NoteThe first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously.   In the second example, it is impossible to purify the cell located at row 1 and column 1.For the third example:

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

immutable int NA = -1;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = new string [n];
		foreach (i; 0..n)
		{
			a[i] = readln ().strip ();
		}
		int [] ans;

		ans = new int [0];
		foreach (i; 0..n)
		{
			int cur = NA;
			foreach (j; 0..n)
			{
				if (a[i][j] == '.')
				{
					cur = j;
					break;
				}
			}
			if (cur == NA)
			{
				break;
			}
			ans ~= cur;
		}
		if (ans.length == n)
		{
			foreach (i; 0..n)
			{
				writefln ("%s %s", i + 1, ans[i] + 1);
			}
			continue;
		}

		ans = new int [0];
		foreach (i; 0..n)
		{
			int cur = NA;
			foreach (j; 0..n)
			{
				if (a[j][i] == '.')
				{
					cur = j;
					break;
				}
			}
			if (cur == NA)
			{
				break;
			}
			ans ~= cur;
		}
		if (ans.length == n)
		{
			foreach (i; 0..n)
			{
				writefln ("%s %s", ans[i] + 1, i + 1);
			}
			continue;
		}

		writeln (-1);
	}
}


You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c). You are staying in the cell (r1, c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2, c2) since the exit to the next level is there. Can you do this?

The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description. Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice). The next line contains two integers, r1 and c1 (1 ≤ r1 ≤ n, 1 ≤ c1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1, c1), that is, the ice on the starting cell is initially cracked. The next line contains two integers r2 and c2 (1 ≤ r2 ≤ n, 1 ≤ c2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.

If you can reach the destination, print 'YES', otherwise print 'NO'.

NoteIn the first sample test one possible path is:After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.


Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last.

The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n). Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.

Print the total number of moves Alice and Bob will make.

NoteIn the first example the tree looks like this:  The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this:  The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable long mod = 10^^9 + 7;

void main(){
    int n, x, ai, bi;
    readVars(n, x);
    --x;

    auto adj = new int[][](n);
    foreach(i ; 0 .. n - 1){
        readVars(ai, bi);
        ai--;
        bi--;
        adj[ai] ~= bi;
        adj[bi] ~= ai;
    }

    auto h = new int[](n);
    auto d = new int[](n);
    auto p = new int[](n);

    dfs(n, adj, p, d, h, 0, 0);

    //stderr.writeln(h);
    //stderr.writeln(d);
    //stderr.writeln(p);

    int ans = 2 * (h[x] + d[x]);
    int lim = (d[x] - 1) / 2;

    foreach(i ; 0 .. lim) {
        x = p[x];
        ans = max(ans, 2 * (h[x] + d[x]));
    }

    writeln(ans);
}

int dfs(int n, int[][] adj, int[] p, int[] d, int[] h, int parent, int u){
    p[u] = parent;
    int res;

    foreach(v ; adj[u]){
        if (v != parent) {
            d[v] = d[u] + 1;
            res = max(res, dfs(n, adj, p, d, h, u, v) + 1);
        }
    }

    h[u] = res;
    return res;
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        throw new Exception("args num < input num");
    }
}


You are given several queries. Each query consists of three integers $$$p$$$, $$$q$$$ and $$$b$$$. You need to answer whether the result of $$$p/q$$$ in notation with base $$$b$$$ is a finite fraction.A fraction in notation with base $$$b$$$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of queries. Next $$$n$$$ lines contain queries, one per line. Each line contains three integers $$$p$$$, $$$q$$$, and $$$b$$$ ($$$0 \le p \le 10^{18}$$$, $$$1 \le q \le 10^{18}$$$, $$$2 \le b \le 10^{18}$$$). All numbers are given in notation with base $$$10$$$.

For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.

import std.stdio;

long mulmod (long a, long b, long m)
{
	long res = 0;
	while (b)
	{
		if (b & 1)
		{
			res += a;
			if (res >= m)
			{
				res -= m;
			}
		}
		a <<= 1;
		if (a >= m)
		{
			a -= m;
		}
		b >>= 1;
	}
	return res;
}

void main ()
{
	int tests;
	readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		long p, q, b;
		readf (" %s %s %s", &p, &q, &b);
		immutable int steps = 6;
		b %= q;
		foreach (step; 0..steps)
		{
			b = mulmod (b, b, q);
		}
		p %= q;
		p = mulmod (p, b, q);
		writeln (p == 0 ? "Finite" : "Infinite");
	}
}

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

T gcd(T) (T a, T b) pure nothrow @nogc {
  if (a < b) {
    swap (a, b);
  }
  while (b) {
    T c = a % b; a = b; b = c;
  }
  return a;
}

void main() {
  int nt;
  readf (" %d", &nt);
  foreach (t; 0 .. nt) {
    long p, q, b;
    readf (" %d %d %d", &p, &q, &b);
    long g = gcd (p, q);
    q /= g;
    while (true) {
      debug stderr.writefln ("q = %d b = %d", q, b);
      g = gcd (q, b);
      if (g == 1) break;
      while (true) {
        long r = q / g;
        if (r * g != q) break;
        q = r;
      }
    }
    writeln (q == 1 ? "Finite" : "Infinite");
  }
}

import std.stdio;

long mulmod (long a, long b, long m)
{
	long res = 0;
	while (b)
	{
		a <<= 1;
		if (a >= m)
		{
			a -= m;
		}
		if (b & 1)
		{
			res += a;
			if (res >= m)
			{
				res -= m;
			}
		}
		b >>= 1;
	}
	return res;
}

void main ()
{
	int tests;
	readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		long p, q, b;
		readf (" %s %s %s", &p, &q, &b);
		immutable int steps = 6;
		b %= q;
		foreach (step; 0..steps)
		{
			b = mulmod (b, b, q);
		}
		p %= q;
		p = mulmod (p, b, q);
		writeln (p == 0 ? "Finite" : "Infinite");
	}
}


Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!

The first line contains integer n (1 ≤ n ≤ 105), showing how many numbers the array has. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the array elements.

Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them.

import std.stdio;
import std.exception;
import std.algorithm;
import std.math;
import std.typecons;

void main(){
	int n;
	readf("%d\n",&n);
	int s=0, min=1000000000;
	auto a = new int[n];
	foreach(i; 0..n){
		readf("%d", &a[i]);
		if (i<n-1) readf(" ");
		if (a[i]<min) min=a[i];
	}
	foreach(i; 0..n){
		if (a[i]%min){
			min=-1;
			break;
		}
	}
	writefln("%d",min);
}

import std.stdio;
import std.exception;
import std.algorithm;
import std.math;
import std.typecons;

void main(){
	int n;
	readf("%d\n",&n);
	int s=0, min=10000000;
	auto a = new int[n];
	foreach(i; 0..n){
		readf("%d", &a[i]);
		if (i<n-1) readf(" ");
		if (a[i]<min) min=a[i];
	}
	foreach(i; 0..n){
		if (a[i]%min!=0){
			min=-1;
			break;
		}
	}
	writefln("%d",min);
}


Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ 105; xi ≠ yi) — the color numbers for the home and away kits of the i-th team.

For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

unittest{
  assert(solve(1) == [1], "Teste 1");
}

void solve(ulong[] a, ulong[] h){
  ulong[ulong] c;
  for(size_t i = 0; i < a.length; i++){
    ++c[a[i]];
  }

  for(size_t i = 0; i < a.length; i++){
    ulong cter = c.get(h[i],0);
    writefln("%s %s",a.length+cter-1,a.length-cter-1);
  }
}

void main(){
  size_t n;

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

  ulong[] h = new ulong[n];
  ulong[] a = new ulong[n];
  for(size_t i = 0; i < n; i++){
    ulong ia,ih;
    readf("%s %s\n",&ia,&ih);
    a[i] = ia;
    h[i] = ih;
  }

  solve(a,h);
  // auto s = r.map!"to!string(a)".array;
}


You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x < n$$$ and $$$1 \le y < m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.

If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto A = new int[][](n, m);
	auto B = new int[][](n, m);
	foreach (i; 0..n)
	{
		A[i] = RDA!int;
	}

	long[2][] ans;
	foreach (y; 0..n-1)
	{
		foreach (x; 0..m-1)
		{
			if (A[y][x] == 1)
			{
				if (A[y+1][x] == 1 && A[y][x+1] == 1 && A[y+1][x+1] == 1)
				{
					ans ~= [y+1, x+1];
					B[y][x]     = 1;
					B[y+1][x]   = 1;
					B[y][x+1]   = 1;
					B[y+1][x+1] = 1;
				}
			}
		}
	}

	bool ok = true;
	foreach (y; 0..n)
	{
		foreach (x; 0..m)
		{
			if (A[y][x] != B[y][x])
			{
				ok = false;
			}
		}
	}

	if (ok)
	{
		writeln(ans.length);
		foreach (e; ans)
			writeln(e[0], " ",e[1]);
	}
	else
	{
		writeln(-1);
	}
	stdout.flush();
	debug readln();
}


A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).

The first and only line consists of a string $$$S$$$ ($$$ 1 \le |S| \le 5\,000 $$$). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.

Print "YES" or "NO", according to the condition.

NoteConsider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.Consider third example: the number of 'c' is equal to the number of 'b'.

/+ dub.sdl:
    name "A"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv, std.regex;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    string s;
    sc.read(s);
    auto r = regex(r"^a+b+c+$");
    if (!matchFirst(s, r)) {
        writeln("NO");
    } else {
        if (s.count('a') != s.count('c') && s.count('b') != s.count('c')) {
            writeln("NO");
        } else {
            writeln("YES");
        }
    }
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  string s; readV(s);

  auto m = s.matchFirst(r"^(a+)(b+)(c+)$");
  writeln(m && (m[1].length == m[3].length || m[2].length == m[3].length) ? "YES" : "NO");
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const S = readToken();
      auto grp = S.group.array;
      bool ans = true;
      ans = ans && (grp.length == 3);
      ans = ans && (grp[0][0] == 'a');
      ans = ans && (grp[1][0] == 'b');
      ans = ans && (grp[2][0] == 'c');
      ans = ans && (grp[2][1] == grp[0][1] || grp[2][1] == grp[1][1]);
      writeln(ans ? "YES" : "NO");
    }
  } catch (EOFException e) {
  }
}

/+ dub.sdl:
    name "A"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv, std.regex;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    string s;
    sc.read(s);
    auto r = regex(r"a+b+c+");
    if (!matchFirst(s, r)) {
        writeln("NO");
    } else {
        if (s.count('a') != s.count('c') && s.count('b') != s.count('c')) {
            writeln("NO");
        } else {
            writeln("YES");
        }
    }
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/


A tree is an undirected connected graph without cycles.You are given a tree of $$$n$$$ vertices. Find the number of ways to choose exactly $$$k$$$ vertices in this tree (i. e. a $$$k$$$-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer $$$c$$$ such that for all $$$u, v$$$ ($$$u \ne v$$$, $$$u, v$$$ are in selected vertices) $$$d_{u,v}=c$$$, where $$$d_{u,v}$$$ is the distance from $$$u$$$ to $$$v$$$).Since the answer may be very large, you need to output it modulo $$$10^9 + 7$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. Each test case consists of several lines. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 100$$$) — the number of vertices in the tree and the number of vertices to be selected, respectively. Then $$$n - 1$$$ lines follow, each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) which describe a pair of vertices connected by an edge. It is guaranteed that the given graph is a tree and has no loops or multiple edges.

For each test case output in a separate line a single integer — the number of ways to select exactly $$$k$$$ vertices so that for all pairs of selected vertices the distances between the vertices in the pairs are equal, modulo $$$10^9 + 7$$$ (in other words, print the remainder when divided by $$$1000000007$$$).

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

void dfs(int node, int p, int[][] t, int[][] c)
{
    auto n = to!int(t.length);
    fill(c[node], 0);
    c[node][0] = 1;
    const int mod = 1000000007;
    foreach (i; 0 .. t[node].length) if (t[node][i] != p)
    {
        dfs(t[node][i], node, t, c);
        foreach (j; 1 .. n) c[node][j] = (c[node][j] + c[t[node][i]][j - 1]) % mod;
    }
}

int solve(int[][] t, int k)
{
    auto n = to!int(t.length);
    if (k == 2) return n * (n - 1) / 2;
    auto c = new int[][](n, n);
    auto pdp = new long[k + 1];
    auto ndp = new long[k + 1];
    const int mod = 1000000007;
    auto res = 0;
    foreach (i; 0 .. n)
    {
        dfs(i, -1, t, c);
        foreach (j; 0 .. n)
        {
            fill(pdp, 0);
            pdp[0] = 1;
            foreach (ni; 0 .. t[i].length)
            {
                ndp[0] = pdp[0];
                foreach (ki; 1 .. k + 1)
                {
                    ndp[ki] = (pdp[ki] + (pdp[ki - 1] * c[t[i][ni]][j]) % mod) % mod;
                }
                ndp.copy(pdp);
            }
            res = (res + pdp[k]) % mod;
        }
    }
    return res;
}

int main(string[] args)
{
    auto T = to!int(readln.strip);
    foreach (_; 0 .. T)
    {
        readln;
        auto r = map!(to!int)(readln.strip.split(" ")).array;
        auto n = r[0], k = r[1];
        auto t = new int[][n];
        foreach (i; 0 .. n - 1)
        {
            r = map!(to!int)(readln.strip.split(" ")).array;
            auto u = r[0] - 1, v = r[1] - 1;
            t[u] ~= v; t[v] ~= u;
        }
        auto ret = solve(t, k);
        writeln(ret);
    }
    return 0;
}