You are given a rooted tree consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, and the root is the vertex $$$1$$$. You are also given a score array $$$s_1, s_2, \ldots, s_n$$$.A multiset of $$$k$$$ simple paths is called valid if the following two conditions are both true.   Each path starts from $$$1$$$.  Let $$$c_i$$$ be the number of paths covering vertex $$$i$$$. For each pair of vertices $$$(u,v)$$$ ($$$2\le u,v\le n$$$) that have the same parent, $$$|c_u-c_v|\le 1$$$ holds.  The value of the path multiset is defined as $$$\sum\limits_{i=1}^n c_i s_i$$$.It can be shown that it is always possible to find at least one valid multiset. Find the maximum value among all valid multisets.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two space-separated integers $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the size of the tree and the required number of paths. The second line contains $$$n - 1$$$ space-separated integers $$$p_2,p_3,\ldots,p_n$$$ ($$$1\le p_i\le n$$$), where $$$p_i$$$ is the parent of the $$$i$$$-th vertex. It is guaranteed that this value describe a valid tree with root $$$1$$$. The third line contains $$$n$$$ space-separated integers $$$s_1,s_2,\ldots,s_n$$$ ($$$0 \le s_i \le 10^4$$$) — the scores of the vertices. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.

For each test case, print a single integer — the maximum value of a path multiset.

NoteIn the first test case, one of optimal solutions is four paths $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 4$$$, $$$1 \to 4$$$, here $$$c=[4,2,2,2,2]$$$. The value equals to $$$4\cdot 6+ 2\cdot 2+2\cdot 1+2\cdot 5+2\cdot 7=54$$$.In the second test case, one of optimal solution is three paths $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 2 \to 3 \to 5$$$, $$$1 \to 4$$$, here $$$c=[3,2,2,1,2]$$$. The value equals to $$$3\cdot 6+ 2\cdot 6+2\cdot 1+1\cdot 4+2\cdot 10=56$$$.

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

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

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

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto P = readarray!int;
    foreach (ref p; P) p--;
    auto G = new int[][N];
    for (int i = 1; i < N; i++) {
        int p = P[i-1];
        G[p] ~= i;
    }
    auto C = readarray!long;

    long[Tuple!(int,int)] cache;
    long f(int v, int m) {
        if (G[v].empty) {
            return C[v] * m;
        } else {
            long r = C[v] * m;
            auto key = tuple(v, m);
            if (key in cache) return cache[key];
            int a = m / (G[v].length);
            int rem = m - a * G[v].length;
            auto xs = G[v].map!(u => f(u, a)).array;
            long sx = xs.reduce!"a+b";
            if (rem > 0) {
                auto ys = G[v].map!(u => f(u, a+1)).array;
                auto ds = iota(G[v].length).array.map!(i => ys[i] - xs[i]).array.sort!"a > b".array;
                long add = 0;
                for (int j = 0; j < rem; j++) {
                    add += ds[j];
                }
                r += sx + add;
                return cache[key] = r;
            } else {
                r += sx;
                return cache[key] = r;
            }
        }
    }
    writeln(f(0, K));
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto p = [0] ~ readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto s = readln.splitter.map !(to !(int)).array;

		auto adj = new int [] [n];
		auto d = new int [n];
		foreach (i; 1..n)
		{
			adj[p[i]] ~= i;
			d[p[i]] += 1;
		}

		alias Pair = Tuple !(int, q{v}, int, q{num});
		long [Pair] mem;

		long recur (int v, int num)
		{
			auto coord = Pair (v, num);
			if (coord !in mem)
			{
				long res = s[v] * 1L * num;
				if (d[v] > 0)
				{
					int lo = num / d[v];
					int hi = (num + d[v] - 1) / d[v];
					long [] vLo;
					long [] vHi;
					foreach (u; adj[v])
					{
						vLo ~= recur (u, lo);
						vHi ~= recur (u, hi);
						res += vLo.back;
					}
					auto p = d[v].iota.array;
					p.schwartzSort !(i => vHi[i] - vLo[i],
					    q{a > b}, SwapStrategy.stable);
					int rem = num % d[v];
					foreach (i; p[0..rem])
					{
						res += (vHi[i] - vLo[i]);
					}
				}
				mem[coord] = res;
			}
			return mem[coord];
		}

		writeln (recur (0, k));
	}
}

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 N;
long K;
int[] P;
long[] S;

int[][] graph;

int[] lens;
long[3][] kss, fss;
long solve(int u, long k) {
  foreach (j; 0 .. lens[u]) {
    if (kss[u][j] == k) {
      return fss[u][j];
    }
  }

  long ret = S[u] * k;
  const deg = cast(int)(graph[u].length);
  if (deg) {
    const q = k / deg;
    const r = k % deg;
    auto ds = new long[deg];
    foreach (j; 0 .. deg) {
      const v = graph[u][j];
      const res0 = solve(v, q);
      ret += res0;
      if (r) {
        const res1 = solve(v, q + 1);
        ds[j] = res1 - res0;
      }
    }
    ds.sort;
    ret += ds[deg - cast(int)(r) .. deg].sum;
  }

  assert(lens[u] < 3);
  kss[u][lens[u]] = k;
  fss[u][lens[u]] = ret;
  ++lens[u];
  return ret;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        K = readLong;
        P = new int[N];
        P[0] = -1;
        foreach (u; 1 .. N) {
          P[u] = readInt - 1;
        }
        S = new long[N];
        foreach (u; 0 .. N) {
          S[u] = readLong;
        }

        graph = new int[][N];
        foreach (u; 1 .. N) {
          graph[P[u]] ~= u;
        }

        lens = new int[N];
        kss = new long[3][N];
        fss = new long[3][N];
        const ans = solve(0, K);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


DZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

The first line contains two space-separated integers n and m . Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order.

Print a single integer — the maximum possible danger.

NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    bool[][] G = new bool[][](N + 1, N + 1);
    foreach (ref L; G) L[] = false;
    foreach (i; 0 .. M) {
        int x, y; scanf("%d %d\n", &x, &y);
        G[x][y] = G[y][x] = true;
    }

    // 連結グラフの個数
    int Count() {
        int Ret = 0;
        bool[] used = new bool[N + 1];

        void dfs(int x) {
            used[x] = true;
            for (int i = 1; i <= N; i++) {
                if (!used[i] && G[x][i]) {
                    dfs(i);
                }
            }
        }

        for (int i = 1; i <= N; i++) {
            if (!used[i]) {
                dfs(i);
                Ret++;
            }
        }
        return Ret;
    }

    writeln( 1L << (N - Count()) );
}

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

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

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

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

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

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

int N, M;
int[] A, B;

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

		int[] uf = new int[N];
		uf[] = -1;
		foreach (i; 0 .. M) {
			uf.conn(A[i], B[i]);
		}

		long ans = 1;
		foreach (u; 0 .. N) {
			if (!(uf[u] < 0)) {
				ans *= 2;
			}
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    bool[][] G = new bool[][](N + 1, N + 1);
    foreach (ref L; G) L[] = false;
    foreach (i; 0 .. M) {
        int x, y; scanf("%d %d\n", &x, &y);
        G[x][y] = G[y][x] = true;
    }

    // 連結グラフの個数
    int Count() {
        int Ret = 0;
        bool[] used = new bool[N + 1];

        void dfs(int x) {
            used[x] = true;
            for (int i = 1; i <= N; i++) {
                if (!used[i]) {
                    dfs(i);
                }
            }
        }

        for (int i = 1; i <= N; i++) {
            if (!used[i]) {
                dfs(i);
                Ret++;
            }
        }
        return Ret;
    }

    writeln( 1L << (N - Count()) );
}

import std.stdio;

void main()
{
    int ctl;
    readf("%s",&ctl);
    if(ctl == -1){
      run_tests();
    } else{
      run_instance(ctl);
    }

}

// void debug(T...)(T args){
//
// }
// int DEBUG = false;
//
// void debug(){
//   if(DEBUG){
//
//   }
// }

