Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$. Each of its vertices also has an integer $$$a_i$$$ written on it. For each vertex $$$i$$$, Evlampiy calculated $$$c_i$$$ — the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. Illustration for the second example, the first integer is $$$a_i$$$ and the integer in parentheses is $$$c_i$$$After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $$$c_i$$$, but he completely forgot which integers $$$a_i$$$ were written on the vertices.Help him to restore initial integers!

The first line contains an integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$ — the number of vertices in the tree. The next $$$n$$$ lines contain descriptions of vertices: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), where $$$p_i$$$ is the parent of vertex $$$i$$$ or $$$0$$$ if vertex $$$i$$$ is root, and $$$c_i$$$ is the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. It is guaranteed that the values of $$$p_i$$$ describe a rooted tree with $$$n$$$ vertices.

If a solution exists, in the first line print "YES", and in the second line output $$$n$$$ integers $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $$$a_i$$$ are between $$$1$$$ and $$$10^9$$$. If there are no solutions, print "NO".

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


The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows:   If the current skill immediately follows another skill of a different type, then its damage is doubled.  In other words,   If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage;  If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the number of skills.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the maximum damage the hero can deal.

NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \times 1 + 2 \times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \times 6 + 2 \times 4 + 2 \times 7 + 2 \times 5 + 2 \times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$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)); }

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


You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.

The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.

In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence.  Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.

NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.

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

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


The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$.  That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis.  The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The next $$$2 \cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers $$$h$$$, $$$m$$$ ($$$1 \le h, m \le 100$$$). The second line contains the start time $$$s$$$ in the described format HH:MM.

For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.

NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.

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


Sonya was unable to think of a story for this problem, so here comes the formal description.You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.

The first line of the input contains a single integer n (1 ≤ n ≤ 3000) — the length of the array. Next line contains n integer ai (1 ≤ ai ≤ 109).

Print the minimum number of operation required to make the array strictly increasing.

NoteIn the first sample, the array is going to look as follows:2 3 5 6 7 9 11|2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9And for the second sample:1 2 3 4 5|5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12

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

immutable long INF = long.max / 8;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		foreach (i; 0..n)
		{
			a[i] -= i;
		}
		a = (a.reduce !(min) - 1) ~ a ~ (a.reduce !(max) + 1);
		debug {writeln ("a = ", a);}
		n += 2;

		auto r = n.iota.map !(i => tuple (a[i], i)).array;
		sort (r);
		debug {writeln (r);}

		auto f = new long [n];
		f[] = 0;
		foreach (pos; 1..n)
		{
			foreach (mid; 0..n)
			{
				f[mid] += abs (a[pos] - a[mid]);
			}
			debug {writeln (f);}
			int lo = 0;
			while (true)
			{
				int hi = lo + 1;
				long cur = f[r[lo][1]];
				while (hi < n && r[hi][0] == r[hi - 1][0])
				{
					cur = min (cur, f[r[hi][1]]);
					hi += 1;
				}
				foreach (me; lo..hi)
				{
					f[r[me][1]] = cur;
				}
				if (hi >= n)
				{
					break;
				}
				f[r[hi][1]] = min (f[r[hi][1]], cur);
				lo = hi;
			}
		}
		writeln (f[$ - 1]);
	}
}


Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold:   there is no actor in the cell the spotlight is placed to;  there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan. The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.

Print one integer — the number of good positions for placing the spotlight.

NoteIn the first example the following positions are good:  the (1, 1) cell and right direction;  the (1, 1) cell and down direction;  the (1, 3) cell and left direction;  the (1, 3) cell and down direction;  the (1, 4) cell and left direction;  the (2, 2) cell and left direction;  the (2, 2) cell and up direction;  the (2, 2) and right direction;  the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example.

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int n, m;
bool[1000][1000][2] a;

inout(bool)[ ][3] findTrue(inout(bool)[ ] a) {
    int i = 0, j = cast(int)a.length;
    while (i < a.length && !a[i])
        i++;
    while (j > i && !a[j - 1])
        j--;
    return [a[0 .. i], a[i .. j], a[j .. $]];
}

