A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.

First line of input data contains single integer n (1 ≤ n ≤ 300) — length of the array. Next line contains n integers a1, a2, ... , an (1 ≤ ai ≤ 109) — found array.

Output single integer — number of right permutations modulo 109 + 7.

NoteFor first example:[1, 2, 4] — right permutation, because 2 and 8 are not perfect squares.[1, 4, 2] — wrong permutation, because 4 is square of 2.[2, 1, 4] — wrong permutation, because 4 is square of 2.[2, 4, 1] — wrong permutation, because 4 is square of 2.[4, 1, 2] — wrong permutation, because 4 is square of 2.[4, 2, 1] — right permutation, because 8 and 2 are not perfect squares.

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

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

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

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

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

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

enum LIM = 1005;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

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

      auto as = A.dup;
      foreach (i; 0 .. N) {
        for (long p = 2; p^^2 <= as[i]; ++p) {
          for (; as[i] % p^^2 == 0; as[i] /= p^^2) {}
        }
      }
      const bs = as.sort.group.map!(g => cast(int)(g[1])).array;
      debug {
        writeln("bs = ", bs);
      }
      const bsLen = cast(int)(bs.length);
      auto bsSum = new int[bsLen + 1];
      foreach (j; 0 .. bsLen) {
        bsSum[j + 1] = bsSum[j] + bs[j];
      }

      auto dp = new Mint[][](bsLen + 1, N + 1);
      dp[0][0] = 1;
      foreach (j; 0 .. bsLen) foreach (a; 0 .. N + 1) {
        if (dp[j][a]) {
          foreach (x; 0 .. bs[j] + 1) foreach (y; 0 .. bs[j] - x + 1) {
            if (x + y >= 1 && a >= x && bsSum[j] + 1 - a >= y) {
              dp[j + 1][a - x + (bs[j] - x - y)] += dp[j][a] * binom(a, x) * binom(bsSum[j] + 1 - a, y) * binom(bs[j] - 1, x + y - 1);
            }
          }
        }
      }
      Mint ans = dp[bsLen][0];
      foreach (j; 0 .. bsLen) {
        ans *= fac[bs[j]];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

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

enum LIM = 1005;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

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

      auto as = A.dup;
      foreach (i; 0 .. N) {
        for (long p = 2; p^^2 <= as[i]; ++p) {
          for (; as[i] % p^^2 == 0; as[i] /= p^^2) {}
        }
      }
      const bs = as.sort.group.map!(g => cast(int)(g[1])).array;
      debug {
        writeln("bs = ", bs);
      }
      const bsLen = cast(int)(bs.length);
      auto bsSum = new int[bsLen + 1];
      foreach (j; 0 .. bsLen) {
        bsSum[j + 1] = bsSum[j] + bs[j];
      }

      auto dp = new Mint[][](bsLen + 1, N + 1);
      dp[0][0] = 1;
      foreach (j; 0 .. bsLen) foreach (a; 0 .. N + 1) {
        if (dp[j][a]) {
          foreach (x; 0 .. bs[j] + 1) foreach (y; 0 .. bs[j] - x + 1) {
            if (x + y >= 1 && a >= x && bsSum[j] + 1 >= y) {
              dp[j + 1][a - x + (bs[j] - x - y)] += dp[j][a] * binom(a, x) * binom(bsSum[j] + 1, y) * binom(bs[j] - 1, x + y - 1);
            }
          }
        }
      }
      Mint ans = dp[bsLen][0];
      foreach (j; 0 .. bsLen) {
        ans *= fac[bs[j]];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of numbers on the board. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$).

Print one number that will be left on the board.

NoteIn the first sample, the first player erases $$$3$$$ and the second erases $$$1$$$. $$$2$$$ is left on the board.In the second sample, $$$2$$$ is left on the board regardless of the actions of the players.

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n = readln.chomp.to!int;
	int[] a = readln.chomp.split.map!(to!int).array;
	std.algorithm.sort(a);
	a[(n - 1) / 2].writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

import std.stdio;
import std.algorithm;
int main()
{
	int a=0;
	readf(" %d", &a);
	int[] m = new int[a];
	for (int i=0; i<a; i++)
	{
		readf(" %d", &m[i]);
	}
	sort(m);
	if (a%2==1)
	{
		writeln(m[a/2]);
	}
	else
	{
		writeln(m[a/2-1]);
	}
	return 0;
}

import std.stdio;
import std.algorithm;
int main()
{
	int a=0;
	readf(" %d", &a);
	int[] m = new int[a];
	for (int i=0; i<a; i++)
	{
		readf(" %d", &m[i]);
	}
	sort(m);
	writeln(m[a/2]);
	return 0;
}


"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For every test case print one non-negative integer — the answer to the problem.

NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs.

import std.stdio;
import std.algorithm;

int main() {
	int t;
	scanf("%d", &t);
	while (t --> 0) {
        int n;
		scanf("%d", &n);
		int[] a = new int[n];
        int[] cnt = new int [42];
        long result = 0;
		for (int i = 0; i < n; ++i) {
			scanf("%d", &a[i]);
            int bit_id = 0;
            while (a[i] > 0) {
            	++bit_id;
                a[i] /= 2;
            }
            result += cnt[bit_id];
            ++cnt[bit_id];
		}
		printf("%lld\n", result);
	}

	return 0;
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    sort(arr);
    ll tim = 1;
    ll res = 0;
    ll cnt = 0;
    foreach(i; 0..n){
        ll num = arr[i];
        bool chang = 0;
        while(num > 0 && num >= tim*2){
            tim *= 2;
            chang = 1;
        }
        if(!chang){
            ++cnt;
        }else{
            res += cnt*(cnt - 1)/2;
            cnt = 1;
        }
    }
    res += cnt*(cnt - 1)/2;
    writeln(res);
}

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

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) {
            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]));
            }
        }
    }
}