void run_instance(int ctl){
    int n = ctl;
    int m; readf(" %s\n",&m);
    auto graph = new G(n);

    for(int i = 0; i < m; i++){
        int s; readf("%s ",&s);
        int d; readf("%s ",&d);
        graph.add_vertex(s,d);
    }

    int r = calculate(n,m,graph);
    writefln("%s",r);
}

int calculate(int n, int m, G graph){
  int c = graph.components();
  int x = std.math.pow(2,n-c);
  //writefln("CX %s",c);
  return x;
}

void run_tests(){
  int[][] rs;
  rs ~= [[calculate(1,0,new G(1,[])),1]];
  rs ~= [[calculate(2,1,new G(2,[1,2])),2]];
  rs ~= [[calculate(3,2,new G(3,[1,2,2,3])),4]];
  rs ~= [[calculate(10,10,new G(10,[1,8,4,10,4,6,5,10,2,3,1,7,3,4,3,6,6,9,3,7])),128]];
  rs ~= [[calculate(10,10,new G(10,[])),1]];

  int i = 0;
  bool failed = false;
  foreach(int[] r;rs){
    if(r[0] != r[1]){
      failed = true;
      //writefln("%s Failed %s != %s",i,r[0],r[1]);
    }
    i++;
  }

  if(!failed){
    writefln("OK");
  }
}

class G{
  int[][] vertex;
  int[] visited;
  ulong v_count = 0;

  this(int v_count){
    //writefln("NEW %s",v_count);
    for (int i = 0; i< v_count; i++){
      this.vertex ~= [[]];
      this.visited ~= 0;
    }
    this.v_count = v_count;
  }

  this(int n, int[] list){
    this(n);
    for (int i = 1; i < list.length; i += 2){
        this.add_vertex(list[i-1],list[i]);
    }
  }

  int[] conn(int v){
    return this.vertex[v];
  }

  void add_vertex(int s,int d){
    //writefln("%s-%s",s,d);
    vertex[s-1] ~= [d-1];
  }

  int components(){
    int cmp = 0;
    int[] q;

    int cur = 0;
    for(int v = 0; v < this.v_count; v++){
      if(this.visited[v] == 0){
        //writefln("*Visited %s (%s)",v+1,this.vertex[v].length);
        this.visited[v] = 1;
        cmp++;
        q ~= this.vertex[v];

        while(q.length > cur){
          v = q[cur];
          cur++;
          if ( this.visited[v] == 0 ){
            //writefln("Visited %s (%s)",v+1,this.vertex[v].length);
            this.visited[v] = 1;
            q ~= this.vertex[v];
          }
        }
      }
    }

    return cmp;
  }
}

import std.stdio;

void main()
{
    int ctl;
    readf("%s",&ctl);
    if(ctl == -1){
      run_tests();
    } else{
      run_instance(ctl);
    }

}

// void debug(T...)(T args){
//
// }
// int DEBUG = false;
//
// void debug(){
//   if(DEBUG){
//
//   }
// }

void run_instance(int ctl){
    int n = ctl;
    int m; readf(" %s\n",&m);
    auto graph = new G(n);

    for(int i = 0; i < m; i++){
        int s; readf("%s ",&s);
        int d; readf("%s ",&d);
        graph.add_vertex(s,d);
    }

    int r = calculate(n,m,graph);
    writefln("%s",r);
}

int calculate(int n, int m, G graph){
  int c = graph.components();
  int x = std.math.pow(2,n-c);
  //writefln("CX %s",c);
  return x;
}

void run_tests(){
  int[][] rs;
  rs ~= [[calculate(1,0,new G(1,[])),1]];
  rs ~= [[calculate(2,1,new G(2,[1,2])),2]];
  rs ~= [[calculate(3,2,new G(3,[1,2,2,3])),4]];
  rs ~= [[calculate(10,10,new G(10,[1,8,4,10,4,6,5,10,2,3,1,7,3,4,3,6,6,9,3,7])),512]];
  rs ~= [[calculate(10,10,new G(10,[])),1]];

  int i = 0;
  bool failed = false;
  foreach(int[] r;rs){
    if(r[0] != r[1]){
      failed = true;
      writefln("%s Failed %s != %s",i,r[0],r[1]);
    }
    i++;
  }

  if(!failed){
    writefln("OK");
  }
}

class G{
  int[][] vertex;
  int[] visited;
  ulong v_count = 0;

  this(int v_count){
    //writefln("NEW %s",v_count);
    for (int i = 0; i< v_count; i++){
      this.vertex ~= [[]];
      this.visited ~= 0;
    }
    this.v_count = v_count;
  }

  this(int n, int[] list){
    this(n);
    for (int i = 1; i < list.length; i += 2){
        this.add_vertex(list[i-1],list[i]);
    }
  }

  int[] conn(int v){
    return this.vertex[v];
  }

  void add_vertex(int s,int d){
    //writefln("%s-%s",s,d);
    vertex[s-1] ~= [d-1];
    vertex[d-1] ~= [s-1];
  }

  int components(){
    int cmp = 0;
    int[] q;

    int cur = 0;
    for(int v = 0; v < this.v_count; v++){
      if(this.visited[v] == 0){
        //writefln("*Visited %s (%s)",v+1,this.vertex[v].length);
        this.visited[v] = 1;
        cmp++;
        q ~= this.vertex[v];

        while(q.length > cur){
          v = q[cur];
          cur++;
          if ( this.visited[v] == 0 ){
            //writefln("Visited %s (%s)",v+1,this.vertex[v].length);
            this.visited[v] = 1;
            q ~= this.vertex[v];
          }
        }
      }
    }

    return cmp;
  }
}

import std.stdio;

void main()
{
    int ctl;
    readf("%s",&ctl);
    if(ctl == -1){
      run_tests();
    } else{
      run_instance(ctl);
    }

}

void run_instance(int ctl){
    int n = ctl;
    int m; readf(" %s\n",&m);
    auto graph = new G(n);

    for(int i = 0; i < m; i++){
        int s; readf("%s ",&s);
        int d; readf("%s ",&d);
        graph.add_vertex(s,d);
    }

    int r = calculate(n,m,graph);
    writefln("%s",r);
}

int calculate(int n, int m, G graph){
  int c = graph.components();
  int x = std.math.pow(2,n-c);
  //writefln("CX %s",c);
  return x;
}

void run_tests(){
  int[][] rs;
  rs ~= [[calculate(1,0,new G(1,[])),1]];
  rs ~= [[calculate(2,1,new G(2,[1,2])),2]];
  rs ~= [[calculate(3,2,new G(3,[1,2,2,3])),4]];
  int i = 0;
  bool failed = false;
  foreach(int[] r;rs){
    if(r[0] != r[1]){
      failed = true;
      writefln("%s Failed %s != %s",i,r[0],r[1]);
    }
    i++;
  }

  if(!failed){
    writefln("OK");
  }
}

class G{
  int[][] vertex;
  int[] visited;
  ulong v_count = 0;

  this(int v_count){
    for (int i = 0; i< v_count; i++){
      this.vertex ~= [[]];
      this.visited ~= 0;
    }
    this.v_count = v_count;
  }

  this(int n, int[] list){
    this(n);
    for (int i = 1; i < list.length; i++){
        this.add_vertex(list[i-1],list[i]);
    }
  }

  int[] conn(int v){
    return this.vertex[v];
  }

  void add_vertex(int s,int d){
    vertex[s-1] ~= d-1;
  }

  int components(){
    int cmp = 0;
    int[] q;

    int cur = 0;
    for(int v = 0; v < this.v_count; v++){
      if(this.visited[v] == 0){
        this.visited[v] = 1;
        cmp++;
        q ~= this.vertex[v];

        while(q.length > cur){
          v = q[cur];
          cur++;

          if ( this.visited[v] == 0 ){
            this.visited[v] = 1;
            q ~= this.vertex[v];
          }
        }
      }
    }

    return cmp;
  }
}

import std.stdio;