void main() {
    while (read(&n, &m)) {
        foreach (i, ref row; a[0][0 .. n])
            foreach (j, ref elem; row[0 .. m]) {
                char c;
                read(&c);
                elem = a[1][j][i] = c == '1';
            }
        int result = 0;
        foreach (ref row; a[0][0 .. n]) {
            auto t = findTrue(row[0 .. m]);
            if (!t[1].empty) {
                result += t[0].count(false);
                result += t[1].count(false) << 1;
                result += t[2].count(false);
            }
        }
        foreach (ref row; a[1][0 .. m]) {
            auto t = findTrue(row[0 .. n]);
            if (!t[1].empty) {
                result += t[0].count(false);
                result += t[1].count(false) << 1;
                result += t[2].count(false);
            }
        }
        writeln(result);
    }
}

import std.stdio;
import std.bigint;
import std.container;
import std.array;
import std.algorithm;
import std.conv;
import std.bitmanip;
import std.functional;
import std.math;
import std.numeric;
import std.string;
import std.range;
import std.uni;
import std.complex;
import std.typecons;
import core.stdc.stdio:freopen;
import core.bitop;
import std.regex;
import std.complex;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
immutable int mod=1000000007;
pure nothrow @safe X binpow(X,Y)(X base,Y exp)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @safe auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@safe @property void putarr(X)(X a,in char ch=' ')
{
	foreach(const ref i;a)write(i,ch);
}
@safe @property void putarr(X)(X[][] a)
{
	foreach(i;0..a.length)
	{
		foreach(j;0..a[i].length)write(a[i][j],' ');
		writeln;
	}
}
void getarr(X)(X a,in int n)
{
	foreach(ref i;a[0..n])input(&i);
}
auto arread(T)()
{
	return readln.split.map!(to!(T)).array;
}
bool input(T...)(T ptrs) if (ptrs.length > 0) {
	return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;
}
struct pair(X,Y)
{
	X fi;
	Y se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	int opCmp(ref const pair!(X,Y) s_) const pure nothrow
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(X x_,Y y_) pure nothrow
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_;
}
X cub(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_*a_;
}
alias pair!(int,int) pii;
alias pair!(long,long) pll;
void inf(in char* name) nothrow @nogc @system
{
	freopen(name,"r",core.stdc.stdio.stdin);
}
void ouf(in char* name) nothrow @nogc @system
{
	freopen(name,"w",core.stdc.stdio.stdout);
}
//split strip readln equalRange upperBound lowerBound string wstring
//dstring ulong wchar dchar array uint foreach_reverse find count false
//nextPermutation isSorted fill reverse swap size_t clear empty insert
//front back remove hypot sqrt round continue swapRanges minPos maxPos
//break goto switch boyerMooreFinder minElement maxElement heapify true
//static multiSort schwartzSort partialSort merge uniq joiner filter
//cumulativeFold fold each sort isAlpha isNumber isWhite isLower isUpper
//toLower toUpper mixin
int[1000][1000] t,a,b;
void main()
{
	int n,m;
	input(&n,&m);
	foreach(i;0..n) foreach(j;0..m){input(&t[i][j]);a[i][j]=b[i][j]=t[i][j];}

	foreach(i;0..n)
	{
		foreach(j;1..m)a[i][j]+=a[i][j-1];
	}
	foreach(i;0..m)
	{
		foreach(j;1..n)b[j][i]+=b[j-1][i];
	}
	int ans=0;
	for(int i=0;i<n;i++)for(int j=0;j<m;j++)
	{
		if(t[i][j]==0)
		{
			if(a[i][j]>0)ans++;
			if(b[i][j]>0)ans++;
			if(a[i][j]<a[i][m-1])ans++;
			if(b[i][j]<b[n-1][j])ans++;
		}

	}
	writeln(ans);
}


You are given an unweighted tree with $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices $$$a, b, c$$$ on this tree such that the number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$ is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.

The first line contains one integer number $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree.  Next $$$n - 1$$$ lines describe the edges of the tree in form $$$a_i, b_i$$$ ($$$1 \le a_i$$$, $$$b_i \le n$$$, $$$a_i \ne b_i$$$). It is guaranteed that given graph is a tree.