uint bits_msb(uint v)
{
    v = v | (v >>  1);
    v = v | (v >>  2);
    v = v | (v >>  4);
    v = v | (v >>  8);
    v = v | (v >> 16);
    return v ^ (v >> 1);
}

void solve()
{
    int N; get(N);
    uint[] AS; get(AS);
    long[33] cs;
    foreach (a; AS) {
        a = bits_msb(a);
        static foreach (i; 0..33) {
            if (a & 1) ++cs[i];
            a >>= 1;
        }
    }
    long r;
    foreach (c; cs) r += c * (c-1) / 2;
    writeln(r);
}

void main()
{
    int T; get(T);
    foreach (_; 0..T) solve();
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (a);
		int j = 0;
		long res = 0;
		foreach (i; 0..n)
		{
			while (j < n && (a[i] & a[j]) >= (a[i] ^ a[j]))
			{
				j += 1;
			}
			res += j - i - 1;
		}
		writeln (res);
	}
}

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;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto a = next!long(n);
      long[35] cnt;
      cnt[] = 0;
      foreach(ai; a)
	{
	  int bits = 0;
	  while(ai != 0)
	    {
	      bits++;
	      ai >>= 1;
	    }
	  cnt[bits]++;
	}
      long res = 0;
      foreach(c; cnt)
	{
	  res += (c * (c - 1)) / 2;
	}
      res.writeln;
    }
}
ulong bitCnt(T)(T x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new long[](63);
		foreach (i; 0..n)
		{
			foreach_reverse (j; 0..63)
			{
				auto bit = 1L << j;
				if (a[i] & bit)
				{
					++cnt[j];
					break;
				}
			}
		}

		foreach (i; 0..63)
		{
			ans[ti] += cnt[i]*(cnt[i]-1)/2;
		}
	}

	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) {
            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]));
            }
        }
    }
}

uint bits_msb(uint v)
{
    v = v | (v >>  1);
    v = v | (v >>  2);
    v = v | (v >>  4);
    v = v | (v >>  8);
    v = v | (v >> 16);
    return v ^ (v >> 1);
}

void solve()
{
    int N; get(N);
    uint[] AS; get(AS);
    long[10] cs;
    foreach (a; AS) {
        a = bits_msb(a);
        static foreach (i; 0..10) {
            if (a & 1) ++cs[i];
            a >>= 1;
        }
    }
    long r;
    foreach (c; cs) r += c * (c-1) / 2;
    writeln(r);
}