void main()
{
    int ctl;
    readf("%s",&ctl);
    if(ctl == -1){
      run_tests();
    } else{
      run_instance(ctl);
    }

}

// void debug(T...)(T args){
//
// }
// int DEBUG = false;
//
// void debug(){
//   if(DEBUG){
//
//   }
// }

void run_instance(int ctl){
    int n = ctl;
    int m; readf(" %s\n",&m);
    auto graph = new G(n);

    for(int i = 0; i < m; i++){
        int s; readf("%s ",&s);
        int d; readf("%s ",&d);
        graph.add_vertex(s,d);
    }

    int r = calculate(n,m,graph);
    writefln("%s",r);
}

int calculate(int n, int m, G graph){
  int c = graph.components();
  int x = std.math.pow(2,n-c);
  writefln("CX %s",c);
  return x;
}

void run_tests(){
  int[][] rs;
  rs ~= [[calculate(1,0,new G(1,[])),1]];
  rs ~= [[calculate(2,1,new G(2,[1,2])),2]];
  rs ~= [[calculate(3,2,new G(3,[1,2,2,3])),4]];
  rs ~= [[calculate(10,10,new G(10,[1,8,4,10,4,6,5,10,2,3,1,7,3,4,3,6,6,9,3,7])),512]];
  rs ~= [[calculate(20,20,new G(20,[6,8,13,20,7,13,6,17,5,15,1,12,5,5,17,5,14,6,14,12,20,7,20,1,6,1,7,2,19,14,17,1,10,11,15,9,18,2,12])),32768]];

  int i = 0;
  bool failed = false;
  foreach(int[] r;rs){
    if(r[0] != r[1]){
      failed = true;
      writefln("%s Failed %s is NOT %s",i,r[0],r[1]);
    }
    i++;
  }

  if(!failed){
    writefln("OK");
  }
}

class G{
  int[][] vertex;
  int[] visited;
  ulong v_count = 0;

  this(int v_count){
    //writefln("NEW %s",v_count);
    for (int i = 0; i< v_count; i++){
      this.vertex ~= [[]];
      this.visited ~= 0;
    }
    this.v_count = v_count;
  }

  this(int n, int[] list){
    this(n);
    for (int i = 1; i < list.length; i += 2){
        this.add_vertex(list[i-1],list[i]);
    }
  }

  int[] conn(int v){
    return this.vertex[v];
  }

  void add_vertex(int s,int d){
    //writefln("%s-%s",s,d);
    vertex[s-1] ~= [d-1];
    vertex[d-1] ~= [s-1];
  }

  int components(){
    int cmp = 0;
    int[] q;

    int cur = 0;
    for(int v = 0; v < this.v_count; v++){
      if(this.visited[v] == 0){
        //writefln("*Visited %s (%s)",v+1,this.vertex[v].length);
        this.visited[v] = 1;
        cmp++;
        q ~= this.vertex[v];

        while(q.length > cur){
          v = q[cur];
          cur++;
          if ( this.visited[v] == 0 ){
            //writefln("Visited %s (%s)",v+1,this.vertex[v].length);
            this.visited[v] = 1;
            q ~= this.vertex[v];
          }
        }
      }
    }

    return cmp;
  }
}


Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.There are two types of tasks:  pow v describes a task to switch lights in the subtree of vertex v. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v.Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.