In the first line print one integer $$$res$$$ — the maximum number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$. In the second line print three integers $$$a, b, c$$$ such that $$$1 \le a, b, c \le n$$$ and $$$a \ne, b \ne c, a \ne c$$$. If there are several answers, you can print any.

NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices $$$1, 5, 6$$$ then the path between $$$1$$$ and $$$5$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 5)$$$, the path between $$$1$$$ and $$$6$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 6)$$$ and the path between $$$5$$$ and $$$6$$$ consists of edges $$$(4, 5), (4, 6)$$$. The union of these paths is $$$(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$$$ so the answer is $$$5$$$. It can be shown that there is no better answer.

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

immutable int NA = -1;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto a = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		alias Depth = Tuple !(int, q{depth}, int, q{num});
		auto d = new Depth [n];

		alias Record =
		    Tuple !(int, q{depth}, int, q{next}, int, q{num});
		auto c = new Record [] [n];

		void recur1 (int v, int p)
		{
			auto res = Depth (0, v);
			foreach (u; a[v]) if (u != p)
			{
				recur1 (u, v);
				res = max (res,
				    Depth (d[u].depth + 1, d[u].num));
				c[v] ~= Record (d[u].depth + 1, u, d[u].num);
			}
			d[v] = res;
			sort !(q{a > b}) (c[v]);
			c[v] ~= Record (0, NA, NA);
			c[v] ~= Record (0, NA, NA);
			c[v] ~= Record (0, NA, NA);
		}

		recur1 (0, NA);

		int x = NA;
		int y = NA;
		int z = NA;
		int answer = 0;

		void recur2 (int v, int p, Record h)
		{
			int cur = h.depth + c[v][0].depth + c[v][1].depth;
			if (answer < cur)
			{
				answer = cur;
				x = h.num;
				y = c[v][0].num;
				z = c[v][1].num;
			}

			int alt = c[v][0].depth + c[v][1].depth + c[v][2].depth;
			if (answer < alt)
			{
				answer = alt;
				x = c[v][0].num;
				y = c[v][1].num;
				z = c[v][2].num;
			}

			foreach (u; a[v]) if (u != p)
			{
				int i = 0;
				if (c[v][i].next == u)
				{
					i += 1;
				}
				auto t = max (h, c[v][i]);
				t.depth += 1;
				recur2 (u, v, t);
			}
		}

		recur2 (0, NA, Record (0, 0, 0));

		if (x > y) swap (x, y);
		if (y > z) swap (y, z);
		if (x > y) swap (x, y);

		while (y == NA || y == x || y == z)
		{
			y += 1;
		}

		while (x == NA || x == y || x == z)
		{
			x += 1;
		}

		writeln (answer);
		writeln (x + 1, " ", y + 1, " ", z + 1);
	}
}

import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.algorithm.searching;

string[] tokens;
string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

const int N = 200000;

int n;
Array!int[N] tree;

int[] bfs(int s)
{
    int[] dist = new int[n];
    fill(dist, -1);
    dist[s] = 0;
    int[] queue = new int[n];
    int rear = 0;
    queue[rear++] = s;
    for (int head = 0; head < rear; ++head)
    {
        int u = queue[head];
        foreach (v; tree[u])
        {
            if (dist[v] == -1)
            {
                dist[v] = dist[u] + 1;
                queue[rear++] = v;
            }
        }
    }
    return dist;
}

int argmax(int[] dist)
{
    return cast(int) dist.enumerate.maxElement!"a.value"[0];
}

auto solve()
{
    int x = argmax(bfs(0));
    int[] dx = bfs(x);
    int y = argmax(dx);
    int diameter = dx[y];
    int[] dy = bfs(y);
    if (diameter == n - 1)
    {
        int z = 0;
        while (z == x || z == y)
        {
            z++;
        }
        return tuple(n - 1, x, y, z);
    }
    int z = n.iota.maxElement!((z) => dx[z] + dy[z]);
    return tuple(dx[z] + dy[z] + diameter >> 1, x, y, z);
}

