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 int inf = 10^^9 + 7;

void main() {
    int n, k;
    readVars(n, k);
    auto x = readln.split.map!(to!long).array;

    auto cs = new long[](n + 1);
    iota(n).each!(i => cs[i + 1] += cs[i] + x[i]);

    auto pfm = new long[](n + 1);
    auto sfm = new long[](n + 1);
    auto pfi = new int[](n + 1);
    auto sfi = new int[](n + 1);

    foreach (i ; k .. n + 1) {
        pfm[i] = pfm[i - 1];
        pfi[i] = pfi[i - 1];

        if (cs[i] - cs[i - k] > pfm[i - 1]) {
            pfm[i] = cs[i] - cs[i - k];
            pfi[i] = i - k;
        }
    }

    foreach_reverse (i ; 0 .. n - k + 1) {
        sfm[i] = sfm[i + 1];
        sfi[i] = sfi[i + 1];

        if (cs[i + k] - cs[i] >= sfm[i + 1]) {
            sfm[i] = cs[i + k] - cs[i];
            sfi[i] = i;
        }
    }

    debug {
        stderr.writeln("pfm:",pfm);
        stderr.writeln("pfi:",pfi);
        stderr.writeln("sfm:",sfm);
        stderr.writeln("sfi:",sfi);
    }

    long max_v;
    int a, b;

    foreach (i ; k .. n - k + 1) {
        if (pfm[i] + sfm[i] > max_v) {
            max_v = pfm[i] + sfm[i];
            a = pfi[i];
            b = sfi[i];
        }
    }

    writeln(a + 1, " ", b + 1);
}

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){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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 int inf = 10^^9 + 7;

void main() {
    int n, k;
    readVars(n, k);
    auto x = readln.split.map!(to!long).array;

    auto cs = new long[](n + 1);
    iota(n).each!(i => cs[i + 1] += cs[i] + x[i]);

    auto pfm = new long[](n + 1);
    auto sfm = new long[](n + 1);
    auto pfi = new int[](n + 1);
    auto sfi = new int[](n + 1);

    foreach (i ; k .. n + 1) {
        pfm[i] = pfm[i - 1];
        pfi[i] = pfi[i - 1];

        if (cs[i] - cs[i - k] > pfm[i - 1]) {
            pfm[i] = cs[i] - cs[i - k];
            pfi[i] = i - k;
        }
    }

    foreach_reverse (i ; 0 .. n - k + 1) {
        sfm[i] = sfm[i + 1];
        sfi[i] = sfi[i + 1];

        if (cs[i + k] - cs[i] >= sfm[i + 1]) {
            sfm[i] = cs[i + k] - cs[i];
            sfi[i] = i;
        }
    }

    debug {
        //stderr.writeln("pfm:",pfm);
        stderr.writeln("pfi:",pfi);
        stderr.writeln("sfm:",sfm);
        stderr.writeln("sfi:",sfi);
    }

    long max_v;
    int a, b;

    foreach (i ; k .. n - k + 1) {
        if (pfm[i] + sfm[i] > max_v) {
            max_v = pfm[i] + sfm[i];
            a = pfi[i];
            b = sfi[i];
        }
    }

    writeln(a + 1, " ", b + 1);
}

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){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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 int inf = 10^^9 + 7;

void main() {
    int n, k;
    readVars(n, k);
    auto x = readln.split.map!(to!long).array;

    auto cs = new long[](n + 1);
    iota(n).each!(i => cs[i + 1] += cs[i] + x[i]);

    int a = 0, b = k;
    long maxsum = cs[k] - cs[0] + cs[2*k] - cs[k];
    long maxpf = cs[k] - cs[0];
    int maxpfi = 0;

    foreach (i ; k + 1 .. n - k + 1) {
        if (cs[i] - cs[i - k] > maxpf) {
            maxpf = cs[i] - cs[i - k];
            maxpfi = i - k;
        }

        if (maxpf + cs[i + k] - cs[i] > maxsum) {
            maxsum = maxpf + cs[i + k] - cs[i];
            a = maxpfi;
            b = i;
        }
    }

    writeln(a + 1, " ", b + 1);
}

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){
        writeln(line);
        throw new Exception("args num < input num");
    }
}


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.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);
	writeln(m[a/2]);
	return 0;
}


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

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

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


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


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

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;

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();
    }
}
// ""

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

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


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 ("!");}
	}
}


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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new int[N];
      auto C = new int[N];
      foreach (u; 0 .. N) {
        P[u] = readInt() - 1;
        C[u] = readInt();
      }

      auto desc = new bool[][](N, N);
      foreach (u; 0 .. N) {
        for (int v = u; v != -1; v = P[v]) {
          desc[v][u] = true;
        }
      }
      auto sz = new int[N];
      foreach (u; 0 .. N) {
        sz[u] = desc[u].count(true);
      }
      auto us = iota(N).array;
      us.sort!((u, v) => (sz[u] < sz[v]));

      bool ok = true;
      foreach (u; 0 .. N) {
        ok = ok && (C[u] < sz[u]);
      }
      if (ok) {
        int num;
        auto ans = new int[N];
        foreach (u; us) {
          int[] xs;
          foreach (v; 0 .. N) {
            if (u != v && desc[u][v]) {
              xs ~= ans[v];
            }
          }
          xs.sort;
          xs ~= ++num;
          foreach (v; 0 .. N) {
            if (u != v && desc[u][v]) {
              int pos = xs.lowerBound(ans[v]);
              if (pos >= C[u]) {
                ++pos;
              }
              ans[v] = xs[pos];
            }
          }
          ans[u] = xs[C[u]];
        }
        writeln("YES");
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(ans[u]);
        }
        writeln();

        debug {
          foreach (u; 0 .. N) {
            int cnt;
            foreach (v; 0 .. N) {
              if (u != v && desc[u][v]) {
                if (ans[u] > ans[v]) {
                  ++cnt;
                }
              }
            }
            assert(C[u] == cnt);
          }
        }
      } else {
        writeln("NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto adj = new int [] [n + 1];
		auto p = new int [n + 1];
		auto c = new int [n + 1];
		foreach (i; 1..n + 1)
		{
			readf !(" %s %s") (p[i], c[i]);
			adj[p[i]] ~= i;
		}

		auto a = new int [n + 1];
		auto s = new int [] [n + 1];

		bool recur (int v)
		{
			foreach (u; adj[v])
			{
				if (!recur (u))
				{
					return false;
				}
				foreach (w; s[u])
				{
					a[w] += s[v].length.to !(int);
				}
				s[v] ~= s[u];
			}

			if (c[v] > s[v].length)
			{
				return false;
			}
			a[v] = c[v];
			foreach (w; s[v])
			{
				if (a[w] >= c[v])
				{
					a[w] += 1;
				}
			}
			s[v] ~= v;
			debug {writeln (v, " ", a);}
			return true;
		}

		if (!recur (0))
		{
			writeln ("NO");
		}
		else
		{
			writeln ("YES");
			writefln !("%(%s %)") (a[1..n + 1]);
		}
	}
}