The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree. The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the ancestor of vertex i. The third line contains n space-separated integers t1, t2, ..., tn (0 ≤ ti ≤ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise. The fourth line contains a single integer q (1 ≤ q ≤ 200 000) — the number of tasks. The next q lines are get v or pow v (1 ≤ v ≤ n) — the tasks described above.

For each task get v print the number of rooms in the subtree of v, in which the light is turned on.

4
1 1 1
1 0 0 1
9
get 1
get 2
get 3
get 4
pow 1
get 1
get 2
get 3
get 4

Note  The tree before the task pow 1. The tree after the task pow 1.

import core.bitop;
import core.checkedint;
import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
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;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

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

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

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

struct SegTree(size_t maxn) {
    int[maxn << 2] t;
    BitSet!(maxn << 2) inv;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void build(int i, in bool[ ] a) {
        if (a.length == 1)
            t[i] = a[0];
        else {
            const mid = a.length >> 1;
            build(lc(i), a[0 .. mid]);
            build(rc(i), a[mid .. $]);
            recalc(i);
        }
    }

    void push(int i, int left, int mid, int right) {
        if (btr(inv.ptr, i)) {
            t[lc(i)] = mid - left - t[lc(i)];
            t[rc(i)] = right - mid - t[rc(i)];
            btc(inv.ptr, lc(i));
            btc(inv.ptr, rc(i));
        }
    }

    void recalc(int i) {
        t[i] = t[lc(i)] + t[rc(i)];
    }

    int getSum(int i, int left, int right, int lb, int rb) {
        if (lb >= rb)
            return 0;
        if (lb == left && rb == right)
            return t[i];
        const mid = (left + right) >> 1;
        push(i, left, mid, right);
        return
            getSum(lc(i), left, mid, lb, min(mid, rb)) +
            getSum(rc(i), mid, right, max(lb, mid), rb);
    }

    void invert(int i, int left, int right, int lb, int rb) {
        if (lb >= rb)
            return;
        if (lb == left && rb == right) {
            t[i] = right - left - t[i];
            btc(inv.ptr, i);
            return;
        }
        const mid = (left + right) >> 1;
        push(i, left, mid, right);
        invert(lc(i), left, mid, lb, min(mid, rb));
        invert(rc(i), mid, right, max(lb, mid), rb);
        recalc(i);
    }
}

int gid;

struct Node {
    Node*[ ] children;
    int left, right;
    bool initial;

    void dfs() {
        left = gid++;
        .initial[left] = initial;
        foreach (child; children)
            child.dfs();
        right = gid;
    }
}

Node[200_000] nodes;
bool[200_000] initial;
SegTree!200_000 sgt;

void main() {
    int n;
    while (scanf("%d", &n) == 1) {
        version (LocalProject)
            nodes[ ] = Node.init;
        int x;
        foreach (ref node; nodes[1 .. n]) {
            scanf("%d", &x);
            nodes[x - 1].children ~= &node;
        }
        foreach (ref node; nodes[0 .. n]) {
            scanf("%d", &x);
            node.initial = cast(bool)x;
        }
        gid = 0;
        nodes[0].dfs();
        assert(gid == n);
        memSet(sgt.inv, 0x00);
        sgt.build(0, initial[0 .. n]);
        int q;
        scanf("%d ", &q);
        while (q--) {
            const cmd = cast(char)getchar();
            getchar();
            getchar();
            scanf("%d ", &x);
            x--;
            if (cmd == 'g')
                printf("%d\n", sgt.getSum(0, 0, n, nodes[x].left, nodes[x].right));
            else
                sgt.invert(0, 0, n, nodes[x].left, nodes[x].right);
        }
        debug putchar('\n');
    }

    fflush(stdout);
    _Exit(0);
}

import core.bitop;
import core.checkedint;
import core.stdc.stdio;
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.container;
import std.conv;
import std.exception;
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:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

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

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

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

struct SegTree(size_t maxn) {
    int[maxn << 2] t;
    BitSet!(maxn << 2) inv;

    static int lc(int i) { return i << 1 | 0x1; }
    static int rc(int i) { return (i << 1) + 2; }

    void build(int i, in bool[ ] a) {
        if (a.length == 1)
            t[i] = a[0];
        else {
            const mid = a.length >> 1;
            build(lc(i), a[0 .. mid]);
            build(rc(i), a[mid .. $]);
            t[i] = t[lc(i)] + t[rc(i)];
        }
    }

    void push(int i, int left, int mid, int right) {
        if (btr(inv.ptr, i)) {
            t[lc(i)] = mid - left - t[lc(i)];
            t[rc(i)] = right - mid - t[rc(i)];
            btc(inv.ptr, lc(i));
            btc(inv.ptr, rc(i));
        }
    }

    int getSum(int i, int left, int right, int lb, int rb) {
        if (lb >= rb)
            return 0;
        if (lb == left && rb == right)
            return t[i];
        const mid = (left + right) >> 1;
        push(i, left, mid, right);
        return
            getSum(lc(i), left, mid, lb, min(mid, rb)) +
            getSum(rc(i), mid, right, max(lb, mid), rb);
    }

    void invert(int i, int left, int right, int lb, int rb) {
        if (lb >= rb)
            return;
        if (lb == left && rb == right) {
            t[i] = right - left - t[i];
            btc(inv.ptr, i);
            return;
        }
        const mid = (left + right) >> 1;
        push(i, left, mid, right);
        invert(lc(i), left, mid, lb, min(mid, rb));
        invert(rc(i), mid, right, max(lb, mid), rb);
    }
}

int gid;

struct Node {
    Node*[ ] children;
    int left, right;
    bool initial;

    void dfs() {
        left = gid++;
        .initial[left] = initial;
        foreach (child; children)
            child.dfs();
        right = gid;
    }
}

Node[200_000] nodes;
bool[200_000] initial;
SegTree!200_000 sgt;

void main() {
    int n;
    while (scanf("%d", &n) == 1) {
        version (LocalProject)
            nodes[ ] = Node.init;
        int x;
        foreach (ref node; nodes[1 .. n]) {
            scanf("%d", &x);
            nodes[x - 1].children ~= &node;
        }
        foreach (ref node; nodes[0 .. n]) {
            scanf("%d", &x);
            node.initial = cast(bool)x;
        }
        gid = 0;
        nodes[0].dfs();
        assert(gid == n);
        memSet(sgt.inv, 0x00);
        sgt.build(0, initial[0 .. n]);
        int q;
        scanf("%d ", &q);
        while (q--) {
            const cmd = cast(char)getchar();
            getchar();
            getchar();
            scanf("%d ", &x);
            x--;
            if (cmd == 'g')
                printf("%d\n", sgt.getSum(0, 0, n, nodes[x].left, nodes[x].right));
            else
                sgt.invert(0, 0, n, nodes[x].left, nodes[x].right);
        }
        debug putchar('\n');
    }
}


You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.The boss battle consists of $$$n$$$ turns. During each turn, you will get several cards. Each card has two parameters: its cost $$$c_i$$$ and damage $$$d_i$$$. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as the total cost of the cards you play during the turn does not exceed $$$3$$$. After playing some (possibly zero) cards, you end your turn, and all cards you didn't play are discarded. Note that you can use each card at most once.Your character has also found an artifact that boosts the damage of some of your actions: every $$$10$$$-th card you play deals double damage.What is the maximum possible damage you can deal during $$$n$$$ turns?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of turns. Then $$$n$$$ blocks of input follow, the $$$i$$$-th block representing the cards you get during the $$$i$$$-th turn. Each block begins with a line containing one integer $$$k_i$$$ ($$$1 \le k_i \le 2 \cdot 10^5$$$) — the number of cards you get during $$$i$$$-th turn. Then $$$k_i$$$ lines follow, each containing two integers $$$c_j$$$ and $$$d_j$$$ ($$$1 \le c_j \le 3$$$, $$$1 \le d_j \le 10^9$$$) — the parameters of the corresponding card. It is guaranteed that $$$\sum \limits_{i = 1}^{n} k_i \le 2 \cdot 10^5$$$.

Print one integer — the maximum damage you may deal.

NoteIn the example test the best course of action is as follows:During the first turn, play all three cards in any order and deal $$$18$$$ damage.During the second turn, play both cards and deal $$$7$$$ damage.During the third turn, play the first and the third card and deal $$$13$$$ damage.During the fourth turn, play the first and the third card and deal $$$25$$$ damage.During the fifth turn, play the only card, which will deal double damage ($$$200$$$).

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

struct XD
{
    int c;
    int d;
}

long saiki(int idx, int rem, long[][] dp, XD[][] b)
{
    auto res = dp[idx][rem];
    if (res != -1) return res;
    if (idx == cast(int)b.length)
    {
        dp[idx][rem] = 0;
        return 0;
    }
    auto one = new int[3];
    fill(one, -1);
    auto two = -1;
    auto three = -1;
    foreach (i; 0 .. b[idx].length)
    {
        auto d = b[idx][i].d;
        if (b[idx][i].c == 1)
        {
            foreach (j; 0 .. 3)
            {
                if (d >= one[j])
                {
                    for (int k = 2; k > j; -- k)
                    {
                        one[k] = one[k - 1];
                    }
                    one[j] = d;
                    break;
                }
            }
        }
        else if (b[idx][i].c == 2)
        {
            if (d > two) two = d;
        }
        else
        {
            if (d > three) three = d;
        }
    }
    res = saiki(idx + 1, rem, dp, b);
    bool twice = (rem == 9);
    long ret = saiki(idx + 1, (rem + 1) % 10, dp, b);
    if (three != -1)
    {
        if (twice) res = max(res, ret + (three << 1));
        else res = max(res, ret + three);
    }
    if (two != -1)
    {
        if (twice) res = max(res, ret + (two << 1));
        else res = max(res, ret + two);
    }
    if (one[0] != -1)
    {
        if (twice) res = max(res, ret + (one[0] << 1));
        else res = max(res, ret + one[0]);
    }
    twice = (rem == 8 || rem == 9);
    ret = saiki(idx + 1, (rem + 2) % 10, dp, b);
    if (one[1] != -1)
    {
        if (twice) res = max(res, ret + (one[0] << 1) + one[1]);
        else res = max(res, ret + one[0] + one[1]);
    }
    if (one[0] != -1 && two != -1)
    {
        if (twice) res = max(res, ret + (max(one[0], two) << 1) + min(one[0], two));
        else res = max(res, ret + one[0] + two);
    }
    if (one[2] != -1)
    {
        twice = (rem >= 7 && rem < 10);
        ret = saiki(idx + 1, (rem + 3) % 10, dp, b);
        if (twice) res = max(res, ret + (one[0] << 1) + one[1] + one[2]);
        else res = max(res, ret + one[0] + one[1] + one[2]);
    }
    dp[idx][rem] = res;
    return res;
}

void solve(XD[][] b)
{
    auto n = cast(int)b.length;
    auto dp = new long[][](n + 1, 10);
    foreach (i; 0 .. n + 1) fill(dp[i], -1);
    auto ans = saiki(0, 0, dp, b);
    writeln(ans);
}

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

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

long saiki(int idx, int rem, long[][] dp, Tuple!(int, int)[][] b)
{
    auto res = dp[idx][rem];
    if (res != -1) return res;
    if (idx == cast(int)b.length)
    {
        dp[idx][rem] = 0;
        return 0;
    }
    auto one = new int[3];
    fill(one, -1);
    auto two = -1;
    auto three = -1;
    foreach (i; 0 .. b[idx].length)
    {
        auto d = b[idx][i][1];
        if (b[idx][i][0] == 1)
        {
            foreach (j; 0 .. 3)
            {
                if (d >= one[j])
                {
                    for (int k = 2; k > j; -- k) one[k] = one[k - 1];
                    one[j] = d;
                    break;
                }
            }
        }
        else if (b[idx][i][0] == 2)
        {
            if (d > two) two = d;
        }
        else
        {
            if (d > three) three = d;
        }
    }
    res = saiki(idx + 1, rem, dp, b);
    bool twice = (rem == 9);
    long ret = saiki(idx + 1, (rem + 1) % 10, dp, b);
    if (three != -1)
    {
        if (twice) res = max(res, ret + (three << 1));
        else res = max(res, ret + three);
    }
    if (two != -1)
    {
        if (twice) res = max(res, ret + (two << 1));
        else res = max(res, ret + two);
    }
    if (one[0] != -1)
    {
        if (twice) res = max(res, ret + (one[0] << 1));
        else res = max(res, ret + one[0]);
    }
    twice = (rem == 8 || rem == 9);
    ret = saiki(idx + 1, (rem + 2) % 10, dp, b);
    if (one[1] != -1)
    {
        if (twice) res = max(res, ret + (one[0] << 1) + one[1]);
        else res = max(res, ret + one[0] + one[1]);
    }
    if (one[0] != -1 && two != -1)
    {
        if (twice) res = max(res, ret + (max(one[0], two) << 1) + min(one[0], two));
        else res = max(res, ret + one[0] + two);
    }
    if (one[2] != -1)
    {
        twice = (rem >= 7 && rem < 10);
        ret = saiki(idx + 1, (rem + 3) % 10, dp, b);
        if (twice) res = max(res, ret + (one[0] << 1) + one[1] + one[2]);
        else res = max(res, ret + one[0] + one[1] + one[2]);
    }
    dp[idx][rem] = res;
    return res;
}

void solve(Tuple!(int, int)[][] b)
{
    auto n = cast(int)b.length;
    auto dp = new long[][](n + 1, 10);
    foreach (i; 0 .. n + 1) fill(dp[i], -1);
    auto ans = saiki(0, 0, dp, b);
    writeln(ans);
}

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


You are given a tree (an undirected connected graph without cycles) and an integer $$$s$$$.Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $$$s$$$. At the same time, he wants to make the diameter of the tree as small as possible.Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.Find the minimum possible diameter that Vanya can get.

The first line contains two integer numbers $$$n$$$ and $$$s$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq s \leq 10^9$$$) — the number of vertices in the tree and the sum of edge weights. Each of the following $$$n−1$$$ lines contains two space-separated integer numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the indexes of vertices connected by an edge. The edges are undirected. It is guaranteed that the given edges form a tree.

Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $$$s$$$. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac {|a-b|} {max(1, b)} \leq 10^{-6}$$$.