void main()
{
    n = readInt;
    for (int i = 0; i < n - 1; ++i)
    {
        int a = readInt - 1;
        int b = readInt - 1;
        tree[a].insert(b);
        tree[b].insert(a);
    }
    auto res = solve();
    writeln(res[0]);
    writeln(res[1] + 1, " ", res[2] + 1, " ", res[3] + 1);
}

import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.algorithm.searching;

string[] tokens;
string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

const int N = 200000;

int n;
Array!int[N] tree;

int[] bfs(int s)
{
    int[] dist = new int[n];
    fill(dist, -1);
    dist[s] = 0;
    int[] queue = new int[n];
    int rear = 0;
    queue[rear++] = s;
    for (int head = 0; head < rear; ++head)
    {
        int u = queue[head];
        foreach (v; tree[u])
        {
            if (dist[v] == -1)
            {
                dist[v] = dist[u] + 1;
                queue[rear++] = v;
            }
        }
    }
    return dist;
}

int argmax(int[] dist)
{
    return cast(int) dist.enumerate.maxElement!"a.value"[0];
}

auto solve()
{
    int x = argmax(bfs(0));
    int[] dx = bfs(x);
    int y = argmax(dx);
    int diameter = dx[y];
    int[] dy = bfs(y);
    if (diameter == n - 1)
    {
        int z = 0;
        while (z == x || z == y)
        {
            z++;
        }
        return tuple(n - 1, x, y, z);
    }
    int z = n.iota.maxElement!((z) => dx[z] + dy[z]);
    return tuple(dx[z] + dy[z] - diameter, x, y, z);
}

void main()
{
    n = readInt;
    for (int i = 0; i < n - 1; ++i)
    {
        int a = readInt - 1;
        int b = readInt - 1;
        tree[a].insert(b);
        tree[b].insert(a);
    }
    auto res = solve();
    writeln(res[0]);
    writeln(res[1] + 1, " ", res[2] + 1, " ", res[3] + 1);
}


This is an interactive problem.Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a $$$n \times n$$$ grid. The snake has a head and a tail in different cells, and its body is a series of adjacent cells connecting the head and the tail without self-intersecting. If Serval hits its head or tail, the snake will bite him and he will die.Luckily, he has a special device which can answer the following question: you can pick a rectangle, it will tell you the number of times one needs to cross the border of the rectangle walking cell by cell along the snake from the head to the tail. The pictures below show a possible snake and a possible query to it, which will get an answer of $$$4$$$.    Today Serval got up too late and only have time to make $$$2019$$$ queries. As his best friend, can you help him find the positions of the head and the tail?Note that two cells are adjacent if and only if they have a common edge in the grid, and a snake can have a body of length $$$0$$$, that means it only has adjacent head and tail.Also note that the snake is sleeping, so it won't move while Serval using his device. And what's obvious is that the snake position does not depend on your queries.

The first line contains a single integer $$$n$$$ ($$$2\leq n \leq 1000$$$) — the size of the grid.

When you are ready to answer, you should print ! x1 y1 x2 y2, where $$$(x_1, y_1)$$$ represents the position of the head and $$$(x_2,y_2)$$$ represents the position of the tail. You can print head and tail in any order.

Note        The pictures above show our queries and the answers in the first example. We first made a query for $$$(1,1)$$$ and got an answer $$$1$$$, then found that it must be connected to exactly one other cell. Then we made a query for $$$(1,2)$$$ and got an answer of $$$0$$$, then knew that the snake never entered it. So the cell connected to $$$(1,1)$$$ must be $$$(2,1)$$$. Then we made a query for $$$(2,2)$$$ and got an answer $$$0$$$, then knew that it never entered $$$(2,2)$$$ as well. So the snake cannot leave $$$(2,1)$$$, which implies that the answer is $$$(1,1)$$$ and $$$(2,1)$$$.      The pictures above show our queries and the answers in the second example. By making query to $$$(2,2)$$$ and receiving $$$2$$$, we found that the snake occupies $$$(2,2)$$$. And by making query to rectangle from $$$(2,1)$$$ to $$$(2,3)$$$ and receiving answer $$$0$$$, we knew that it never goes out of the rectangle from $$$(2,1)$$$ to $$$(2,3)$$$. Since the first answer is $$$2$$$, both $$$(2,1)$$$ and $$$(2,3)$$$ must be occupied but none of others, so the answer is $$$(2,1)$$$ and $$$(2,3)$$$.

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