void main()
{
    int T; get(T);
    foreach (_; 0..T) solve();
}

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;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto a = next!int(n);
      int[35] cnt;
      cnt[] = 0;
      foreach(ai; a)
	{
	  int bits = 0;
	  while(ai != 0)
	    {
	      bits++;
	      ai >>= 1;
	    }
	  cnt[bits]++;
	}
      long res = 0;
      foreach(i, c; cnt)
	{
	  res += c * (c - 1) / 2;
	}
      res.writeln;
    }
}
ulong bitCnt(T)(T x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form:  Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.

The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.

Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.

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;

auto positive(T)(T t)
{
  if (t < 0) return -t;
  return t;
}

struct Fraction(T)
{
  T numerator;
  T denominator;
  this(T numerator, T denominator)
  {
    auto commonDivisor = gcd(numerator.positive, denominator.positive);
    numerator /= commonDivisor;
    denominator /= commonDivisor;
    debug assert(denominator != 0);
    this.numerator = numerator;
    this.denominator = denominator;
    if (this.denominator < 0)
      {
	this.numerator *= -1;
	this.denominator *= -1;
      }
  }
  string toString()
  {
    return text(cast(real)numerator / cast(real)denominator);
  }
  auto opBinary(string operation)(const Fraction!T rhs) const
  {
    static if (operation == "+")
      {
	return Fraction!T(this.numerator * rhs.denominator + rhs.numerator * this.denominator,
			  this.denominator * rhs.denominator);
      }
    else static if (operation == "-")
      {
	return Fraction!T(this.numerator * rhs.denominator - rhs.numerator * this.denominator,
			  this.denominator * rhs.denominator);
      }
    else static if (operation == "*")
      {
	return Fraction!T(this.numerator * rhs.numerator, this.denominator * rhs.denominator);
      }
    else static if (operation == "/")
      {
	return Fraction!T(this.numerator * rhs.denominator, this.denominator * rhs.numerator);
      }
  }
  bool opEquals(const Fraction!T rhs) const
  {
    return this.numerator == rhs.numerator && this.denominator == rhs.denominator;
  }
  int opCmp(const Fraction!T rhs) const
  {
    auto difference = this - rhs;
    if (difference.numerator > 0)
      return 1;
    if (difference.numerator < 0)
      return -1;
    return 0;
  }
}

void main(string[] args)
{
  auto n = next!int;
  auto k = new long[](n);
  auto b = new long[](n);
  long[real] sumOnPoint;
  auto points = redBlackTree!real();
  foreach(i; 0 .. n)
    {
      k[i] = next!long;
      b[i] = next!long;
      if (k[i] != 0)
	{
	  auto root = cast(real)(-b[i]) / cast(real)k[i];
	  points.insert(root);
	  if (k[i] > 0)
	    {
	      sumOnPoint.require(root, 0) += k[i];
	    }
	  else
	    {
	      sumOnPoint.require(root, 0) -= k[i];
	    }
	}
      else
	{

	}
    }
  points[].map!(p => sumOnPoint[p]).count!(s => s != 0).writeln;
}

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

auto positive(T)(T t)
{
  if (t < 0) return -t;
  return t;
}

struct Fraction(T)
{
  T numerator;
  T denominator;
  this(T numerator, T denominator)
  {
    auto commonDivisor = gcd(numerator.positive, denominator.positive);
    numerator /= commonDivisor;
    denominator /= commonDivisor;
    debug assert(denominator != 0);
    this.numerator = numerator;
    this.denominator = denominator;
    if (this.denominator < 0)
      {
	this.numerator *= -1;
	this.denominator *= -1;
      }
  }
  auto opBinary(string operation)(const Fraction!T rhs) const
  {
    static if (operation == "+")
      {
	return Fraction!T(this.numerator * rhs.denominator + rhs.numerator * this.denominator,
			  this.denominator * rhs.denominator);
      }
    else static if (operation == "-")
      {
	return Fraction!T(this.numerator * rhs.denominator - rhs.numerator * this.denominator,
			  this.denominator * rhs.denominator);
      }
    else static if (operation == "*")
      {
	return Fraction!T(this.numerator * rhs.numerator, this.denominator * rhs.denominator);
      }
    else static if (operation == "/")
      {
	return Fraction!T(this.numerator * rhs.denominator, this.denominator * rhs.numerator);
      }
  }
  bool opEquals(const Fraction!T rhs) const
  {
    return this.numerator == rhs.numerator && this.denominator == rhs.denominator;
  }
  int opCmp(const Fraction!T rhs) const
  {
    auto difference = this - rhs;
    if (difference.numerator > 0)
      return 1;
    if (difference.numerator < 0)
      return -1;
    return 0;
  }
}

void main(string[] args)
{
  auto n = next!int;
  auto k = new long[](n);
  auto b = new long[](n);
  long[Tuple!(long, long)] sumOnPoint;
  auto points = redBlackTree!(Fraction!long)();
  foreach(i; 0 .. n)
    {
      k[i] = next!long;
      b[i] = next!long;
      if (k[i] != 0)
	{
	  auto root = Fraction!long(-b[i], k[i]);
	  points.insert(root);
	  sumOnPoint.require(tuple(root.numerator, root.denominator), 0) += k[i];
	}
      else
	{

	}
    }
  debug writeln("points are : ", points[]);
  int cnt = 0;
  long prevSum = 0;
  foreach(point; points)
    {
      auto delta = sumOnPoint[tuple(point.numerator, point.denominator)];
      if (delta != 0)
	{
	  prevSum += delta;
	  cnt ++;
	}
    }
  cnt.writeln;
}

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


Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500.If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem.There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.Unfortunately, Vasya is a cheater. He has registered 109 + 7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.

The first line contains a single integer n (2 ≤ n ≤ 120) — the number of round participants, including Vasya and Petya. Each of the next n lines contains five integers ai, 1, ai, 2..., ai, 5 ( - 1 ≤ ai, j ≤ 119) — the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j. It is guaranteed that each participant has made at least one successful submission. Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order.

Output a single integer — the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal.

NoteIn the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980 + 940 + 420 + 360 + 270 = 2970 points, while Petya will score just 800 + 820 + 420 + 440 + 470 = 2950 points.In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points.In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one.

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		auto v=new int[5],p=new int[5],k=new int[5];
		foreach(i;0..5)
		{
			input(v[i]);
			if(v[i]!=-1)k[i]++;
		}
		foreach(i;0..5)
		{
			input(p[i]);
			if(p[i]!=-1)k[i]++;
		}
		debug putarr(v);
		debug writeln;
		debug putarr(p);
		foreach(i;0..n-2)
		{
			foreach(j;0..5)
			{
				int x;
				input(x);
				if(x!=-1)k[j]++;
			}
		}
		foreach(akks;0..32*n)
		{
			int vas,pet;
			foreach(i;0..5)
			{
				if(v[i]==-1)
				{
					if(p[i]==-1)continue;
					int x=(n+akks)/(k[i]);
					if(x>=32)pet+=3000-3000*p[i]/250;
					else if(x>=16)pet+=2500-2500*p[i]/250;
					else if(x>=8)pet+=2000-2000*p[i]/250;
					else if(x>=4)pet+=1500-1500*p[i]/250;
					else if(x>=2)pet+=1000-1000*p[i]/250;
					else if(x>=1)pet+=500-500*p[i]/250;
				}
				else if(p[i]==-1)
				{
					int x=(n+akks)/(k[i]);
					if(x>=32)vas+=3000-3000*v[i]/250;
					else if(x>=16)vas+=2500-2500*v[i]/250;
					else if(x>=8)vas+=2000-2000*v[i]/250;
					else if(x>=4)vas+=1500-1500*v[i]/250;
					else if(x>=2)vas+=1000-1000*v[i]/250;
					else if(x>=1)vas+=500-500*v[i]/250;
				}
				else if(v[i]<p[i])
				{
					int x=(n+akks)/(k[i]);
					if(x>=32)pet+=3000-3000*p[i]/250;
					else if(x>=16)pet+=2500-2500*p[i]/250;
					else if(x>=8)pet+=2000-2000*p[i]/250;
					else if(x>=4)pet+=1500-1500*p[i]/250;
					else if(x>=2)pet+=1000-1000*p[i]/250;
					else if(x>=1)pet+=500-500*p[i]/250;
					if(x>=32)vas+=3000-3000*v[i]/250;
					else if(x>=16)vas+=2500-2500*v[i]/250;
					else if(x>=8)vas+=2000-2000*v[i]/250;
					else if(x>=4)vas+=1500-1500*v[i]/250;
					else if(x>=2)vas+=1000-1000*v[i]/250;
					else if(x>=1)vas+=500-500*v[i]/250;
				}
				else
				{
					int x=(n+akks)/(k[i]+akks);
					if(x>=32)pet+=3000-3000*p[i]/250;
					else if(x>=16)pet+=2500-2500*p[i]/250;
					else if(x>=8)pet+=2000-2000*p[i]/250;
					else if(x>=4)pet+=1500-1500*p[i]/250;
					else if(x>=2)pet+=1000-1000*p[i]/250;
					else if(x>=1)pet+=500-500*p[i]/250;
					if(x>=32)vas+=3000-3000*v[i]/250;
					else if(x>=16)vas+=2500-2500*v[i]/250;
					else if(x>=8)vas+=2000-2000*v[i]/250;
					else if(x>=4)vas+=1500-1500*v[i]/250;
					else if(x>=2)vas+=1000-1000*v[i]/250;
					else if(x>=1)vas+=500-500*v[i]/250;
				}
			}
			debug writeln(vas,' ',pet);
			if(vas>pet)
			{
				writeln(akks);
				continue loop;
			}
		}
		writeln(-1);
	}
}

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