NoteIn the first example it is necessary to put weights like this:  It is easy to see that the diameter of this tree is $$$2$$$. It can be proved that it is the minimum possible diameter.In the second example it is necessary to put weights like this:

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

immutable int INF = 10L ^^ 9 + 23;
immutable int MD = 10 ^^ 9 + 7;

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

    auto adjcnt = new int[] (n+1);
    foreach (_ ; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        adjcnt[u] += 1;
        adjcnt[v] += 1;
    }

    auto leafs = adjcnt.count!(x => x == 1);

    double ans = s.to!double / leafs * 2;

    ans.writefln!"%.10f";
}


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

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

void main()
{
	int n = to!int(readln.strip);
	auto line = to!(int[])(readln.strip.split);

	int left = fold!max(line);
	int indLeft = line.countUntil(left);
	copy(line[0..indLeft].dup, line[1..indLeft+1]);
	line[0] = left;

	int right = fold!min(line);
	line.reverse;
	int indRight = line.countUntil(right);
	writeln(indLeft + indRight);
}

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

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[] nums;
	nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
	}
	int min = int.max;
	int p = 0;
	int totalmoves = 0;
	foreach (int i; 0..n)
	{
		if (nums[i] <= min)
		{
			min = nums[i];
			p = i;
		}
	}
	totalmoves = (n - p - 1);
	foreach (int i; p..(n-1))
	{
		nums[i] = nums[i+1];
	}
	nums[nums.length - 1] = min;
	int max = int.min;
	foreach (int i; 0..n)
	{
		if (nums[i] > max)
		{
			max = nums[i];
			p = i;
		}
	}
	totalmoves += p;
	printf("%d", totalmoves);
	return 0;
}

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

void main() {
  readln;

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

  int max = a[0];
  int min = a[0];
  int maxInd = 0;
  int minInd = 0;

  foreach (int i, e; a.array) {
    if (max < e) {
      max = e;
      maxInd = i;
    }

    if (min >= e) {
      min = e;
      minInd = i;
    }
  }

  auto ans = maxInd + a.length - minInd - 1;
  if (minInd < maxInd) ans--;
  ans.writeln;
}


Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called "massive refactoring", which can replace names of many variable in just one run. To use it, Alice needs to select two strings $$$s$$$ and $$$t$$$ and after that for each variable the following algorithm is performed: if the variable's name contains $$$s$$$ as a substring, then the first (and only first) occurrence of $$$s$$$ is replaced with $$$t$$$. If the name doesn't contain $$$s$$$, then this variable's name stays the same.The list of variables is known and for each variable both the initial name and the name Alice wants this variable change to are known. Moreover, for each variable the lengths of the initial name and the target name are equal (otherwise the alignment of the code could become broken). You need to perform renaming of all variables in exactly one run of the massive refactoring command or determine that it is impossible.

The first line contains the only integer $$$n$$$ ($$$1 \le n \le 3000$$$) — the number of variables in Alice's program. The following $$$n$$$ lines contain the initial names of variables $$$w_1, w_2, \ldots, w_n$$$, one per line. After that, $$$n$$$ more lines go, the $$$i$$$-th of them contains the target name $$$w'_i$$$ for the $$$i$$$-th variable. It is guaranteed that $$$1 \le |w_i| = |w'_i| \le 3000$$$. It is guaranteed that there is at least one variable having its target name different from the initial name. Both initial and target names consist of lowercase English letters only. For each variable the length of its initial name is equal to the length of its target name.

If it is impossible to rename all variables with one call of "massive refactoring", print "NO" (quotes for clarity). Otherwise, on the first line print "YES" (quotes for clarity) and on the following lines print $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 5000$$$), which should be used for replacement. Strings $$$s$$$ and $$$t$$$ should consist only of lowercase letters of English alphabet. If there are multiple ways to perform a "massive refactoring", you can use any of them.

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

int [] kmp1 (string s)
{
	int [] p;
	int k = -1;
	p ~= k;
	foreach (i, char c; s)
	{
		while (k >= 0 && c != s[k])
		{
			k = p[k];
		}
		k += 1;
		p ~= k;
	}
	return p;
}

int kmp2 (string t, string s, int [] p)
{
	int len = s.length.to !(int);
	int k = 0;
	foreach (i, char c; t)
	{
		while (k >= 0 && c != s[k])
		{
			k = p[k];
		}
		k += 1;
		if (k >= len)
		{
			return i - len + 1;
		}
	}
	return -1;
}

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

		auto lo = new int [n];
		lo[] = int.max;
		auto hi = new int [n];
		hi[] = int.min;
		foreach (i; 0..n)
		{
			auto k = a[i].length;
			assert (k == b[i].length);
			foreach (j; 0..k)
			{
				if (a[i][j] != b[i][j])
				{
					lo[i] = min (lo[i], j);
					hi[i] = max (hi[i], j);
				}
			}
		}

		auto act = n.iota.map !(i => (lo[i] <= hi[i])).array;
		assert (any (act));

		int first = n.iota.find !(i => act[i]).front;
		int len = hi[first] - lo[first] + 1;
		bool ok = n.iota.all !(i => !act[i] ||
		    hi[i] - lo[i] + 1 == len);
		if (!ok)
		{
			writeln ("NO");
			continue multitest_loop;
		}

		foreach (i; 0..n)
		{
			if (act[i])
			{
				foreach (j; 0..len)
				{
					ok &= a[i][j + lo[i]] ==
					    a[first][j + lo[first]];
					ok &= b[i][j + lo[i]] ==
					    b[first][j + lo[first]];
				}
			}
		}
		if (!ok)
		{
			writeln ("NO");
			continue multitest_loop;
		}

		while (n.iota.all !(i => !act[i] || (lo[i] > 0 &&
		    a[i][lo[i] - 1] == a[first][lo[first] - 1])))
		{
			lo[] -= 1;
		}

		while (n.iota.all !(i => !act[i] || (hi[i] < a[i].length - 1 &&
		    a[i][hi[i] + 1] == a[first][hi[first] + 1])))
		{
			hi[] += 1;
		}

		string src = a[first][lo[first]..hi[first] + 1];
		string dst = b[first][lo[first]..hi[first] + 1];
		auto p = kmp1 (src);

		foreach (i; 0..n)
		{
			auto pos = kmp2 (a[i], src, p);
			ok &= pos == (act[i] ? lo[i] : -1);
		}
		if (!ok)
		{
			writeln ("NO");
			continue multitest_loop;
		}

		writeln ("YES");
		writeln (src);
		writeln (dst);
	}
}