const long mod = 1_000_000_007;

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;

	int i1, i2;
	int fi = 0;
	foreach(i; 1 .. n + 1){
		if(ask(i, 1, i, n) % 2 > 0){
			fi += 1;
			if(fi == 1) i1 = i;
			else if(fi == 2){
				i2 = i;
				break;
			}
		}
	}

	int j1, j2;
	int fj = 0;
	foreach(j; 1 .. n + 1){
		if(ask(1, j, n, j) % 2 > 0){
			fj += 1;
			if(fj == 1) j1 = j;
			else if(fj == 2){
				j2 = j;
				break;
			}
		}
	}

	if(fi == 2 && fj == 2){
		if(ask(i1, j1, i1, j1) % 2 > 0){
			answer(i1, j1, i2, j2);
			return;
		}
		else{
			answer(i1, j2, i2, j1);
			return;
		}
	}
	else if(fi == 2){
		int j = 1 + uplimit(1, n, (int j) => (ask(1, 1, i1, j) % 2 == 0));
		answer(i1, j, i2, j);
		return;
	}
	else{ // fj == 2
		int i = 1 + uplimit(1, n, (int i) => (ask(1, 1, i, j1) % 2 == 0));
		answer(i, j1, i, j2);
		return;
	}
}

/*

An area that contains head or tail will return odd number.

First, ask (1, 1, n, j) for all j.
This turns odd when j passes the head (or tail),
and then it turns even again when j passes the tail (or head).

Similarly ask (1, 1, i, n) for all i.

If such i and j are found, the answer will be one of
(i1, j1, i2, j2) or (i1, j2, i2, j1).
To determine which of these, ask (i1, j1, i1, j1).

If it happen that i1 = i2 or j1 = j2, we cannot find it,
but i1 = i2 and j1 = j2 do not happen at the same time;
if j1 = j2, ask (1, 1, i1, j) in binary lsearch of j to find j1 = j2.

*/
int ask(int x1, int y1, int x2, int y2){
	("? " ~ [x1, y1, x2, y2].map!(to!string).array.join(" ")).writeln;
	stdout.flush;
	return read.to!int;
}
void answer(int x1, int y1, int x2, int y2){
	("! " ~ [x1, y1, x2, y2].map!(to!string).array.join(" ")).writeln;
}

T uplimit(T)(T a, T c, bool delegate(T) f){
	if(f(c)) return c; if(! f(a)) return a - 1;
	while(a + 1 < c){ T b = (a + c) / 2; if(f(b)) a = b; else c = b; }
	return a;
}


Dreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from $$$1$$$ to $$$54$$$ after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in $$$n$$$ Codeforces rounds. His place in the first round is $$$a_1$$$, his place in the second round is $$$a_2$$$, ..., his place in the $$$n$$$-th round is $$$a_n$$$.You are given a positive non-zero integer $$$x$$$.Please, find the largest $$$v$$$ such that this person can collect all the places from $$$1$$$ to $$$v$$$ after $$$x$$$ more rated contests.In other words, you need to find the largest $$$v$$$, such that it is possible, that after $$$x$$$ more rated contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.For example, if $$$n=6$$$, $$$x=2$$$ and $$$a=[3,1,1,5,7,10]$$$ then answer is $$$v=5$$$, because if on the next two contest he will take places $$$2$$$ and $$$4$$$, then he will collect all places from $$$1$$$ to $$$5$$$, so it is possible to get $$$v=5$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains two integers $$$n, x$$$ ($$$1 \leq n, x \leq 100$$$). The second line contains $$$n$$$ positive non-zero integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$).

For each test case print one line containing the largest $$$v$$$, such that it is possible that after $$$x$$$ other contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.

NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place $$$1,2,\ldots,99$$$ and place $$$101$$$ on them in some order, to collect places $$$1,2,\ldots,101$$$.

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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto a = RDA;
		a.sort();
		int cnt;
		foreach (e; a)
		{
			if (e < cnt+1) continue;
			while (cnt+1 < e)
			{
				if (x == 0) break;
				--x;
				++cnt;
			}
			if (cnt+1 == e)
				++cnt;
		}
		ans[ti] = cnt + x;
	}

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


Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.Vasya has a train lighting schedule for all n hours of the trip — n numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose k hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.

The first input line contains two integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n) — the number of hours on the train and the number of hours to read, correspondingly. The second line contains n space-separated integers ai (0 ≤ ai ≤ 100), ai is the light level at the i-th hour.

In the first output line print the minimum light level Vasya will read at. In the second line print k distinct space-separated integers b1, b2, ..., bk, — the indexes of hours Vasya will read at (1 ≤ bi ≤ n). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers bi in an arbitrary order.

NoteIn the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20.

import std.stdio : File, readln, writeln, chomp;
import std.string : split;
import std.conv : to;
import std.array : sort;
import std.algorithm : minCount;

const int INF = 1<<28;

int n,k;
int[] list;

int[] ans;
int value = INF;
void solve()
{
	int[] _list = list.dup;
	_list.sort;
	int count = 0;
	foreach_reverse(v; _list){
		foreach(i, ref ite; list){
			if(ite==v){
				ans ~= i+1;
				ite = -1;
				if(v<value){
					value = v;
				}
				if(k<=++count){
					return;
				}
			}
		}
	}
}

void io()
{
	auto input = File("input.txt", "r");
	auto output = File("output.txt", "w");
	char[][] str = input.readln().dup.split();
	n = str[0].to!int;
	k = str[1].to!int;
	str = input.readln().dup.split();
	foreach(ite; str){
		list ~= ite.to!int;
	}

	solve();

	output.writeln = value;
	for(int i=0; i<ans.length; ++i){
		output.write(ans[i]);
		if(i+1<ans.length){
			output.write(' ');
		}
	}
	output.write('\n');
}
void main()
{
	io();
}

import std.stdio : File, readln, writeln, chomp;
import std.string : split;
import std.conv : to;
import std.array : sort;
import std.algorithm : minCount;

int n,k;
int[] list;

int[] ans;
void solve()
{
	int[] _list = list.dup;
	_list.sort;
	int count = 0;
	foreach_reverse(v; _list){
		foreach(i, ref ite; list){
			if(ite==v){
				ans ~= i+1;
				ite = -1;
				if(k<=++count){
					return;
				}
			}
		}
	}
}

void io()
{
	auto input = File("input.txt", "r");
	auto output = File("output.txt", "w");
	char[][] str = input.readln().dup.split();
	n = str[0].to!int;
	k = str[1].to!int;
	str = input.readln().dup.split();
	foreach(ite; str){
		list ~= ite.to!int;
	}

	solve();

	output.writeln = ans.minCount[0];
	for(int i=0; i<ans.length; ++i){
		output.write(ans[i]);
		if(i+1<ans.length){
			output.write(' ');
		}
	}
	output.write('\n');
}
void main()
{
	io();
}


Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: "Is the unknown number divisible by number y?".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.

A single line contains number n (1 ≤ n ≤ 103).

Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions yi (1 ≤ yi ≤ n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.

NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter.

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

void solve(int n)
{
    if (n == 1)
    {
        writeln(0);
        return;
    }
    auto f = new bool[n + 1];
    fill(f, false);
    int[] s;
    foreach (i; 2 .. n + 1)
    {
        if (!f[i])
        {
            for (int j = i; j <= n; j *= i)
            {
                s ~= j;
            }
            for (int j = i * i; j <= n; j += i)
            {
                f[j] = true;
            }
        }
    }
    writeln(s.length);
    foreach (i; 0 .. s.length - 1)
    {
        write(s[i], " ");
    }
    writeln(s[s.length - 1]);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        solve(n);
    }
    return 0;
}

import std.algorithm;
import std.conv;
import std.numeric;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [] a;
		auto b = new bool [n + 1];
		b[] = true;
		for (int i = 2; i <= n; i++) if (b[i])
		{
			for (int j = i; j <= n; j *= i)
			{
				a ~= j;
			}
			for (int j = i * i; j <= n; j += i)
			{
				b[j] = false;
			}
		}
		writeln (a.length);
		writefln ("%(%s %)", a);
	}
}