import std.algorithm, std.conv, std.range, std.stdio, std.string;
void main () {
	auto n = readln.strip.to!int, g = new int [] [n + 1],
	    s = g.map !(x => x.dup).array,
	    p = new int [n + 1], a = p.dup, r = 1;
	foreach (i; 1..n + 1) {
		readf !" %s %s" (p[i], a[i]);
		g[p[i]] ~= i;
	}

	void recur (int v) {
		foreach (u; g[v]) {
			recur (u);
			foreach (w; s[u])
				a[w] += s[v].length.to !(int);
			s[v] ~= s[u];
		}

		r &= (a[v] <= s[v].length);
		foreach (w; s[v])
			a[w] += (a[w] >= a[v]);
		s[v] ~= v;
	}

	recur (0);
	if (r) {
		writeln ("YES");
		writefln !("%(%s %)") (a[1..n + 1]);
	}
	else
		writeln ("NO");
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

void main()
{
  int n;
  read(n);
  auto p = new int[n.ind + 1];
  auto children = new int[][n.ind + 1];
  auto c = new int[n.ind + 1];
  int root = -1;
  foreach(i; 1 .. n + 1)
    {
      read(p[i], c[i]);
      if (p[i])
        children[p[i]] ~= i;
      else
        root = i;
    }
  auto subsize = new int[n.ind + 1];
  class Impossible: Throwable
  {
    this()
    {
      super("");
    }
  }
  auto solution = new int[][n.ind + 1];
  void dfs(int node)
  {
    mixin(logCall);
    subsize[node.ind] = 1;
    solution[n.ind] = null;
    auto childSol = new int[0];
    foreach(child; children[node.ind])
      {
        dfs(child);
        subsize[node.ind] += subsize[child.ind];
        childSol ~= solution[child.ind];
      }
    assert(childSol.length == subsize[node.ind] - 1);
    if (c[node.ind] > subsize[node.ind] - 1)
      throw new Impossible();
    int value = 0;
    solution[node.ind] = childSol[0 .. c[node.ind].ind] ~ [node] ~ childSol[c[node.ind].ind .. $];
  }
  auto pos = new int[n.ind + 1];
  try dfs(root);
  catch(Impossible impossibl)
    goto no;
 yes:
  writeln("YES");
  foreach(i; 0 .. solution[root.ind].length)
    pos[solution[root.ind][i]] = cast(int)i + 1;
  foreach(pi; pos[1 .. $])
    write(pi, " ");
  writeln;
  return;
 no:
  writeln("NO");
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  immutable n = r.next!uint ();
  auto p = new int[n+1];
  auto c = new int[n+1];
  int root;
  auto e = new int[][n+1];
  foreach (i; 1 .. n + 1) {
    p[i] = r.next!uint ();
    c[i] = r.next!uint ();
    if (p[i] == 0) root = i;
    else {
      e[p[i]] ~= i;
    }
  }
  auto ss = new int[n+1];
  auto vis = new bool[n+1];
  void go (int i) {
    ss[i] = 1;
    foreach (j; e[i]) if (!vis[j]) {
      vis[j] = true;
      go (j);
      ss[i] += ss[j];
    }
  }
  vis[root] = true;
  go (root);
  foreach (i; 1 .. n + 1) {
    if (ss[i] - 1 < c[i]) {
      writeln ("NO");
      return;
    }
  }
  auto idx = iota (1, n.to!int + 1).array;
  auto a = new int[n+1];
  void go2 (int i, int l) {
    int k = c[i];
    int j = l;
    debug stderr.writeln (idx);
    debug stderr.writefln ("k = %d", k);
    while (idx[j] < 0) ++j;
    while (--k >= 0) {
      ++j;
      while (idx[j] < 0) ++j;
    }
    a[i] = idx[j];
    debug stderr.writefln ("i = %d, j = %d, a[i] = %d, idx[j] = %d", i, j, a[i], idx[j]);
    assert (a[i] >= 0);
    idx[j] = -1;
    foreach (u; e[i]) {
      go2 (u, 0);
    }
  }
  go2 (root, 0);
  writeln ("YES");
  writefln ("%(%s %)", a[1 .. $]);
}

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 n = rint;
	Node[] nodes;
	Node root;
	foreach(i; 0 .. n) nodes ~= new Node(i);

	foreach(i; 0 .. n){
		int p = rint - 1;
		long c = rlong;
		if(p >= 0){
			nodes[i].parent = nodes[p];
			nodes[p].sons ~= nodes[i];
			nodes[p].waitcount += 1;
		}
		else{
			nodes[i].parent = null;
			root = nodes[i];
		}
		nodes[i].value = c;
	}

	auto ndq = new Queue!Node;
	foreach(nd; nodes) ndq.enq(nd);
	while(ndq.length){
		Node nd = ndq.deq;
		if(nd.waitcount == 0){
			if(nd.value == 0) nd.nodes ~= nd;
			foreach(son; nd.sons) foreach(q; son.nodes){
				nd.nodes ~= q;
				if(nd.value == nd.nodes.length) nd.nodes ~= nd;
			}
			if(nd.value > nd.nodes.length){
				"NO".writeln;
				return;
			}
			if(nd.parent) nd.parent.waitcount -= 1;
		}
		else ndq.enq(nd);
	}

	"YES".writeln;
	foreach(i, nd; root.nodes){ nd.ans = i + 1; }
	nodes.map!(nd => nd.ans.to!string).join(" ").writeln;

}
class Node{
	int id;
	Node parent;
	long value;
	int waitcount;
	long ans;
	Node[] nodes;
	Node[] sons;
	this(int id){
		this.id = id;
	}
}
// ----- キュー -----
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}
// ----- スタック -----
class Stack(T){
	private T[] xs;
	private uint j; // j : 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(){ return new Stack!T; }
	static Stack!T opCall(T[] xs){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}


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

long solve (int [] a, int [] b)
{
	long res = 0;
	while (!a.empty && !b.empty)
	{
		res += a.back * 2;
		a.popBack ();
		swap (a, b);
	}
	return res + sum (a, 0L) + sum (b, 0L);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		auto u = n.iota.filter !(i => a[i] == 0)
		    .map !(i => b[i]).array;
		auto v = n.iota.filter !(i => a[i] == 1)
		    .map !(i => b[i]).array;
		sort (u);
		sort (v);
		writeln (max (solve (u, v), solve (v, u)));
	}
}

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

        long[][2] bss;
        foreach (i; 0 .. N) {
          bss[A[i]] ~= B[i];
        }
        foreach (h; 0 .. 2) {
          bss[h].sort;
        }

        long ans;
        foreach (h0; 0 .. 2) {
          int[2] poss;
          foreach (h; 0 .. 2) {
            poss[h] = cast(int)(bss[h].length);
          }
          long score;
          int lastA;
          long lastB;
          for (; poss[0] > 0 || poss[1] > 0; ) {
            foreach (h; [h0, h0 ^ 1]) if (poss[h] > 0) {
              score += ((h != lastA) ? 2 : 1) * lastB;
              lastA = h;
              lastB = bss[h][--poss[h]];
            }
          }
          score += lastB;
          debug {
            writeln(h0, ": ", score);
          }
          chmax(ans, score);
        }

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

      auto as = A.dup;
      as.sort;
      auto uf = new int[N];
      uf[] = -1;
      foreach (u; 0 .. N) {
        const v = as.lowerBound(A[u]);
        uf.connect(u, v);
      }

      auto uss = new int[][N];
      foreach (u; 0 .. N) {
        uss[uf.root(u)] ~= u;
      }
      writeln(uf.count!"a < 0");
      foreach (r; 0 .. N) {
        if (uss[r]) {
          write(uss[r].length);
          foreach (u; uss[r]) {
            write(" ", u + 1);
          }
          writeln;
        }
      }
    }
  } catch (EOFException e) {
  }
}