You are given a huge decimal number consisting of $$$n$$$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers $$$0 \le y < x < n$$$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

The first line of the input contains three integers $$$n, x, y$$$ ($$$0 \le y < x < n \le 2 \cdot 10^5$$$) — the length of the number and the integers $$$x$$$ and $$$y$$$, respectively. The second line of the input contains one decimal number consisting of $$$n$$$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.

Print one integer — the minimum number of operations you should perform to obtain the number having remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

NoteIn the first example the number will be $$$11010100100$$$ after performing one operation. It has remainder $$$100$$$ modulo $$$100000$$$.In the second example the number will be $$$11010100010$$$ after performing three operations. It has remainder $$$10$$$ modulo $$$100000$$$.

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

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

    int ans = 0;

    foreach (i; 0..X) {
        if (i < Y) {
            ans += S[N-i-1] == '1' ;
        } else if (i == Y) {
            ans += S[N-i-1] == '0';
        } else {
            ans += S[N-i-1] == '1' ;
        }
    }

    ans.writeln;
}

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

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 x = read.to!int;
	int y = read.to!int;

	bool[] us = readln.chomp.map!(x => x == '1').array;
	bool[] ys;
	foreach_reverse(u; us) ys ~= u;

	print!1("ys:", ys);

	int ans;
	foreach(int i; 0 .. x){
		if(i == y && ! ys[i]) print!1("*"), ans += 1;
		if(i != y && ys[i]) print!1("-"), ans += 1;
		print!1(ans);
	}

	ans.writeln;

}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
  GC.disable();

  //

  int n, x, y;
  readf(" %s %s %s\n", n, x, y);
  auto s = readln().strip.dup;

  reverse(s);

  int tt = 0;
  if (s[y] == '0') tt++;
  tt += s[0 .. y].filter!"a!='0'".array.length;

  tt += s[y+1 .. x].filter!"a!='0'".array.length;

  writeln(tt);

  //

}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD!int;
	auto X = RD!int;
	auto Y = RD!int;
	auto s = RD!string;

	long ans;
	foreach_reverse (i; 0..N)
	{
		if (N-1-i == X) break;
		auto bit = N-1-i == Y ? '1' : '0';
		if (s[i] != bit)
			++ans;
	}

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


Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of $$$n$$$ tracks numbered from $$$1$$$ to $$$n$$$. The playlist is automatic and cyclic: whenever track $$$i$$$ finishes playing, track $$$i+1$$$ starts playing automatically; after track $$$n$$$ goes track $$$1$$$.For each track $$$i$$$, you have estimated its coolness $$$a_i$$$. The higher $$$a_i$$$ is, the cooler track $$$i$$$ is.Every morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness $$$x$$$ of already played tracks. Once you hear that a track with coolness strictly less than $$$\frac{x}{2}$$$ (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood.For each track $$$i$$$, find out how many tracks you will listen to before turning off the music if you start your morning with track $$$i$$$, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of tracks in the playlist. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), denoting coolnesses of the tracks.

Output $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$, where $$$c_i$$$ is either the number of tracks you will listen to if you start listening from track $$$i$$$ or $$$-1$$$ if you will be listening to music indefinitely.

NoteIn the first example, here is what will happen if you start with...   track $$$1$$$: listen to track $$$1$$$, stop as $$$a_2 < \frac{a_1}{2}$$$.  track $$$2$$$: listen to track $$$2$$$, stop as $$$a_3 < \frac{a_2}{2}$$$.  track $$$3$$$: listen to track $$$3$$$, listen to track $$$4$$$, listen to track $$$1$$$, stop as $$$a_2 < \frac{\max(a_3, a_4, a_1)}{2}$$$.  track $$$4$$$: listen to track $$$4$$$, listen to track $$$1$$$, stop as $$$a_2 < \frac{\max(a_4, a_1)}{2}$$$. In the second example, if you start with track $$$4$$$, you will listen to track $$$4$$$, listen to track $$$1$$$, listen to track $$$2$$$, listen to track $$$3$$$, listen to track $$$4$$$ again, listen to track $$$1$$$ again, and stop as $$$a_2 < \frac{max(a_4, a_1, a_2, a_3, a_4, a_1)}{2}$$$. Note that both track $$$1$$$ and track $$$4$$$ are counted twice towards the result.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional, std.meta;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

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

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

    if (arr.maxElement <= arr.minElement * 2) {
        (-1).repeat(n).map!(to!string).join(" ").writeln;
        return;
    }

    auto arr3 = arr.chain(arr).chain(arr).array;

    debug { arr3.writeln; }

    auto ans = new int[] (n);

    int le = 0;
    alias elem = Tuple!(int, int);
    auto mx = make!(DList!elem);
    foreach (i, e; arr3) {
        while (!mx.empty() && e >= mx.back[0]) {
            mx.removeBack();
        }

        mx ~= tuple(e.to!int, i.to!int);

        debug { writeln(i, ' ', e, ' ', mx.front[0]); }

        while (!mx.empty() && e * 2 < mx.front[0]) {
            while (le <= mx.front[1]) {
                ans[le % n] = i.to!int - le;
                ++le;
            }

            debug { writeln(le); }
            mx.removeFront();
        }
    }

    ans.map!(to!string).join(" ").writeln;
}

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

immutable int logHalf = 19;
immutable int half = 1 << logHalf;
immutable int limit = half << 1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		auto t = new int [limit];
		foreach (i; 0..n * 3 + 1)
		{
			t[i + half] = a[i % n];
		}
		foreach_reverse (i; 1..half)
		{
			t[i] = min (t[i * 2 + 0], t[i * 2 + 1]);
		}

		auto bads = new int [n * 2];
		for (int i = 0; i < n * 2; i++)
		{
			int value = a[i % n];
			int hi = i + half;
			while (true)
			{
				if ((hi & 1) == 0 && t[hi + 1] * 2 < value)
				{
					break;
				}
				hi = hi / 2;
			}
			while (hi < half)
			{
				int p = hi * 2 + 2;
				if (t[p] * 2 < value)
				{
					p -= 1;
				}
				hi = p;
			}
			bads[i] = hi - half;
			debug {writeln (i, ": ", bads[i]);}
		}

		foreach_reverse (i; 0..n * 2 - 1)
		{
			bads[i] = min (bads[i], bads[i + 1]);
		}
		debug {writeln (bads);}

		auto res = new int [n];
		foreach (i; 0..n)
		{
			if (bads[i] == n * 3)
			{
				res[i] = -1;
			}
			else
			{
				res[i] = bads[i] - i + 1;
			}
		}
		writefln ("%(%s %)", res);
	}
}

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;

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

void solve(){
	int n = rint;
	long[] as = rlong(n);
	as ~= as ~ as;
	log("as:", as);

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

	int[] ans;
	K[] ks = new K[](n * 2);
	int l = 0, r = 0;
	int j0;
	foreach(int i, a; as){
		while(l < r && ks[r - 1].value <= a) r -= 1;
		ks[r] = K(i, a), r += 1;
		log("i:", i, "a:", a, "l:", l, "r:", r, "ks:", ks[0 .. n]);
		int newl = uplimit(l, r - 1, (int x) => (ks[x].value > a * 2));
		if(newl >= 0 && j0 <= ks[newl].pos){
			foreach(j; j0 .. ks[newl].pos + 1) ans ~= i - j;
			j0 = ks[newl].pos + 1;
		}
		log("l:", l, "newl:", newl, "ans:", ans);
	}
	while(ans.length < n) ans ~= -1;
	ans[0 .. n].map!(to!string).array.join(" ").writeln;

}
struct K{
	int pos;
	long value;
}

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

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

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

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