When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.

The first line contains two integers n and t (1 ≤ n ≤ 105; 1 ≤ t ≤ 109) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.

Print a single integer — the maximum number of books Valera can read.

module cf_279B;

import std.stdio;

void main() {
    int n, t;
    int[] times;

    readf("%d %d", &n, &t);
    times = new int[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d", &times[i]);
        if (i > 0) {
            times[i] += times[i - 1];
        }
    }

    int start = 0, finish = 0;
    while (finish < n && times[finish] <= t) {
        ++finish;
    }

    int readBooks = finish;
    while (finish <= n) {
        while (start < finish && times[finish - 1] - times[start] > t) {
            ++start;
        }

        int cur = finish - start - 1;
        if (cur > readBooks) {
            readBooks = cur;
        }

        ++finish;
    }

    writeln(readBooks);
}


You are given a non-empty string $$$s=s_1s_2\dots s_n$$$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string $$$s$$$ if there is an integer $$$j$$$ ($$$1 \le j \le n-2$$$), that $$$s_{j}s_{j+1}s_{j+2}=$$$"one" or $$$s_{j}s_{j+1}s_{j+2}=$$$"two".For example:  Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"),  Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two"). Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.For example, if the string looks like $$$s=$$$"onetwone", then if Polycarp selects two indices $$$3$$$ and $$$6$$$, then "onetwone" will be selected and the result is "ontwne".What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Next, the test cases are given. Each test case consists of one non-empty string $$$s$$$. Its length does not exceed $$$1.5\cdot10^5$$$. The string $$$s$$$ consists only of lowercase Latin letters. It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed $$$1.5\cdot10^6$$$.

Print an answer for each test case in the input in order of their appearance. The first line of each answer should contain $$$r$$$ ($$$0 \le r \le |s|$$$) — the required minimum number of positions to be removed, where $$$|s|$$$ is the length of the given line. The second line of each answer should contain $$$r$$$ different integers — the indices themselves for removal in any order. Indices are numbered from left to right from $$$1$$$ to the length of the string. If $$$r=0$$$, then the second line can be skipped (or you can print empty). If there are several answers, print any of them.

10
onetwonetwooneooonetwooo
two
one
twooooo
ttttwo
ttwwoo
ooone
onnne
oneeeee
oneeeeeeetwooooo

NoteIn the first example, answers are:  "onetwone",  "testme" — Polycarp likes it, there is nothing to remove,  "oneoneone",  "twotwo". In the second example, answers are:   "onetwonetwooneooonetwooo",  "two",  "one",  "twooooo",  "ttttwo",  "ttwwoo" — Polycarp likes it, there is nothing to remove,  "ooone",  "onnne" — Polycarp likes it, there is nothing to remove,  "oneeeee",  "oneeeeeeetwooooo".

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new size_t[][](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;
		if (s.length < 3) continue;
		foreach (i; 2..s.length)
		{
			if (s[i-2..i+1] == "one")
			{
				if (i >= 4)
				{
					if (s[i-4..i+1] == "twone")
					{
						++ans[ti][$-1];
						continue;
					}
				}
				ans[ti] ~= i;
			}
			else if (s[i-2..i+1] == "two")
			{
				ans[ti] ~= i;
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
		{
			writeln(0);
			writeln;
		}
		else
		{
			writeln(e.length);
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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 S = readToken();
        const N = cast(int)(S.length);

        auto s = S.dup;

        int[] anss;
        foreach (i; 0 .. N - 5 + 1) {
          if (s[i .. i + 5] == "twone") {
            anss ~= i + 2;
            s[i + 2] = '!';
          }
        }
        debug {
          writeln("s = ", s);
        }
        foreach (i; 0 .. N - 3 + 1) {
          if (s[i .. i + 3] == "one" || s[i .. i + 3] == "two") {
            anss ~= i + 1;
          }
        }

        writeln(anss.length);
        int ou;
        foreach (i; anss) {
          if (ou++) write(" ");
          write(i + 1);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}