enum M = 5;
enum K = 6;
enum LIM = 10^^6;

int calc(long p, long q) {
  foreach (k; 0 .. K - 1) {
    if (p > (q >> (k + 1))) {
      return k;
    }
  }
  return K - 1;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new int[][](N, M);
      foreach (i; 0 .. N) foreach (j; 0 .. M) {
        A[i][j] = readInt();
      }

      auto cnt = new int[M];
      foreach (i; 0 .. N) foreach (j; 0 .. M) {
        if (A[i][j] != -1) {
          ++cnt[j];
        }
      }

      foreach (n; 0 .. LIM) {
        int sum;
        foreach (j; 0 .. M) {
          int k;
          if (A[0][j] != -1 && A[1][j] != -1 && A[0][j] > A[1][j]) {
            k = calc(cnt[j] + n, N + n);
          } else {
            k = calc(cnt[j], N + n);
          }
          if (A[0][j] != -1) sum += 500 * (k + 1) - 2 * (k + 1) * A[0][j];
          if (A[1][j] != -1) sum -= 500 * (k + 1) - 2 * (k + 1) * A[1][j];
        }
        if (sum > 0) {
          writeln(n);
          goto found;
        }
      }
      writeln(-1);
     found:
    }
  } catch (EOFException e) {
  }
}