enum E = 20;

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

      auto mx = new int[][](E, N);
      auto mn = new int[][](E, N);
      auto live = new bool[][](E, N);
      foreach (i; 0 .. N) {
        mx[0][i] = A[i];
        mn[0][i] = A[i];
        live[0][i] = true;
      }
      foreach (e; 0 .. E - 1) {
        foreach (i; 0 .. N) {
          const j = (i + (1 << e)) % N;
          mx[e + 1][i] = max(mx[e][i], mx[e][j]);
          mn[e + 1][i] = min(mn[e][i], mn[e][j]);
          live[e + 1][i] = live[e][i] && live[e][j] && !(mx[e][i] > 2 * mn[e][j]);
        }
      }
      auto ans = new int[N];
      foreach (i; 0 .. N) {
        int m = 0;
        int sum;
        int j = i;
        foreach_reverse (e; 0 .. E) {
          if (live[e][j] && !(m > 2 * mn[e][j])) {
            chmax(m, mx[e][j]);
            sum += 1 << e;
            j = (j + (1 << e)) % N;
          }
        }
        ans[i] = (sum >= 2 * N) ? -1 : sum;
      }

      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number ai (1 ≤ ai ≤ n·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions:  each child gets exactly n orange segments;  the i-th child gets the segment with number ai for sure;  no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.

The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ n·k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.

Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int k = cin.readInt;
                int[] d = new int[n * k + 1];
                int[int] map;
                int[][] c = new int[][](k);

                for (int i = 0; i < k; i++) {
                        int input = cin.readInt;
                        d[input] = 1;
                        map[i] = input;
                }

                int offSet = 1;
                for (int i = 0; i < k; i++) {
                        c[i] ~= map[i];
                        int count = 1;
                        for (int j = offSet; count < n;) {
                                if (!d[j]) {
                                        c[i] ~= j;
                                        d[j] = 1;
                                        count++;
                                        j++;
                                        offSet = j;
                                } else {
                                        offSet++;
                                        j++;
                                }
                        }
                }

                for (int i = 0; i < k; i++) {
                        for (int j = 0; j < c[i].length; j++) {
                                write(c[i][j], " ");
                        }
                        writeln();
                }
        }
}

module sigod.codeforces.p244A;

import std.array : split;
import std.conv : to;
import std.stdio;
import std.string : strip;

void main() {
	int n, k;

	read_variables(n, k);

	auto a = read_array!int();
	auto orange = new bool[n * k + 1];

	foreach (ref ai; a) {
		orange[ai] = true;
	}

	int position = 1;

	foreach (ref ai; a) {
		stdout.write(ai);

		int count = 1;
		while (count < n) {
			if (!orange[position]) {
				stdout.write(" ", position);

				orange[position] = true;

				++count;
			}

			++position;
		}

		stdout.writeln();
	}
}

private
void read_variables(S...)(out S args) {
	auto input = stdin.readln().strip().split();

	foreach (index, ref arg; args) {
		arg = input[index].to!(typeof(arg))();
	}
}

private
T[] read_array(T)() {
	auto input = stdin.readln().strip().split();

	T[] result = new T[input.length];

	foreach (index, ref element; input) {
		result[index] = element.to!T();
	}

	return result;
}

module sigod.codeforces.p244A;

import std.array : split;
import std.conv : to;
import std.stdio;
import std.string : strip;

void main() {
	int n, k;

	read_variables(n, k);

	auto a = read_array!int();

	foreach (ai; a) {
		stdout.write(ai);

		foreach (ni; 1 .. n) {
			ai += k;

			if (ai > n * k) ai %= n * k;

			stdout.write(" ", ai);
		}

		stdout.writeln();
	}
}

private
void read_variables(S...)(out S args) {
	auto input = stdin.readln().strip().split();

	foreach (index, ref arg; args) {
		arg = input[index].to!(typeof(arg))();
	}
}

private
T[] read_array(T)() {
	auto input = stdin.readln().strip().split();

	T[] result = new T[input.length];

	foreach (index, ref element; input) {
		result[index] = element.to!T();
	}

	return result;
}


Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?

The first line of input contains an integer t (0 < t < 180) — the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) — the angle the robot can make corners at measured in degrees.

For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.

NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case — a square.

import std.stdio;

int main(string[] argv)
{
	int n;
	// formula for the angle of n line poligon is (n - 2) * 180 / n, where n >= 3
	scanf("%d", &n);
	foreach (int i; 0..n)
	{
		int angle; scanf("%d", &angle);
		int nl = 360 / (180 - angle);
		if (((nl - 2) * 180) / nl == angle)
		{
			printf("YES\n");
		} else {
			printf("NO\n");
		}
	}
	return 0;
}

import std.stdio;

int main(string[] argv)
{
	int n;
	// formula for the angle of n line poligon is (n - 2) * 180 / n, where n >= 3
	scanf("%d", &n);
	foreach (int i; 0..n)
	{
		int angle; scanf("%d", &angle);
		foreach (int k; 3..101)
		{
			int ca = (((k - 2) * 180) / k);
			if (ca == angle)
			{
				printf("YES\n");
				break;
			} else
			if (ca > angle)
			{
				printf("NO\n");
				break;
			}
		}
	}
	return 0;
}

import std.stdio;

int main(string[] argv)
{
	int n;
	// formula for the angle of n line poligon is (n - 2) * 180 / n, where n >= 3
	scanf("%d", &n);
	foreach (int i; 0..n)
	{
		int angle; scanf("%d", &angle);
		bool wasAnswered = false;
		foreach (int k; 3..101)
		{
			int ca = (((k - 2) * 180) / k);
			if (ca == angle)
			{
				printf("YES\n");
				wasAnswered = true;
				break;
			} else
			if (ca > angle)
			{
				printf("NO\n");
				wasAnswered = true;
				break;
			}
		}
		if (!wasAnswered)
		{
			printf("NO\n");
		}
	}
	return 0;
}


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $$$x \to (-x)$$$). What is the maximum number of different values in the array you can achieve?

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The next lines contain the description of the $$$t$$$ test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 100$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$).

For each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.

NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array $$$[-1, 1, 2, -2]$$$ with four different values.In the second example all three numbers are already different.In the third example negation does not change anything.

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable s =
            readln
            .chomp
            .split(' ')
            .to!(byte[])
            .sort
            .group
            .assocArray;

        immutable ans = s.length +
            s.byKey
            .count!((k) => s[k] >= 2 && -k !in s);

        writeln(ans);
    }
}
// "" ' '

void main() { runSolver(); }

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

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

      bool[long] visited;
      foreach(a; A) {
        if (a in visited) visited[-a] = true; else visited[a] = false;
      }

      return visited.length;
    }

    foreach(_; 0..QN) subSolve().writeln;
  }

  outputForAtCoder(&solve);
}

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

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

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int [int] k;
		foreach (ref c; a)
		{
			k[abs (c)] += 1;
			k[abs (c)] = min (k[abs (c)], 1 + (c != 0));
		}
		k.byValue.sum.writeln;
	}
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    int[int] freq;
    foreach (x ; a)
      freq[x]++;
    int ans = (0 in freq) ? 1 : 0;
    foreach (i ; 1 .. 101) {
      int cnt = freq.get(i, 0) + freq.get(-i, 0);
      ans += min(cnt, 2);
    }
    writeln(ans);
  }
}

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

        int[int] freq;
        foreach (i; 0 .. N) {
          ++freq[abs(A[i])];
        }
        int ans;
        foreach (key, val; freq) {
          ans += min((key == 0) ? 1 : 2, val);
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable arr = readln().chomp.split(' ').to!(int[]).assumeUnique;

        int[int] normal;
        foreach (val; arr) ++ normal[val];

        size_t maxi = normal.length;
        foreach (i; 0 .. n) {
            int[int] frec = normal.dup;

            foreach (j; i .. n) {
                if (arr[j]) {
                    -- frec[arr[j]];
                    ++ frec[-arr[j]];
                    if (frec[arr[j]] == 0)
                        frec.remove(arr[j]);
                }
                maxi = max(maxi, frec.length);
            }
        }

        maxi.writeln();
    }
}
// "" ' '

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable arr = readln().chomp.split(' ').to!(int[]).assumeUnique;

        int[int] normal;
        foreach (val; arr) ++ normal[val];

        size_t maxi = normal.length;
        foreach (i; 0 .. n) {
            int[int] frec = normal.dup;
            int[int] inverted;

            size_t cont = frec.length;
            foreach (j; i .. n) {
                if (arr[j] != 0) {
                    cont += (inverted[arr[j]] ++ == 0);
                    cont -= (-- frec[arr[j]] == 0);
                }
                maxi = max(maxi, cont);
            }
        }

        maxi.writeln();
    }
}
// "" ' '