module main;
__gshared:
import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
enum mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt gcd(BigInt a, BigInt b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///integer size
		int sz(T)(T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///posicion lower bound
		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;
		}
		///posicion upper bound
		size_t upb(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 (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		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;
		}
		///binary search
		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;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(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;
	}
	///readln without format
	bool read(T...)(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;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//freopen("output.txt", "w", core.stdc.stdio.stdout);
		/*StopWatch sw;
		sw.start;
		scope (exit)
		{
			sw.stop;
			stderr.writefln("\nTime: %d ms", sw.peek.msecs);
		}*/
	}
	int n;
	loop: while (read(n))
	{
		auto a = arread!int;
		auto b = a.dup;
		sort(b);
		auto r = a.map!(x => mp(x, binf(b, x))).array;
		auto u = new bool[n];
		size_t[][] ans;
		foreach (i; 0 .. n)
		{
			if (u[i])
				continue;
			ans.length++;
			size_t p = i;
			while (!u[p])
			{
				u[p] = 1;
				ans.back ~= p + 1;
				p = r[p].se;
			}
		}
		writeln(ans.length);
		foreach (p; ans)
		{
			write(p.length);
			foreach (x; p)
			{
				write(' ', x);
			}
			writeln;
		}
	}
}

/+ dub.sdl:
    name "A"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;
// import dcomp.datastructure.unionfind;

int main() {
    auto sc = new Scanner(stdin);
    int n; int[] a;
    sc.read(n, a);
    int[] idx = iota(n).array;
    idx.sort!((x, y) => a[x] < a[y]);
    auto uf = UnionFind(n);
    foreach (i, j; idx) {
        uf.merge(i.to!int, j);
    }
    writeln(uf.count);
    foreach (v; uf.groups) {
        if (v.length == 0) continue;
        writeln(v.length, " ", v.map!(x => (x+1).to!string).join(" "));
    }
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    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);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    import core.bitop : bsf, bsr, popcnt;
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

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 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;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        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 {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(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);
        }
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/datastructure/unionfind.d */
// module dcomp.datastructure.unionfind;

struct UnionFind {
    import std.algorithm : map, swap, each;
    import std.range : iota, array;
    int[] id;
    int[][] groups;
    int count;

    this(int n) {
        id = iota(n).array;
        groups = iota(n).map!(a => [a]).array;
        count = n;
    }

    void merge(int a, int b) {
        if (same(a, b)) return;
        count--;
        int x = id[a], y = id[b];
        if (groups[x].length < groups[y].length) swap(x, y);
        groups[y].each!(a => id[a] = x);
        groups[x] ~= groups[y];
        groups[y] = [];
    }

    int[] group(int i) {
        return groups[id[i]];
    }

    bool same(int a, int b) {
        return id[a] == id[b];
    }
}

module solution;
import std.algorithm;
import std.array;
import std.conv;
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)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = n.iota.array;
		makeIndex (a, b);
		auto d = new bool [n];
		int [] [] ans;
		foreach (i; 0..n)
		{
			if (!d[i])
			{
				int [] line;
				int j = i;
				do
				{
					j = b[j];
					d[j] = true;
					line ~= j + 1;
				}
				while (j != i);
				ans ~= line;
			}
		}
		writeln (ans.length);
		foreach (line; ans)
		{
			writefln ("%s %(%s %)", line.length, line);
		}
	}
}