Mainak has two positive integers $$$n$$$ and $$$m$$$.Mainak finds a sequence $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers interesting, if for all integers $$$i$$$ ($$$1 \le i \le n$$$), the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$ is $$$0$$$. Formally if $$$p_i$$$ is the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$, then $$$a$$$ is an interesting sequence if $$$p_1 = p_2 = \ldots = p_n = 0$$$.For example, sequences $$$[1,3,2,3,1,2,3]$$$, $$$[4,4,4,4]$$$, $$$[25]$$$ are interesting, whereas $$$[1,2,3,4]$$$ ($$$p_2 = 1 \ne 0$$$), $$$[4,1,1,2,4]$$$ ($$$p_1 = 1 \oplus 1 \oplus 2 = 2 \ne 0$$$), $$$[29,30,30]$$$ ($$$p_2 = 29 \ne 0$$$) aren't interesting.Here $$$a \oplus b$$$ denotes bitwise XOR of integers $$$a$$$ and $$$b$$$.Find any interesting sequence $$$a_1, a_2, \ldots, a_n$$$ (or report that there exists no such sequence) such that the sum of the elements in the sequence $$$a$$$ is equal to $$$m$$$, i.e. $$$a_1 + a_2 \ldots + a_n = m$$$.As a reminder, the bitwise XOR of an empty sequence is considered to be $$$0$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line and the only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le m \le 10^9$$$) — the length of the sequence and the sum of the elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if there exists some interesting sequence, output "Yes" on the first line, otherwise output "No". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer). If the answer is "Yes", output $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i \ge 1$$$), forming an interesting sequence such that $$$a_1 + a_2 \ldots + a_n = m$$$. If there are multiple solutions, output any.