One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle $$$n \times m$$$, where each cell is either empty, or contains a digit from $$$1$$$ to $$$8$$$, or a bomb. The field is valid if for each cell:   if there is a digit $$$k$$$ in the cell, then exactly $$$k$$$ neighboring cells have bombs.  if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $$$8$$$ neighboring cells).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the sizes of the field. The next $$$n$$$ lines contain the description of the field. Each line contains $$$m$$$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $$$1$$$ to $$$8$$$, inclusive.

Print "YES", if the field is valid and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrarily.

NoteIn the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article.

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

void main()
{
	int n, m;
	readln.chomp.split.tie(n, m);
	char[][] board = new char[][](n);
	foreach (i; 0..n) {
		board[i] = readln.chomp.dup;
	}
	bool yes = true;
	enum OFS = [
		[0, 1],
		[1, 0],
		[-1, 0],
		[0, -1],
		[1, 1],
		[1, -1],
		[-1, 1],
		[-1, -1]
	];
	foreach (y; 0..n) {
		foreach (x; 0..m) {
			if (board[y][x] == '*') {
				continue;
			}
			int v;
			if (board[y][x] == '.') {
				v = 0;
			} else {
				v = board[y][x] - '0';
			}
			int cnt = 0;
			foreach (d; OFS) {
				int nx = x + d[0];
				int ny = y + d[1];
				if (nx < 0 || m <= nx
						|| ny < 0 || n <= ny) {
					continue;
				}
				if (board[ny][nx] == '*') {
					++cnt;
				}
			}
			yes &= v == cnt;
		}
	}
	writeln = yes ? "YES" : "NO";
}

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

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


A bitstring is a string that contains only the characters 0 and 1.Koyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length $$$2n$$$. A valid novel for the contest is a bitstring of length at most $$$3n$$$ that contains at least two of the three given strings as subsequences.Koyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) characters.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). Each of the following three lines contains a bitstring of length $$$2n$$$. It is guaranteed that these three strings are pairwise distinct. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, print a single line containing a bitstring of length at most $$$3n$$$ that has at least two of the given bitstrings as subsequences. It can be proven that under the constraints of the problem, such a bitstring always exists. If there are multiple possible answers, you may output any of them.

NoteIn the first test case, the bitstrings 00 and 01 are subsequences of the output string: 010 and 010. Note that 11 is not a subsequence of the output string, but this is not required.In the second test case all three input strings are subsequences of the output string: 011001010, 011001010 and 011001010.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		string [] s;
		foreach (k; 0..3)
		{
			s ~= readln.strip;
		}
		string res;
		foreach (i; 0..3 * n)
		{
			if (s.any !(empty))
			{
				break;
			}
			char c = '0';
			if ((s[0].front == '1') + (s[1].front == '1') +
			    (s[2].front == '1') >= 2)
			{
				c = '1';
			}
			res ~= c;
			foreach (k; 0..3)
			{
				if (s[k].front == c)
				{
					s[k].popFront ();
				}
			}
		}
		s.schwartzSort !(t => t.length);
		res ~= s.join;
		while (res.length < n * 3)
		{
			res ~= '0';
		}
		res = res[0..n * 3];
		writeln (res);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		string [] s;
		foreach (k; 0..3)
		{
			s ~= readln.strip ~ '#';
		}
		string res;
		foreach (i; 0..3 * n)
		{
			char c = '0';
			if ((s[0].front == '1') + (s[1].front == '1') +
			    (s[2].front == '1') >= 2)
			{
				c = '1';
			}
			res ~= c;
			foreach (k; 0..3)
			{
				if (s[k].front == c)
				{
					s[k].popFront ();
				}
			}
		}
		writeln (res);
	}
}


You are given an array $$$a$$$ of $$$n$$$ elements. Your can perform the following operation no more than $$$n$$$ times: Select three indices $$$x,y,z$$$ $$$(1 \leq x < y < z \leq n)$$$ and replace $$$a_x$$$ with $$$a_y - a_z$$$. After the operation, $$$|a_x|$$$ need to be less than $$$10^{18}$$$.Your goal is to make the resulting array non-decreasing. If there are multiple solutions, you can output any. If it is impossible to achieve, you should report it as well.

Each test contains multiple test cases. The first line will contain a single integer $$$t$$$ $$$(1 \leq t \leq 10000)$$$ — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ $$$(3 \leq n \leq 2 \cdot 10^5)$$$ — the size of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots ,a_n$$$ $$$(-10^9 \leq a_i \leq 10^9)$$$, the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$-1$$$ in a single line if there is no solution. Otherwise in the first line you should print a single integer $$$m$$$ $$$(0 \leq m \leq n)$$$ — number of operations you performed. Then the $$$i$$$-th of the following $$$m$$$ lines should contain three integers $$$x,y,z$$$ $$$(1 \leq x < y < z \leq n)$$$— description of the $$$i$$$-th operation. If there are multiple solutions, you can output any. Note that you don't have to minimize the number of operations in this task.

NoteIn the first example, the array becomes $$$[-6,-4,2,-1,2]$$$ after the first operation,$$$[-6,-4,-3,-1,2]$$$ after the second operation.In the second example, it is impossible to make the array sorted after any sequence of operations.In the third example, the array is already sorted, so we don't need to perform any operations.

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.typecons;
import std.algorithm;
void solution(ref File input, ref File output)
{
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp.split(' ').map!(to!int).array;
        if (source[$ - 2] <= source[$ - 1])
        {
            if (source[$ - 1] >= 0)
            {
                output.writeln(source.length - 2);
                for (int i = 0; i < source.length - 2; i++)
                {
                    output.writeln(i + 1, ' ', source.length - 1, ' ', source.length);
                }
            } else
            {
                output.writeln(
                    source.isSorted ? 0 : -1
                );
            }
        } else
        {
            output.writeln(-1);
        }
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.typecons;
import std.algorithm;
void solution(ref File input, ref File output)
{
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp.split(' ').map!(to!int).array;
        if (source[$ - 2] < source[$ - 1])
        {
            if (source[$ - 1] >= 0)
            {
                output.writeln(source.length - 2);
                for (int i = 0; i < source.length - 2; i++)
                {
                    output.writeln(i + 1, ' ', source.length - 1, ' ', source.length);
                }
            } else
            {
                output.writeln(
                    source.isSorted ? 0 : -1
                );
            }
        } else
        {
            output.writeln(-1);
        }
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}


Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of T-shirts. The $$$i$$$-th of the next $$$n$$$ lines contains $$$a_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the previous year. The $$$i$$$-th of the next $$$n$$$ lines contains $$$b_i$$$ — the size of the $$$i$$$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $$$b$$$ from the list $$$a$$$.

Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.

NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal.

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

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

    int [char][int][2] arr;

    foreach (i; 0 .. 2) {
        foreach (_; 0 .. n) {
            auto s = readln.chomp;
            arr[i][cast(int) s.length][s[$-1]] += 1;
        }
    }

    debug { arr.writeln; }

    auto ans = 0;
    foreach (len; 1 .. 5) {
        foreach (letter; ['S', 'M', 'L']) {
            auto getVal = (int i) => len in arr[i] ? arr[i][len].get(letter, 0) : 0;
            ans += abs(getVal(0)- getVal(1));
        }
    }

    ans /= 2;
    ans.writeln;
}