module solution;
import std.algorithm;
import std.array;
import std.conv;
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)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = n.iota.array;
		makeIndex (a, b);
		writeln (b);
		auto d = new bool [n];
		int [] [] ans;
		foreach (i; 0..n)
		{
			if (!d[i])
			{
				int [] line;
				int j = i;
				do
				{
					j = b[j];
					d[j] = true;
					line ~= j + 1;
				}
				while (j != i);
				ans ~= line;
			}
		}
		writeln (ans.length);
		foreach (line; ans)
		{
			writefln ("%s %(%s %)", line.length, line);
		}
	}
}


module main;
import std.stdio, std.conv, std.string, std.ascii, std.algorithm, std.format;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    auto result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

char mirror_char(char c)
{
    switch (c)
    {
    case '0':
        return '0';
    case '1':
        return '1';
    case '2':
        return '5';
    case '5':
        return '2';
    case '8':
        return '8';
    default:
        return '\0';
    }
}

char[5] mirror_time(char[5] str)
in(str[2] == ':')
{
    return [
        mirror_char(str[4]), mirror_char(str[3]), ':', mirror_char(str[1]),
        mirror_char(str[0])
    ];
}

bool is_valid_hour(const char[] str, int h)
in(str.length == 2)
in(h >= 1 && h <= 100)
{
    if (!str.all!isDigit)
        return false;
    int value = str.to!int;
    return value < h;
}