Note In the first test case, $$$[3]$$$ is the only interesting sequence of length $$$1$$$ having sum $$$3$$$. In the third test case, there is no sequence of length $$$2$$$ having sum of elements equal to $$$1$$$, so there is no such interesting sequence. In the fourth test case, $$$p_1 = p_2 = p_3 = 0$$$, because bitwise XOR of an empty sequence is $$$0$$$.

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

int [] solve (int n, int m)
{
	if (n > m)
	{
		return null;
	}

	auto a = new int [n];
	a[] = 1;
	m -= n;
	if (n % 2 == 1)
	{
		a.back += m;
	}
	else if (m % 2 == 0)
	{
		a[$ - 1] += m / 2;
		a[$ - 2] += m / 2;
	}
	else
	{
		return null;
	}
	return a;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto s = solve (n, m);
		if (s.empty)
		{
			writeln ("No");
		}
		else
		{
			writeln ("Yes");
			writefln !("%(%s %)") (s);
		}
	}
}


Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \le k_i$$$ for all $$$1 \le i \le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 < k_2 < \dots < k_n$$$ ($$$1 \le k_i \le 10^9$$$) — the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le k_i \le 10^9$$$) — the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.

For each testcase, print a single integer — the least amount of mana required for Monocarp to kill all monsters.

NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively.

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

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

alias P = Tuple!(long, "t", int, "i");

void solve() {
    int N = read!int;
    auto K = readarray!long;
    auto H = readarray!long;

    long ans = 0;
    auto PQ = heapify!"a.t == b.t ? a.i > b.i : a.t > b.t"(new P[0], 0);
    foreach (i; 0 .. N) {
        long ti = K[i] - H[i] + 1;
        PQ.insert(P(ti, i));
    }
    long ct = 0;
    long cp = 0;
    while (! PQ.empty) {
        auto p = PQ.front; PQ.removeFront;
        int i = p.i;
        if (ct < p.t) {
            ans += (1L + H[i]) * H[i] / 2L;
            cp = H[i];
            ct = K[i];
        } else {
            if (K[i] <= ct) continue;
            ans += (cp + 1L + cp + K[i] - ct) * (K[i] - ct) / 2L;
            cp = cp + K[i] - ct;
            ct = K[i];
        }
    }
    writeln(ans);
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto k = readln.splitter.map!(to!long).array;
    auto h = readln.splitter.map!(to!long).array;

    foreach_reverse (i ; 1 .. cast(int)n) {
      long delay = k[i] - k[i - 1];
      if (delay < h[i] - h[i - 1])
        h[i - 1] = h[i] - delay;
    }

    long ans;
    ans = h[0] * (1L + h[0]) / 2;
    long power = h[0];
    foreach (i ; 1 .. cast(int)n) {
      long delay = k[i] - k[i - 1];
      if (delay >= h[i]) {
        ans += h[i] * (1L + h[i]) / 2;
        power = h[i];
      } else {
        ans += delay * ((power + 1) + (power + delay)) / 2;
        power += delay;
      }
    }
    writeln(ans);
  }
}

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(ushort, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        readln();

        immutable times = readln.chomp
            .split(" ")
            .to!(uint[]);

        immutable hp = readln.chomp
            .split(" ")
            .to!(uint[]);

        alias Pair = Tuple!(uint, "start", uint, "end");

        auto stack = Array!Pair();

        foreach (health, time; lockstep(hp, times, StoppingPolicy.requireSameLength)) {
            immutable start = time - health + 1;
            immutable end = time;

            while (stack.length != 0 && stack.back().start >= start)
                stack.removeBack();

            if (stack.length == 0)
                stack ~= Pair(start, end);
            else {
                if (stack.back.end >= start)
                    stack.back.end = end;
                else
                    stack ~= Pair(start, end);
            }
        }

        stack
            .fold!((a, b) {
                    immutable ulong total_casts = b.end - b.start + 1;
                    return a + total_casts * (total_casts + 1) / 2;
            })(0uL)
            .writeln();
    }
}
// ""

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto T = scan!long(N);
      auto H = scan!long(N);

      long lastTime = T[$ - 1];
      long lastDamage;
      long ans;
      foreach_reverse(t, h; zip(T, H)) {
        long damage = max(0, lastDamage - (lastTime - t));
        if (damage >= h) continue;

        if (damage == 0) {
          ans += h * (h + 1) / 2;
          lastDamage = h;
          lastTime = t;
        } else {
          ans -= lastDamage * (lastDamage + 1) / 2;
          lastDamage += h - damage;
          ans += lastDamage * (lastDamage + 1) / 2;
        }
        // [t, h, ans].deb;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

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 k = readln.splitter.map !(to !(long)).array;
		auto h = readln.splitter.map !(to !(long)).array;

		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				h[i] = max (h[i], h[j] - k[j] + k[i]);
			}
		}
		long res = 0;
		long cur = 0;
		foreach (i; 0..n)
		{
			if (i > 0 && h[i] > k[i] - k[i - 1])
			{
				res += cur * 1L * (k[i] - k[i - 1]);
				res += (k[i] - k[i - 1]) *
				    (k[i] - k[i - 1] + 1L) / 2;
				cur += k[i] - k[i - 1];
			}
			else
			{
				res += h[i] * (h[i] + 1L) / 2;
				cur = h[i];
			}
		}
		writeln (res);
	}
}

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

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