alias is_valid_minute = is_valid_hour;

bool is_valid_time(char[5] str, int h, int m)
{
    return is_valid_hour(str[0 .. 2], h) && is_valid_minute(str[3 .. 5], m);
}

char[5] next_time_str(char[5] str, int h, int m)
in(is_valid_time(str, h, m))
{
    assert(str.length == 5);
    auto hour = str[0 .. 2].to!int;
    auto minute = str[3 .. 5].to!int;
    ++minute;
    if (minute >= m)
    {
        minute = 0;
        ++hour;
    }
    if (hour >= h)
        hour = 0;
    char[5] result;
    sformat!"%02d:%02d"(result, hour, minute);
    assert(is_valid_time(result, h, m));
    return result;
}

void solve_case()
{
    auto h = read!int, m = read!int;
    char[5] time_str = read!string;
    assert(is_valid_time(time_str, h, m));
    while (!is_valid_time(mirror_time(time_str), h, m))
    {
        time_str = next_time_str(time_str, h, m);
    }
    writeln(time_str);
}

void main()
{
    auto T = read!int;
    foreach (case_index; 0 .. T)
        solve_case();
}

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 string[](t);
	auto safe = [1, 1, 1, 0, 0, 1, 0, 0, 1, 0];
	foreach (ti; 0..t)
	{
		auto h = RD!int;
		auto m = RD!int;
		auto s = RD!string;

		auto tokens = s.split(":");
		int hh, mm;
		void f (ref int x, string s)
		{
			foreach (i; 0..2)
				x += 10^^(1-i) * (s[i]-'0');
		}
		f(hh, tokens[0]);
		f(mm, tokens[1]);

		while (true)
		{
			auto hh_s = hh.to!string;
			auto mm_s = mm.to!string;
			while (hh_s.length < 2)
				hh_s = '0' ~ hh_s;
			while (mm_s.length < 2)
				mm_s = '0' ~ mm_s;
			bool ok = true;
			foreach (c; hh_s ~ mm_s)
			{
				if (safe[c-'0'] == 0)
					ok = false;
			}
			if (ok)
			{
				string hh_s2, mm_s2;
				foreach_reverse (c; hh_s)
				{
					if (c == '2')
						mm_s2 ~= '5';
					else if (c == '5')
						mm_s2 ~= '2';
					else
						mm_s2 ~= c;
				}
				foreach_reverse (c; mm_s)
				{
					if (c == '2')
						hh_s2 ~= '5';
					else if (c == '5')
						hh_s2 ~= '2';
					else
						hh_s2 ~= c;
				}
				int hh2, mm2;
				f(hh2, hh_s2);
				f(mm2, mm_s2);
				if (hh2 >= h || mm2 >= m)
					ok = false;
			}
			if (ok)
			{
				ans[ti] = hh_s ~ ":" ~ mm_s;
				break;
			}
			++mm;
			if (mm == m)
			{
				mm = 0;
				++hh;
				if (hh == h)
					hh = 0;
			}
		}
	}

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

module main;
import core.exception;
import std.stdio, std.conv, std.string, std.ascii, std.format;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    immutable result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

struct Time
{
    immutable int hc = 1, mc = 1;
    int h = 0, m = 0;

    invariant(h >= 0 && h < hc);
    invariant(m >= 0 && m < mc);

    this(int h, int m, int hc, int mc) inout
    in(hc >= 1 && hc <= 100)
    in(mc >= 1 && mc <= 100)
    {
        this.h = h;
        this.m = m;
        this.hc = hc;
        this.mc = mc;
    }

    this(char[5] str, int hc, int mc) inout
    in(str[2] == ':')
    {
        this(str[0 .. 2].to!int, str[3 .. 5].to!int, hc, mc);
    }

    string toString() const
    {
        return format!"%02d:%02d"(h, m);
    }

    ref Time opUnary(string op)() if (op == "++")
    {
        ++m;
        if (m >= mc)
        {
            m = 0;
            ++h;
            if (h >= hc)
                h = 0;
        }
        return this;
    }

    bool is_mirrored_valid() const
    {
        char mirror_char(char c)
        in(c.isDigit)
        {
            switch (c)
            {
            case '0':
                return '0';
            case '1':
                return '1';
            case '2':
                return '5';
            case '5':
                return '2';
            case '8':
                return '8';
            default:
                return 0;
            }
        }

        int mirror(int n)
        in(n >= 0 && n < 100)
        {
            immutable a = mirror_char(cast(char)('0' + n % 10));
            immutable b = mirror_char(cast(char)('0' + n / 10));
            if (!a || !b)
                return int.max;
            return [a, b].to!int;
        }

        return mirror(m) < hc && mirror(h) < mc;
    }
}

void solve_case()
{
    immutable h = read!int, m = read!int;
    immutable char[5] time_str = read!string;
    auto time = Time(time_str, h, m);
    while (!time.is_mirrored_valid)
        ++time;
    writeln(time);
}

void main()
{
    immutable T = read!int;
    foreach (case_index; 0 .. T)
        solve_case();
}