alias P = Tuple!(long, "t", int, "i");

void solve() {
    int N = read!int;
    auto K = readarray!long;
    auto H = readarray!long;

    long ans = 0;
    auto PQ = heapify!"a.t == b.t ? a.i > b.i : a.t > b.t"(new P[0], 0);
    foreach (i; 0 .. N) {
        long ti = K[i] - H[i] + 1;
        PQ.insert(P(ti, i));
    }
    long ct = 0;
    long cp = 0;
    while (! PQ.empty) {
        auto p = PQ.front; PQ.removeFront;
        int i = p.i;
        if (ct < p.t) {
            ans += (1L + H[i]) * H[i] / 2L;
            ct = K[i];
            cp = H[i];
        } else {
            if (K[i] < ct) continue;
            ans += (cp + 1L + cp + K[i] - ct) * (K[i] - ct) / 2L;
            ct = K[i];
            cp = cp + K[i] - ct;
        }
    }
    writeln(ans);
}

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

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

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

alias P = Tuple!(long, "t", int, "i");

void solve() {
    int N = read!int;
    auto K = readarray!long;
    auto H = readarray!long;

    long ans = 0;
    auto PQ = heapify!"a.t == b.t ? a.i > b.i : a.t > b.t"(new P[0], 0);
    foreach (i; 0 .. N) {
        long ti = K[i] - H[i] + 1;
        PQ.insert(P(ti, i));
    }
    long ct = 0;
    long cp = 0;
    while (! PQ.empty) {
        auto p = PQ.front; PQ.removeFront;
        int i = p.i;
        if (ct < p.t) {
            ans += (1L + H[i]) * H[i] / 2L;
            ct = K[i];
            cp = H[i];
        } else {
            ans += (cp + 1L + cp + K[i] - ct) * (K[i] - ct) / 2L;
            ct = K[i];
            cp = cp + K[i] - ct;
        }
    }
    writeln(ans);
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto k = readln.splitter.map!(to!long).array;
    auto h = readln.splitter.map!(to!long).array;
    long ans;
    ans = h[0] * (1L + h[0]) / 2;
    long power = h[0];
    foreach (i ; 1 .. cast(int)n) {
      long delay = k[i] - k[i - 1];
      if (delay >= h[i]) {
        ans += h[i] * (1L + h[i]) / 2;
        power = h[i];
      } else {
        ans += delay * ((power + 1) + (power + delay)) / 2;
        power += delay;
      }
    }
    writeln(ans);
  }
}

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(ushort, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        readln();

        immutable times = readln.chomp
            .split(" ")
            .to!(uint[]);

        immutable hp = readln.chomp
            .split(" ")
            .to!(uint[]);

        alias Pair = Tuple!(uint, "start", uint, "end");

        auto stack = Array!Pair();

        foreach (health, time; lockstep(hp, times, StoppingPolicy.requireSameLength)) {
            immutable start = time - health + 1;
            immutable end = time;

            while (stack.length != 0 && stack.back().start >= start)
                stack.removeBack();

            if (stack.length == 0)
                stack ~= Pair(start, end);
            else {
                if (stack.back.end >= start)
                    stack.back.end = end;
                else
                    stack ~= Pair(start, end);
            }
        }

        stack
            .fold!((a, b) {
                    immutable total_casts = b.end - b.start + 1;
                    return a + total_casts * (total_casts + 1) / 2;
            })(0)
            .writeln();
    }
}
// ""

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto T = scan!long(N);
      auto H = scan!long(N);

      long lastTime = T[$ - 1];
      long lastDamage;
      long ans;
      foreach_reverse(t, h; zip(T, H)) {
        long damage = max(0, lastDamage - (lastTime - t));
        if (damage >= h) continue;

        if (damage == 0) {
          ans += h * (h + 1) / 2;
          lastDamage = h;
        } else {
          ans -= lastDamage * (lastDamage + 1) / 2;
          lastDamage += h - damage;
          ans += lastDamage * (lastDamage + 1) / 2;
        }

        lastTime = t;
        // [t, h, ans].deb;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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


The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., an of n these beavers. Beavershave 5000 needs one session to shave beavers with ids from x to y (inclusive) if and only if there are such indices i1 < i2 < ... < ik, that ai1 = x, ai2 = x + 1, ..., aik - 1 = y - 1, aik = y. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1, 2, 3, ..., n.If we can't shave beavers from x to y in one session, then we can split these beavers into groups [x, p1], [p1 + 1, p2], ..., [pm + 1, y] (x ≤ p1 < p2 < ... < pm < y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs m + 1 working sessions to shave beavers from x to y.All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types:   what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive?  two beavers on positions x and y (the beavers ax and ay) swapped. You can assume that any beaver can be shaved any number of times.

The first line contains integer n — the total number of beavers, 2 ≤ n. The second line contains n space-separated integers — the initial beaver permutation. The third line contains integer q — the number of queries, 1 ≤ q ≤ 105. The next q lines contain the queries. Each query i looks as pi xi yi, where pi is the query type (1 is to shave beavers from xi to yi, inclusive, 2 is to swap beavers on positions xi and yi). All queries meet the condition: 1 ≤ xi < yi ≤ n.   to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem B1);  to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems B1+B2).  Note that the number of queries q is limited 1 ≤ q ≤ 105 in both subproblem B1 and subproblem B2.