module main;
import core.exception;
import std.stdio, std.conv, std.string, std.ascii, std.format;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    immutable result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

struct Time
{
    immutable int hc = 1, mc = 1;
    int h = 0, m = 0;

    invariant(h >= 0 && h < hc);
    invariant(m >= 0 && m < mc);

    this(int h, int m, int hc, int mc) inout
    in(hc >= 1 && hc <= 100)
    in(mc >= 1 && mc <= 100)
    {
        this.h = h;
        this.m = m;
        this.hc = hc;
        this.mc = mc;
    }

    this(char[5] str, int hc, int mc) inout
    in(str[2] == ':')
    {
        this(str[0 .. 2].to!int, str[3 .. 5].to!int, hc, mc);
    }

    string toString() const
    {
        return format!"%02d:%02d"(h, m);
    }

    ref Time opUnary(string op)() if (op == "++")
    {
        ++m;
        if (m >= mc)
        {
            m = 0;
            ++h;
            if (h >= hc)
                h = 0;
        }
        return this;
    }

    bool is_mirrored_valid() const
    {
        char mirror_char(char c)
        in(c.isDigit)
        {
            final switch (c)
            {
            case '0':
                return '0';
            case '1':
                return '1';
            case '2':
                return '5';
            case '5':
                return '2';
            case '8':
                return '8';
            }
        }

        int mirror(int n)
        in(n >= 0 && n < 100)
        {
            immutable a = cast(char)('0' + n / 10);
            immutable b = cast(char)('0' + n % 10);
            return [mirror_char(b), mirror_char(a)].to!int;
        }

        try
        {
            return mirror(m) < hc && mirror(h) < mc;
        }
        catch (Throwable ex)
        {
            return false;
        }
    }
}

void solve_case()
{
    immutable h = read!int, m = read!int;
    immutable char[5] time_str = read!string;
    auto time = Time(time_str, h, m);
    while (!time.is_mirrored_valid)
        ++time;
    writeln(time);
}

void main()
{
    immutable T = read!int;
    foreach (case_index; 0 .. T)
        solve_case();
}

module main;
import core.exception;
import std.stdio, std.conv, std.string, std.ascii, std.format;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    immutable result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

struct Time
{
    immutable int hc = 1, mc = 1;
    int h = 0, m = 0;

    invariant(h >= 0 && h < hc);
    invariant(m >= 0 && m < mc);

    this(int h, int m, int hc, int mc) inout
    in(hc >= 1 && hc <= 100)
    in(mc >= 1 && mc <= 100)
    {
        this.h = h;
        this.m = m;
        this.hc = hc;
        this.mc = mc;
    }

    this(char[5] str, int hc, int mc) inout
    in(str[2] == ':')
    {
        this(str[0 .. 2].to!int, str[3 .. 5].to!int, hc, mc);
    }

    string toString() const
    {
        return format!"%02d:%02d"(h, m);
    }

    ref Time opUnary(string op)() if (op == "++")
    {
        ++m;
        if (m >= mc)
        {
            m = 0;
            ++h;
            if (h >= hc)
                h = 0;
        }
        return this;
    }

    bool is_mirrored_valid() const
    {
        char mirror_char(char c)
        in(c.isDigit)
        {
            switch (c)
            {
            case '0':
                return '0';
            case '1':
                return '1';
            case '2':
                return '5';
            case '5':
                return '2';
            case '8':
                return '8';
            default:
                return 0;
            }
        }

        int mirror(int n)
        in(n >= 0 && n < 100)
        {
            immutable a = mirror_char(cast(char)('0' + n / 10));
            immutable b = mirror_char(cast(char)('0' + n % 10));
            if (!a || !b)
                return int.max;
            return [a, b].to!int;
        }

        return mirror(m) < hc && mirror(h) < mc;
    }
}

void solve_case()
{
    immutable h = read!int, m = read!int;
    immutable char[5] time_str = read!string;
    auto time = Time(time_str, h, m);
    while (!time.is_mirrored_valid)
        ++time;
    writeln(time);
}

void main()
{
    immutable T = read!int;
    foreach (case_index; 0 .. T)
        solve_case();
}