For each query with pi = 1, print the minimum number of Beavershave 5000 sessions.

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;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = array (iota (n + 2));
		auto b = array (iota (n + 2));
		foreach (i; 1..n + 1)
		{
			readf (" %s", &a[i]);
			b[a[i]] = i;
		}

		auto f = new int [n + 2];

		void add (int p, int v)
		{
			for ( ; p <= n + 1; p += (p & -p))
			{
				debug {writeln ("add ", p, " ", v);}
				f[p] += v;
			}
		}

		int sum (int p)
		{
			int res = 0;
			for ( ; p > 0; p -= (p & -p))
			{
				debug {writeln ("sum ", p);}
				res += f[p];
			}
			return res;
		}

		void mark (int p, int v)
		{
			if (b[p] > b[p + 1])
			{
				add (p, v);
			}
		}

		f[] = 0;
		foreach (i; 1..n + 1)
		{
			mark (i, +1);
		}

		int q;
		readf (" %s", &q);
		foreach (z; 0..q)
		{
			debug {writeln ("a = ", a);}
			debug {writeln ("b = ", b);}
			debug {writeln ("f = ", f);}
			int t, x, y;
			readf (" %s %s %s", &t, &x, &y);
			if (t == 1)
			{
				writeln (sum (y - 1) - sum (x - 1) + 1);
			}
			else if (t == 2)
			{
				swap (a[x], a[y]);
				x = a[x];
				y = a[y];
				if (x > y)
				{
					swap (x, y);
				}
				mark (x - 1, -1);
				mark (x - 0, -1);
				if (y - 1 != x - 0)
				{
					mark (y - 1, -1);
				}
				mark (y - 0, -1);
				swap (b[x], b[y]);
				mark (x - 1, +1);
				mark (x - 0, +1);
				if (y - 1 != x - 0)
				{
					mark (y - 1, +1);
				}
				mark (y - 0, +1);
			}
			else
			{
				assert (false);
			}
		}
		debug {writeln ("!");}
	}
}