module main;
import core.exception;
import std.stdio, std.conv, std.string, std.ascii, std.format;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    immutable result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

struct Time
{
    immutable int hc = 1, mc = 1;
    int h = 0, m = 0;

    invariant(h >= 0 && h < hc);
    invariant(m >= 0 && m < mc);

    this(int h, int m, int hc, int mc) inout
    in(hc >= 1 && hc <= 100)
    in(mc >= 1 && mc <= 100)
    {
        this.h = h;
        this.m = m;
        this.hc = hc;
        this.mc = mc;
    }

    this(char[5] str, int hc, int mc) inout
    in(str[2] == ':')
    {
        this(str[0 .. 2].to!int, str[3 .. 5].to!int, hc, mc);
    }

    string toString() const
    {
        return format!"%02d:%02d"(h, m);
    }

    ref Time opUnary(string op)() if (op == "++")
    {
        ++m;
        if (m >= mc)
        {
            m = 0;
            ++h;
            if (h >= hc)
                h = 0;
        }
        return this;
    }

    bool is_mirrored_valid() const
    {
        char mirror_char(char c)
        in(c.isDigit)
        {
            final switch (c)
            {
            case '0':
                return '0';
            case '1':
                return '1';
            case '2':
                return '5';
            case '5':
                return '2';
            case '8':
                return '8';
            }
        }

        int mirror(int n)
        in(n >= 0 && n < 100)
        {
            immutable a = cast(char)('0' + n / 10);
            immutable b = cast(char)('0' + n % 10);
            return [mirror_char(b), mirror_char(a)].to!int;
        }

        try
        {
            return mirror(m) < hc && mirror(h) < mc;
        }
        catch (Throwable ex)
        {
            writeln(ex);
            return false;
        }
    }
}

void solve_case()
{
    immutable h = read!int, m = read!int;
    immutable char[5] time_str = read!string;
    auto time = Time(time_str, h, m);
    while (!time.is_mirrored_valid)
        ++time;
    writeln(time);
}

void main()
{
    immutable T = read!int;
    foreach (case_index; 0 .. T)
        solve_case();
}

module main;
import std.stdio, std.conv, std.string, std.ascii, std.algorithm, std.format;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    auto result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

char mirror_char(char c)
{
    switch (c)
    {
    case '0':
        return '0';
    case '1':
        return '1';
    case '2':
        return '5';
    case '5':
        return '2';
    case '6':
        return '9';
    case '8':
        return '8';
    case '9':
        return '6';
    default:
        return '\0';
    }
}

char[5] mirror_time(char[5] str)
in(str[2] == ':')
{
    return [
        mirror_char(str[4]), mirror_char(str[3]), ':', mirror_char(str[1]),
        mirror_char(str[0])
    ];
}

bool is_valid_hour(const char[] str, int h)
in(str.length == 2)
in(h >= 1 && h <= 100)
{
    if (!str.all!isDigit)
        return false;
    int value = str.to!int;
    return value < h;
}

alias is_valid_minute = is_valid_hour;

bool is_valid_time(char[5] str, int h, int m)
{
    return is_valid_hour(str[0 .. 2], h) && is_valid_minute(str[3 .. 5], m);
}

char[5] next_time_str(char[5] str, int h, int m)
in(is_valid_time(str, h, m))
{
    assert(str.length == 5);
    auto hour = str[0 .. 2].to!int;
    auto minute = str[3 .. 5].to!int;
    ++minute;
    if (minute >= m)
    {
        minute = 0;
        ++hour;
    }
    if (hour >= h)
        hour = 0;
    char[5] result;
    sformat!"%02d:%02d"(result, hour, minute);
    assert(is_valid_time(result, h, m));
    return result;
}

void solve_case()
{
    auto h = read!int, m = read!int;
    char[5] time_str = read!string;
    assert(is_valid_time(time_str, h, m));
    while (!is_valid_time(mirror_time(time_str), h, m))
    {
        time_str = next_time_str(time_str, h, m);
    }
    writeln(time_str);
}

void main()
{
    auto T = read!int;
    foreach (case_index; 0 .. T)
        solve_case();
}