A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v, u).A parent of vertex v in the rooted tree with the root in vertex r (v ≠ r) is vertex pv, such that d(r, pv) + 1 = d(r, v) and d(pv, v) = 1. For example, on the picture the parent of vertex v = 5 is vertex p5 = 2.One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1 < v ≤ n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7="ba". The characters in the strings are numbered starting from 0.    An example of Polycarpus's tree (corresponds to the example from the statement) Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v, x) that means that the position is the x-th letter of the string sv (1 < v ≤ n, 0 ≤ x < |sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2, 1) and (3, 1).Let's consider the pair of positions (v, x) and (u, y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v, x) to (u, y), written in the order of this path. For example, in the picture the highlighted positions define string "bacaba".Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!

The first line contains integer n (2 ≤ n ≤ 105) — the number of vertices of Polycarpus's tree. Next n - 1 lines contain the tree edges. The i-th of them contains number pi + 1 and string si + 1 (1 ≤ pi + 1 ≤ n; pi + 1 ≠ (i + 1)). String si + 1 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2. It is guaranteed that the input contains at most 3·105 English letters.

Print a single integer — the required number. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
aba

7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
bacaba

NoteIn the first test case string "aba" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down.

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

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

alias Tuple !(int, "v", string, "s") edge;

edge a [] [];
string s;
int [] p;

int go (int v, int r)
{
	int res = 0;
	foreach (e; a[v])
	{
		int k = r;
		foreach (c; e.s)
		{
			while (k >= 0 && c != s[k])
			{
				k = p[k];
			}
			k++;
			if (k == s.length)
			{
				res++;
				k = p[k];
			}
		}
		res += go (e.v, k);
	}
	return res;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		a = new edge [] [n];
		foreach (i; 1..n)
		{
			int v;
			readf (" %s ", &v);
			v--;
			auto t = readln ().strip ();
			a[v] ~= edge (i, t);
		}
		s = readln ().strip ();
		p = kmp (s);
		writeln (go (0, 0));
	}
}


A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.

The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai < bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.

If the required division into teams doesn't exist, print number -1. Otherwise, print  lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team.  If there are multiple answers, you are allowed to print any of them.

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new bool [] [] (n, n);
		foreach (i; 0..n)
		{
			a[i][i] = true;
		}
		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--; v--;
			a[u][v] = a[v][u] = true;
		}
		foreach (k; 0..n)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..n)
				{
					a[i][j] |= a[i][k] && a[k][j];
				}
			}
		}

		auto d = new int [n];
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				if (a[i][j])
				{
					d[i]++;
				}
			}
		}

		RedBlackTree !(int) [int] x;
		foreach (i; 0..n + 1)
		{
			x[i] = redBlackTree !(int) ();
		}
		foreach (i; 0..n)
		{
			debug {writeln (d[i]);}
			x[d[i]].insert (i);
		}

		bool ok = true;
		ok &= (x[1].length + x[2].length + x[3].length == n);
		ok &= (x[2].length <= x[1].length * 2);

		int [] [] ans;
		if (ok)
		{
			debug {writefln ("%s %s %s", x[1].length, x[2].length,
			                 x[3].length);}
			while (x[3].length > 0)
			{
				int c = x[3].front ();
				int [] cur;
				foreach (i; 0..n)
				{
					if (a[c][i])
					{
						cur ~= i;
						x[3].removeKey (i);
					}
				}
				ans ~= cur;
			}

			debug {writefln ("%s %s %s", x[1].length, x[2].length,
			                 x[3].length);}
			while (x[2].length > 0)
			{
				int c = x[2].front ();
				int [] cur;
				foreach (i; 0..n)
				{
					if (a[c][i])
					{
						cur ~= i;
						x[2].removeKey (i);
					}
				}
				cur ~= x[1].front ();
				x[1].removeFront ();
				ans ~= cur;
			}

			debug {writefln ("%s %s %s", x[1].length, x[2].length,
			                 x[3].length);}
			while (x[1].length > 0)
			{
				int [] cur;
				foreach (i; 0..3)
				{
					cur ~= x[1].front ();
					x[1].removeFront ();
				}
				ans ~= cur;
			}
		}

		if (ok)
		{
			foreach (ref c; ans)
			{
				c[] += 1;
			}
			writefln ("%(%(%s %)\n%)", ans);
		}
		else
		{
			writeln (-1);
		}
	}
}

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new bool [] [] (n, n);
		foreach (i; 0..n)
		{
			a[i][i] = true;
		}
		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--; v--;
			a[u][v] = a[v][u] = true;
		}
		foreach (k; 0..n)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..n)
				{
					a[i][j] |= a[i][k] && a[k][j];
				}
			}
		}

		auto d = new int [n];
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				if (a[i][j])
				{
					d[i]++;
				}
			}
		}

		RedBlackTree !(int) [int] x;
		foreach (i; 0..n + 1)
		{
			x[i] = redBlackTree !(int) ();
		}
		foreach (i; 0..n)
		{
			debug {writeln (d[i]);}
			x[d[i]].insert (i);
		}

		bool ok = true;
		ok &= (x[1].length + x[2].length + x[3].length == n);
		ok &= (x[2].length <= x[1].length);

		int [] [] ans;
		if (ok)
		{
			foreach (c; x[3])
			{
				int [] cur;
				foreach (i; 0..n)
				{
					if (a[c][i])
					{
						cur ~= i;
						if (i != c)
						{
							x[3].removeKey (i);
						}
					}
				}
				ans ~= cur;
			}

			foreach (c; x[2])
			{
				int [] cur;
				foreach (i; 0..n)
				{
					if (a[c][i])
					{
						cur ~= i;
						if (i != c)
						{
							x[2].removeKey (i);
						}
					}
				}
				cur ~= x[1].front ();
				x[1].removeFront ();
				ans ~= cur;
			}

			while (x[1].length > 0)
			{
				int [] cur;
				foreach (i; 0..3)
				{
					cur ~= x[1].front ();
					x[1].removeFront ();
				}
				ans ~= cur;
			}
		}

		if (ok)
		{
			foreach (ref c; ans)
			{
				c[] += 1;
			}
			writefln ("%(%(%s %)\n%)", ans);
		}
		else
		{
			writeln (-1);
		}
	}
}


Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.

The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.

The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.

NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.

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

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


This is the hard version of the problem. The difference is that in this version the array contains zeros. You can make hacks only if both versions of the problem are solved.You are given an array $$$[a_1, a_2, \ldots a_n]$$$ consisting of integers $$$-1$$$, $$$0$$$ and $$$1$$$. You have to build a partition of this array into the set of segments $$$[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]$$$ with the following property:  Denote the alternating sum of all elements of the $$$i$$$-th segment as $$$s_i$$$: $$$s_i$$$ = $$$a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \ldots \pm a_{r_i}$$$. For example, the alternating sum of elements of segment $$$[2, 4]$$$ in array $$$[1, 0, -1, 1, 1]$$$ equals to $$$0 - (-1) + 1 = 2$$$.  The sum of $$$s_i$$$ over all segments of partition should be equal to zero. Note that each $$$s_i$$$ does not have to be equal to zero, this property is about sum of $$$s_i$$$ over all segments of partition.The set of segments $$$[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]$$$ is called a partition of the array $$$a$$$ of length $$$n$$$ if $$$1 = l_1 \le r_1, l_2 \le r_2, \ldots, l_k \le r_k = n$$$ and $$$r_i + 1 = l_{i+1}$$$ for all $$$i = 1, 2, \ldots k-1$$$. In other words, each element of the array must belong to exactly one segment.You have to build a partition of the given array with properties described above or determine that such partition does not exist.Note that it is not required to minimize the number of segments in the partition.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$-1$$$, $$$0$$$, or $$$1$$$) — the elements of the given array. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.

For each test case print an integer $$$k$$$ — the number of segments in the partition. If required partition does not exist, print $$$-1$$$. If partition exists, in the $$$i$$$-th of the following $$$k$$$ lines print two integers $$$l_i$$$ and $$$r_i$$$ — description of the $$$i$$$-th segment. The following conditions should be satisfied:   $$$l_i \le r_i$$$ for each $$$i$$$ from $$$1$$$ to $$$k$$$.  $$$l_{i + 1} = r_i + 1$$$ for each $$$i$$$ from $$$1$$$ to $$$(k - 1)$$$.  $$$l_1 = 1, r_k = n$$$.  If there are multiple correct partitions of the array, print any of them.

NoteIn the first test case we can build a partition of $$$4$$$ segments — each of them will contain only one element of the array equals to $$$0$$$. So the sum will be equal to $$$0 + 0 + 0 + 0 = 0$$$.In the second test case we can build a partition of $$$4$$$ segments. The alternating sum of the first segment will be equal to $$$-1$$$, the alternating sum of the second segment will be equal to $$$1$$$, of the third segment — $$$0 - 1 + 0 = -1$$$, of the fourth segment — $$$1 - 0 = 1$$$. The sum will be equal to $$$-1 + 1 -1 + 1 = 0$$$.In the third test case it can be proved that the required partition does not exist.

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)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		if (sum (a) % 2 != 0)
		{
			writeln (-1);
			continue;
		}
		auto b = a.enumerate.filter !(x => x.value != 0).array;
		b ~= typeof (b.front) (n, 0);
		int [] [] answer;
		if (b[0].index > 0)
		{
			answer ~= [0, b[0].index];
		}
		for (int i = 0; i + 2 < b.length; i += 2)
		{
			if (b[i].value == b[i + 1].value)
			{
				if ((b[i].index & 1) != (b[i + 1].index & 1))
				{
					answer ~= [b[i].index, b[i + 2].index];
				}
				else
				{
					answer ~= [b[i].index, b[i + 1].index - 1];
					answer ~= [b[i + 1].index - 1, b[i + 2].index];
				}
			}
			else
			{
				answer ~= [b[i].index, b[i + 1].index];
				answer ~= [b[i + 1].index, b[i + 2].index];
			}
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line[0] + 1, " ", line[1]);
		}
	}
}

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

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

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

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

int N;
int[] A;

int[] solve() {
  const sumA = A.sum;
  if (sumA % 2 != 0) {
    return null;
  }

  auto fs = new bool[N];
  bool greedy(int a, int k) {
    foreach (i; 0 .. N) {
      if (i == 0 || fs[i - 1]) {
        continue;
      }
      if (A[i] == a && k > 0) {
        fs[i] = true;
        --k;
      }
    }
    return (k == 0);
  }
  if (sumA >= 0) {
    if (!greedy(+1, sumA / 2)) return null;
  } else {
    if (!greedy(-1, -sumA / 2)) return null;
  }
  debug {
    writeln("fs = ", fs);
  }

  int[] cuts;
  cuts ~= 0;
  foreach (i; 1 .. N) {
    if (fs[i - 1] == fs[i]) {
      assert(!fs[i]);
      cuts ~= i;
    }
  }
  cuts ~= N;
  return cuts;
}

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

        const ans = solve;
        debug {
          writeln(A, ": ", ans);
        }
        const len = cast(int)(ans.length) - 1;
        if (len >= 0) {
          writeln(len);
          foreach (i; 0 .. len) {
            writeln(ans[i] + 1, " ", ans[i + 1]);
          }
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

bool solve(int[] a, int sum, ref Tuple!(int, int)[] ans)
{
  if (a.length == 0)
    return sum == 0;

  if (sum == 0) {
    ans ~= tuple(cast(int)a.length, cast(int)a.length);
    return solve(a[0 .. $ - 1], sum, ans);
    return true;
  }

  if (sum < 0) {
    if (a.length >= 2 && a[$ - 1] < 0) {
      ans ~= tuple(cast(int)a.length - 1, cast(int)a.length);
      return solve(a[0 .. $ - 2], sum - 2 * a[$ - 1], ans);
    } else {
      ans ~= tuple(cast(int)a.length, cast(int)a.length);
      return solve(a[0 .. $ - 1], sum, ans);
    }
  } else {
    if (a.length >= 2 && a[$ - 1] > 0) {
      ans ~= tuple(cast(int)a.length - 1, cast(int)a.length);
      return solve(a[0 .. $ - 2], sum - 2 * a[$ - 1], ans);
    } else {
      ans ~= tuple(cast(int)a.length, cast(int)a.length);
      return solve(a[0 .. $ - 1], sum, ans);
    }
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    Tuple!(int, int)[] ans;
    if (solve(a, a.sum, ans)) {
      ans.reverse;
      writeln(ans.length);
      foreach (x; ans) {
        writefln("%d %d", x[0], x[1]);
      }
    } else {
      writeln(-1);
    }
  }
}

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)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		if (sum (a) % 2 != 0)
		{
			writeln (-1);
			continue;
		}
		if (!any (a))
		{
			writeln (1);
			writeln (1, " ", n);
			continue;
		}
		auto b = a.enumerate.filter !(x => x.value != 0).array;
		b ~= typeof (b.front) (n, 0);
		int [] [] answer;
		for (int i = 0; i + 2 < b.length; i += 2)
		{
			if (b[i].value == b[i + 1].value)
			{
				if ((b[i].index & 1) != (b[i + 1].index & 1))
				{
					answer ~= [b[i].index, b[i + 2].index];
				}
				else
				{
					answer ~= [b[i].index, b[i + 1].index - 1];
					answer ~= [b[i + 1].index - 1, b[i + 2].index];
				}
			}
			else
			{
				answer ~= [b[i].index, b[i + 1].index];
				answer ~= [b[i + 1].index, b[i + 2].index];
			}
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line[0] + 1, " ", line[1]);
		}
	}
}

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)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		if (sum (a) % 2 != 0)
		{
			writeln (-1);
			continue;
		}
		if (!any (a))
		{
			writeln (1);
			writeln (1, " ", n);
			continue;
		}
		auto b = a.enumerate.filter !(x => x.value != 0).array;
		b ~= typeof (b.front) (n, 0);
		int [] [] answer;
		for (int i = 0; i + 2 < b.length; i += 2)
		{
			if (b[i].value == b[i + 1].value)
			{
				answer ~= [b[i].index, b[i + 2].index];
			}
			else
			{
				answer ~= [b[i].index, b[i + 1].index];
				answer ~= [b[i + 1].index, b[i + 2].index];
			}
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line[0] + 1, " ", line[1]);
		}
	}
}

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

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

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

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

int N;
int[] A;

int[] solve() {
  const sumA = A.sum;
  if (sumA % 2 != 0) {
    return null;
  }

  auto fs = new bool[N];
  bool greedy(int a, int k) {
    foreach (i; 0 .. N) {
      if (i > 0 && fs[i - 1]) {
        continue;
      }
      if (A[i] == a && k > 0) {
        fs[i] = true;
        --k;
      }
    }
    return (k == 0);
  }
  if (sumA >= 0) {
    if (!greedy(+1, sumA / 2)) return null;
  } else {
    if (!greedy(-1, -sumA / 2)) return null;
  }

  int[] cuts;
  cuts ~= 0;
  foreach (i; 1 .. N) {
    if (fs[i - 1] == fs[i]) {
      assert(!fs[i]);
      cuts ~= i;
    }
  }
  cuts ~= N;
  return cuts;
}

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

        const ans = solve;
        debug {
          writeln(A, ": ", ans);
        }
        const len = cast(int)(ans.length) - 1;
        if (len >= 0) {
          writeln(len);
          foreach (i; 0 .. len) {
            writeln(ans[i] + 1, " ", ans[i + 1]);
          }
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}


Mihai has an $$$8 \times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked.     An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 36$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.

For each test case, output two integers $$$r$$$ and $$$c$$$ ($$$2 \leq r, c \leq 7$$$) — the row and column of the bishop.  The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.

NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row $$$4$$$ and column $$$3$$$, the correct output is 4 3.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan!string(8);

      auto x = 8.iota.filter!(x => S.map!(s => s[x]).canFind("#.#")).array;
      auto y = 8.iota.filter!(y => S[y].canFind("#.#")).array;
      return [y[0] + 2, x[0] + 2].toAnswerString;
    }

    foreach(i; 0..QN) {
      outputForAtCoder(&subSolve);
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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"];

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


You are given a positive integer $$$D$$$. Let's build the following graph from it:   each vertex is a divisor of $$$D$$$ (not necessarily prime, $$$1$$$ and $$$D$$$ itself are also included);  two vertices $$$x$$$ and $$$y$$$ ($$$x > y$$$) have an undirected edge between them if $$$x$$$ is divisible by $$$y$$$ and $$$\frac x y$$$ is a prime;  the weight of an edge is the number of divisors of $$$x$$$ that are not divisors of $$$y$$$. For example, here is the graph for $$$D=12$$$:   Edge $$$(4,12)$$$ has weight $$$3$$$ because $$$12$$$ has divisors $$$[1,2,3,4,6,12]$$$ and $$$4$$$ has divisors $$$[1,2,4]$$$. Thus, there are $$$3$$$ divisors of $$$12$$$ that are not divisors of $$$4$$$ — $$$[3,6,12]$$$.There is no edge between $$$3$$$ and $$$2$$$ because $$$3$$$ is not divisible by $$$2$$$. There is no edge between $$$12$$$ and $$$3$$$ because $$$\frac{12}{3}=4$$$ is not a prime.Let the length of the path between some vertices $$$v$$$ and $$$u$$$ in the graph be the total weight of edges on it. For example, path $$$[(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)]$$$ has length $$$1+2+2+3+1+2=11$$$. The empty path has length $$$0$$$.So the shortest path between two vertices $$$v$$$ and $$$u$$$ is the path that has the minimal possible length.Two paths $$$a$$$ and $$$b$$$ are different if there is either a different number of edges in them or there is a position $$$i$$$ such that $$$a_i$$$ and $$$b_i$$$ are different edges.You are given $$$q$$$ queries of the following form:   $$$v$$$ $$$u$$$ — calculate the number of the shortest paths between vertices $$$v$$$ and $$$u$$$. The answer for each query might be large so print it modulo $$$998244353$$$.

The first line contains a single integer $$$D$$$ ($$$1 \le D \le 10^{15}$$$) — the number the graph is built from. The second line contains a single integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le D$$$). It is guaranteed that $$$D$$$ is divisible by both $$$v$$$ and $$$u$$$ (both $$$v$$$ and $$$u$$$ are divisors of $$$D$$$).

Print $$$q$$$ integers — for each query output the number of the shortest paths between the two given vertices modulo $$$998244353$$$.

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

immutable int limit = 100;
immutable int mod = 998_244_353;
alias Pair = Tuple !(long, q{p}, int, q{q});

void main ()
{
	auto c = new int [] [] (limit, limit);
	foreach (i; 0..limit)
	{
		c[i][0] = 1;
		foreach (j; 1..i + 1)
		{
			c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
		}
	}

	long n;
	while (readf !(" %s") (n) > 0)
	{
		Pair [] f;
		for (long d = 2; d * d <= n; d++)
		{
			if (n % d == 0)
			{
				int q = 0;
				do
				{
					n /= d;
					q += 1;
				}
				while (n % d == 0);
				f ~= Pair (d, q);
			}
		}
		if (n > 1)
		{
			f ~= Pair (n, 1);
		}

		auto divs = f.length.to !(int);
		int [] [long] s;
		auto cur = new int [divs];

		void recur (int pos, long product)
		{
			if (pos >= divs)
			{
				s[product] = cur.dup;
				return;
			}
			foreach (i; 0..f[pos].q + 1)
			{
				recur (pos + 1, product);
				product *= f[pos].p;
				cur[pos] += 1;
			}
			cur[pos] = 0;
		}

		recur (0, 1);

		int solve (int [] x, int [] y)
		{
			int res = 1;
			int total = 0;
			foreach (i; 0..divs)
			{
				int cur = x[i] - y[i];
				total += cur;
				res = (res * 1L * c[total][cur]) % mod;
			}
			return res;
		}

		int q;
		readf !(" %s") (q);
		foreach (r; 0..q)
		{
			long v, u;
			readf !(" %s %s") (v, u);

			auto x = s[u];
			auto y = s[v];
			auto z = new int [divs];
			foreach (i; 0..divs)
			{
				z[i] = min (x[i], y[i]);
			}
			int one = solve (x, z);
			int two = solve (y, z);
			writeln ((one * 1L * two) % mod);
		}
	}
}


There is a square of size $$$10^6 \times 10^6$$$ on the coordinate plane with four points $$$(0, 0)$$$, $$$(0, 10^6)$$$, $$$(10^6, 0)$$$, and $$$(10^6, 10^6)$$$ as its vertices.You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n, m \le 10^5$$$) — the number of horizontal segments and the number of vertical segments. The next $$$n$$$ lines contain descriptions of the horizontal segments. The $$$i$$$-th line contains three integers $$$y_i$$$, $$$lx_i$$$ and $$$rx_i$$$ ($$$0 < y_i < 10^6$$$; $$$0 \le lx_i < rx_i \le 10^6$$$), which means the segment connects $$$(lx_i, y_i)$$$ and $$$(rx_i, y_i)$$$. The next $$$m$$$ lines contain descriptions of the vertical segments. The $$$i$$$-th line contains three integers $$$x_i$$$, $$$ly_i$$$ and $$$ry_i$$$ ($$$0 < x_i < 10^6$$$; $$$0 \le ly_i < ry_i \le 10^6$$$), which means the segment connects $$$(x_i, ly_i)$$$ and $$$(x_i, ry_i)$$$. It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.

Print the number of pieces the square is divided into after drawing all the segments.

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

immutable int limit = 10 ^^ 6;

alias Segment = Tuple !(int, q{y}, int, q{xLo}, int, q{xHi});
enum Type {start, cross, finish};
alias Event = Tuple !(int, q{y}, Type, q{type}, int, q{id});

auto solve (Segment [] a, Segment [] b)
{
	Event [] e;
	foreach (int i, ref c; a)
	{
		e ~= Event (c.y, Type.cross, i);
	}
	foreach (int i, ref c; b)
	{
		e ~= Event (c.xLo, Type.start, i);
	}
	foreach (int i, ref c; b)
	{
		e ~= Event (c.xHi, Type.finish, i);
	}
	sort (e);

	auto t = new int [limit + 2];

	void act (int pos, int delta)
	{
		for (pos += 1; pos < limit + 2; pos += pos & -pos)
		{
			t[pos] += delta;
		}
	}

	int num (int pos)
	{
		int res = 0;
		for (pos += 1; pos > 0; pos -= pos & -pos)
		{
			res += t[pos];
		}
		return res;
	}

	long res = 0;
	foreach (ref event; e)
	{
		final switch (event.type)
		{
			case Type.start:
				act (b[event.id].y, +1);
				break;
			case Type.cross:
				auto cur = num (a[event.id].xHi) -
				    num (a[event.id].xLo - 1);
				res += cur - 1;
				break;
			case Type.finish:
				act (b[event.id].y, -1);
				break;
		}
	}
	debug {writeln ("res = ", res);}
	return res;
}

void main ()
{
	int h, v;
	while (readf !(" %s %s") (h, v) > 0)
	{
		auto readSegments (int n)
		{
			auto res = new Segment [n];
			foreach (ref c; res)
			{
				readf !(" %s %s %s") (c.y, c.xLo, c.xHi);
			}
			res ~= Segment (0, 0, limit);
			res ~= Segment (limit, 0, limit);
			sort (res);
			return res;
		}

		auto a = readSegments (h);
		auto b = readSegments (v);

		auto x = solve (a, b);
		auto y = solve (b, a);
		auto z = x + h;
		writeln (x + y - z - 1);
	}
}


You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples:   if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$;  if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$) — the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.

// Vicfred
// https://codeforces.com/contest/1430/problem/B
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int t = readln.chomp.to!int;

    while(t--) {
        int n, k;
        readf("%s %s\n", &n, &k);

        long[] a = readln.split.map!(to!long).array;

        a.sort;
        a.reverse;

        long ans = 0L;
        for(int i = 0; i <= k; ++i)
            ans += a[i];

        ans.writeln;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 1..min(k+1, n))
		{
			a[0] += a[i];
		}
		ans[ti] = a[0];
	}

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


An integer array $$$a_1, a_2, \ldots, a_n$$$ is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array:   Choose any number $$$x$$$ from the array $$$a$$$, and any letter of the English alphabet $$$y$$$.  Replace all occurrences of number $$$x$$$ with the letter $$$y$$$. For example, if we initially had an array $$$a = [2, 3, 2, 4, 1]$$$, then we could transform it the following way:  Choose the number $$$2$$$ and the letter c. After that $$$a = [c, 3, c, 4, 1]$$$.  Choose the number $$$3$$$ and the letter a. After that $$$a = [c, a, c, 4, 1]$$$.  Choose the number $$$4$$$ and the letter t. After that $$$a = [c, a, c, t, 1]$$$.  Choose the number $$$1$$$ and the letter a. After that $$$a = [c, a, c, t, a]$$$. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array $$$a$$$ and the string $$$s$$$ determine if the string $$$s$$$ could be got from the array $$$a$$$ after the described transformation?

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the array $$$a$$$ and the string $$$s$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$) — the elements of the array $$$a$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.

For each test case, output "YES", if we can get the string $$$s$$$ from the array $$$a$$$, and "NO" otherwise. You can output each letter in any case.

NoteThe first test case corresponds to the sample described in the statement.In the second test case we can choose the number $$$50$$$ and the letter a.In the third test case we can choose the number $$$11$$$ and the letter a, after that $$$a = [a, 22]$$$. Then we choose the number $$$22$$$ and the letter b and get $$$a = [a, b]$$$.In the fifth test case we can change all numbers one by one to the letter a.

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 solve() {
    int n = read!int;
    auto a = readarray!int;
    auto s = readln.strip;
    dchar[int] dict;
    foreach (tup; zip(a, s))
    {
        if (tup[0] in dict)
            if (dict[tup[0]] != tup[1]) {
                writeln("NO");
                return;
            }
        dict[tup[0]] = tup[1];
    }
    writeln("YES");
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array;
    auto s = readln.strip;
    char[int] m;
    bool good = true;
    foreach (i ; 0 .. a.length) {
      if (a[i] in m) {
        if (m[a[i]] != s[i]) {
          good = false;
          break;
        }
      } else {
        m[a[i]] = s[i];
      }
    }
    writeln(good ? "YES" : "NO");
  }
}


There are $$$n$$$ people in a row. The height of the $$$i$$$-th person is $$$a_i$$$. You can choose any subset of these people and try to arrange them into a balanced circle.A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than $$$1$$$. For example, let heights of chosen people be $$$[a_{i_1}, a_{i_2}, \dots, a_{i_k}]$$$, where $$$k$$$ is the number of people you choose. Then the condition $$$|a_{i_j} - a_{i_{j + 1}}| \le 1$$$ should be satisfied for all $$$j$$$ from $$$1$$$ to $$$k-1$$$ and the condition $$$|a_{i_1} - a_{i_k}| \le 1$$$ should be also satisfied. $$$|x|$$$ means the absolute value of $$$x$$$. It is obvious that the circle consisting of one person is balanced.Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of people. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the height of the $$$i$$$-th person.

In the first line of the output print $$$k$$$ — the number of people in the maximum balanced circle. In the second line print $$$k$$$ integers $$$res_1, res_2, \dots, res_k$$$, where $$$res_j$$$ is the height of the $$$j$$$-th person in the maximum balanced circle. The condition $$$|res_{j} - res_{j + 1}| \le 1$$$ should be satisfied for all $$$j$$$ from $$$1$$$ to $$$k-1$$$ and the condition $$$|res_{1} - res_{k}| \le 1$$$ should be also satisfied.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		a ~= int.max;
		auto b = group (a);
		debug {writeln (b);}

		int [] res;
		int [] cur;
		int prev = int.min;
		int total = 0;
		foreach (ref g; b)
		{
			auto value = g[0];
			auto amount = g[1].to !(int);

			if (prev + 1 < value)
			{
				if (res.length < cur.length)
				{
					res = cur;
				}
				cur = null;
			}

			if (amount == 1)
			{
				cur ~= value;
				if (res.length < cur.length)
				{
					res = cur;
				}
				cur = [value];
			}
			else
			{
				cur ~= value.repeat (amount).array;
			}

			prev = value;
		}

		int [] temp;
		int [] add;
		int last = res.front;
		foreach (ref x; res)
		{
			if (last < x)
			{
				add ~= x;
				last = x;
			}
			else
			{
				temp ~= x;
			}
		}
		reverse (add);
		res = temp ~ add;

		writeln (res.length);
		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 read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int n = read.to!int;

	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;
	log("as:", as);
	int amax = -1;
	foreach(a; as) amax = max(amax, a);

	int[] acount = new int[](amax + 1);
	foreach(a; as) acount[a] += 1;
	log("acount:", acount);

	int l, r, sum;
	int bestl = 0, bestr = -1, bestsum = 0;
	int s = 0; // 0=not selecting, 1=selecting
	foreach(i; 0 .. amax + 1){
		if(s == 0){
			if(acount[i] == 0) continue;
			if(acount[i] >= 1){
				sum = acount[i];
				s = 1;
				l = r = i;
				if(sum > bestsum) bestl = l, bestr = r, bestsum = sum;
			}
		}
		else{
			sum += acount[i];
			r = i;
			if(sum > bestsum) bestl = l, bestr = r, bestsum = sum;
			if(acount[i] == 0) s = 0;
			if(acount[i] == 1){
				sum = acount[i];
				s = 1;
				l = r = i;
			}
		}
		log("i:", i, "l:", l, "r:", r, "sum:", sum, "bestl:", bestl, "bestr:", bestr, "bestsum:", bestsum);
	}

	int[] ans;
	foreach(i; bestl .. bestr + 1) ans ~= i, acount[i] -= 1;

	foreach_reverse(i; bestl .. bestr + 1) while(acount[i] > 0) ans ~= i, acount[i] -= 1;

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

}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int n = read.to!int;

	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;
	log("as:", as);
	int amax = -1;
	foreach(a; as) amax = max(amax, a);

	int[] acount = new int[](amax + 1);
	foreach(a; as) acount[a] += 1;
	log("acount:", acount);

	int l, r, sum;
	int bestl = 0, bestr = -1, bestsum = 0;
	int s = 0; // 0=not selecting, 1=selecting
	foreach(i; 0 .. amax + 1){
		if(acount[i] == 0){
			s = 0, sum = 0;
			l = i + 1;
		}
		else if(acount[i] == 1){
			if(s == 0){
				l = r = i, sum += acount[i];
				if(sum > bestsum) bestr = r, bestl = l, bestsum = sum;
				s = 1, sum = 1;
				l = r = i;
			}
			else{
				r = i, sum += acount[i];
				if(sum > bestsum) bestr = r, bestl = l, bestsum = sum;
				s = 0, sum = 0;
				l = i + 1;
			}
		}
		else{
			if(s == 0) s = 1;
			r = i, sum += acount[i];
			if(sum > bestsum) bestr = r, bestl = l, bestsum = sum;
		}
		log("i:", i, "l:", l, "r:", r, "sum:", sum, "bestl:", bestl, "bestr:", bestr, "bestsum:", bestsum);
	}

	int[] ans;
	foreach(i; bestl .. bestr + 1) ans ~= i, acount[i] -= 1;

	foreach_reverse(i; bestl .. bestr + 1) while(acount[i] > 0) ans ~= i, acount[i] -= 1;

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

}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int n = read.to!int;

	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;
	log("as:", as);
	int amax = -1;
	foreach(a; as) amax = max(amax, a);

	int[] acount = new int[](amax + 1);
	foreach(a; as) acount[a] += 1;
	log("acount:", acount);

	int l, r, sum;
	int bestl = 0, bestr = -1, bestsum = 0;
	int s = 0; // 0=not selecting, 1=selecting
	foreach(i; 0 .. amax + 1){
		if(acount[i] == 0){
			s = 0, sum = 0;
			l = i + 1;
		}
		else if(acount[i] == 1){
			if(s == 0){
				l = r = i, sum += acount[i];
				if(sum > bestsum) bestr = r, bestl = l, bestsum = sum;
				s = 1, sum = 1;
				l = r = i;
			}
			else{
				r = i, sum += acount[i];
				if(sum > bestsum) bestr = r, bestl = l, bestsum = sum;
				s = 0, sum = 0;
				l = i + 1;
			}
		}
		else{
			if(s == 0) s = 1;
			r = i, sum += acount[i];
			if(sum > bestsum) bestr = r, bestl = l, bestsum = sum;
		}
		log("i:", i, "l:", l, "r:", r, "sum:", sum, "bestl:", bestl, "bestr:", bestr, "bestsum:", bestsum);
	}

	int[] ans;
	foreach(i; bestl .. bestr + 1) ans ~= i, acount[i] -= 1;

	foreach_reverse(i; bestl .. bestr + 1) while(acount[i] > 0) ans ~= i, acount[i] -= 1;

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

}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int n = read.to!int;

	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;
	log("as:", as);
	int amax = -1;
	foreach(a; as) amax = max(amax, a);

	int[] acount = new int[](amax + 1);
	foreach(a; as) acount[a] += 1;
	log("acount:", acount);

	int l, r, sum;
	int bestl = 0, bestr = -1, bestsum = 0;
	int s = 0; // 0=not selecting, 1=selecting
	foreach(i; 0 .. amax + 1){
		if(s == 0){
			if(acount[i] == 0) continue;
			if(acount[i] >= 1){
				sum = acount[i];
				s = 1;
				l = r = i;
				if(sum > bestsum) bestl = l, bestr = r, bestsum = sum;
			}
		}
		else{
			sum += acount[i];
			r = i;
			if(sum > bestsum) bestl = l, bestr = r, bestsum = sum;
			if(acount[i] <= 1) s = 0;
		}
		log("i:", i, "l:", l, "r:", r, "sum:", sum, "bestl:", bestl, "bestr:", bestr, "bestsum:", bestsum);
	}

	int[] ans;
	foreach(i; bestl .. bestr + 1) ans ~= i, acount[i] -= 1;

	foreach_reverse(i; bestl .. bestr + 1) while(acount[i] > 0) ans ~= i, acount[i] -= 1;

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

}


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

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

void main() {
  int n = readln().strip().to!int;
  int[] a = new int[n];
  foreach (i; 0..n) {
    a[i] = readln().strip().removechars(" ").to!int;
  }
  bool[int] initial;
  bool[int] s;
  foreach (k; a) {
    if (k < 0) {
      k = -k;
      if (k in s) {
        s.remove(k);
      } else {
        initial[k] = true;
      }
    } else {
      s[k] = true;
    }
  }
  s = initial;
  int ans = cast(int)s.length;
  foreach (k; a) {
    if (k < 0) {
      k = -k;
      s.remove(k);
    } else {
      s[k] = true;
    }
    ans = max(ans, cast(int)s.length);
  }
  writeln(ans);
}


There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.

The first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≤ ai ≤ 100 000), the elements of the array.

Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.

NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.

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

  int n, x; rd(n, x);
  auto a=readln.split.to!(int[]);

  int[int] bef, aft;
  foreach(e; a){
    if(e in bef) bef[e]++;
    else bef[e]=1;
    if ((e&x) in aft) aft[e&x]++;
    else aft[e&x]=1;
  }
  int mn=3;
  foreach(e; a){
    if(bef[e]>1) mn=0;
    else{
      bef[e]--;
      if(((e&x) in bef) && bef[e&x]>0) mn=min(mn, 1);
      if(aft[e&x]>1) mn=min(mn, 2);
      bef[e]++;
    }
  }
  if(mn>2) writeln(-1);
  else writeln(mn);
}

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

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

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

    int[int] cnt;
    readln.chomp.split.map!(to!int).each!(v => ++cnt[v]);

    debug { cnt.writeln; }

    int ans = 3;
    bool [int] afterAnd;
    foreach (k, v; cnt) {
        if (v > 1) {
            ans = 0;
            break;
        }

        auto now = k & x;
        if (now != k && now in cnt) ans = min(ans, 1);
        else if (now in afterAnd) ans = min(ans, 2);

        afterAnd[now] = true;
    }

    if (ans == 3) ans = -1;

    ans.writeln;
}


Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps.  Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.

The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values.

Print the minimum number of steps in a single line.

NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.

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

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto d = new int [1000030];
		foreach (x; readln.split.map !(to !(int)))
		{
			d[x]++;
		}
		foreach (i; 0..d.length - 1)
		{
			d[i + 1] += d[i] >> 1;
			d[i] &= 1;
		}
		writeln (sum (d));
	}
}

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

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto d = new int [n + 30];
		foreach (x; readln.split.map !(to !(int)))
		{
			d[x]++;
		}
		foreach (i; 0..d.length - 1)
		{
			d[i + 1] += d[i] >> 1;
			d[i] &= 1;
		}
		writeln (sum (d));
	}
}


You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$:  Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \le i, j \le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$.  Select any arbitrary index $$$i$$$ ($$$1 \le i \le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.

Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.

NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: "100" $$$\to$$$ "000" $$$\to$$$ "001". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then "100" $$$\to$$$ "001", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as "0101" $$$\to$$$ "0011". The cost is $$$|2 - 3| = 1$$$.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.chomp;
    auto B = readln.chomp;
    long ans = 0;

    for (int i = 0; i < N; ++i) {
        if (A[i] == B[i]) continue;
        if (i == N - 1) {
            ans += 1;
        } else if (A[i+1] != B[i+1] && A[i] != A[i+1]) {
            ans += 1;
            i += 1;
        } else {
            ans += 1;
        }
    }

    ans.writeln;
}

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

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

    auto s = readln.chomp;
    auto t = readln.chomp;
    auto ans = 0;
    auto chg = false;
    foreach (i; 0 .. n) {
        if ((s[i] == t[i]) || (i > 0 && s[i-1] != s[i] && chg)) {
            chg = false;
            continue;
        }

        ++ans;
        chg = true;
    }

    ans.writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.strip;
		auto b = readln.strip;
		int res = 0;
		int pos = -1;
		char last = '*';
		foreach (i; 0..n)
		{
			if (a[i] != b[i])
			{
				res += 1;
				if (pos + 1 == i && last == b[i])
				{
					res -= 1;
				}
				else
				{
					pos = i;
					last = a[i];
				}
			}
		}
		writeln (res);
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.chomp;
    auto B = readln.chomp;
    long ans = 0;

    for (int i = 0; i < N; ++i) {
        if (A[i] != B[i]) {
            if (i == N - 1 || A[i+1] == B[i+1]) {
                ans += 1;
            } else {
                ans += 1;
                ++i;
            }
        }
    }

    ans.writeln;
}

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

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

    auto s = readln.chomp;
    auto t = readln.chomp;
    auto ans = 0;
    foreach (i; 0 .. n) {
        if (s[i] == t[i]) continue;
        if (i > 0 && s[i-1] != s[i] && s[i-1] != t[i-1]) continue;

        ++ans;
    }

    ans.writeln;
}


You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$"abca", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the length of $$$s$$$ and the number of tries correspondingly. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of each test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$) — the number of characters pressed right during the $$$i$$$-th try. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ both does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$). It is guaranteed that the answer for each letter does not exceed $$$2 \cdot 10^9$$$.

For each test case, print the answer — $$$26$$$ integers: the number of times you press the button 'a', the number of times you press the button 'b', $$$\dots$$$, the number of times you press the button 'z'.

3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4

NoteThe first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is $$$4$$$, 'b' is $$$2$$$ and 'c' is $$$2$$$.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is $$$9$$$, 'd' is $$$4$$$, 'e' is $$$5$$$, 'f' is $$$3$$$, 'o' is $$$9$$$, 'r' is $$$3$$$ and 's' is $$$1$$$.

module C;

import std.stdio : readln, write, writeln;

struct IO {
  import std.conv : to;
  import std.range : empty, front, popFront, split;

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

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

  string[] tokens;
}

void main() {
  IO io;
  int T = io.readInt;
  while (T--) {
    int n = io.readInt;
    int m = io.readInt;
    string s = io.readToken;
    long[] sum = new long[n];
    sum[n - 1]++;
    for (int i = 0; i < m; ++i) {
      sum[io.readInt - 1]++;
    }
    for (int i = n - 1; i--;) {
      sum[i] += sum[i + 1];
    }
    long[] count = new long[26];
    for (int i = 0; i < n; ++i) {
      count[s[i] - 'a'] += sum[i];
    }
    for (int i = 0; i < 26; ++i) {
      write(count[i], " \n"[i == 25]);
    }
  }
}

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

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

void solve(){
        foreach(_; 0 .. rint){
        int n = rint, m = rint;
        int[] as = readln.chomp.map!ctoi.array;
        int[] ps = rint(m).map!(x => x - 1).array;

        int[] us = new int[](n); // mistake just after position p (; 0 .. n)
        foreach(p; ps) us[p] += 1;

        int[] ans = new int[](26);
        int[] cs = new int[](26);
        foreach(i; 0 .. n){
            cs[as[i]] += 1;
            foreach(k; 0 .. 26) ans[k] += cs[k] * us[i];
        }

        foreach(k; 0 .. 26) ans[k] += cs[k];

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

}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t, 26);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto s = RD!string;
		auto p = RDA!int;
		auto cnt = new long[][](n+1, 26);
		foreach (i; 0..n)
		{
			auto num = s[i]-'a';
			cnt[i+1] = cnt[i].dup;
			++cnt[i+1][num];
		}
		foreach (i; 0..m)
		{
			ans[ti][] += cnt[p[i]][];
		}
		ans[ti][] += cnt[n][];
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}


There is a binary string $$$a$$$ of length $$$n$$$. In one operation, you can select any prefix of $$$a$$$ with an equal number of $$$0$$$ and $$$1$$$ symbols. Then all symbols in the prefix are inverted: each $$$0$$$ becomes $$$1$$$ and each $$$1$$$ becomes $$$0$$$.For example, suppose $$$a=0111010000$$$.   In the first operation, we can select the prefix of length $$$8$$$ since it has four $$$0$$$'s and four $$$1$$$'s: $$$[01110100]00\to [10001011]00$$$.  In the second operation, we can select the prefix of length $$$2$$$ since it has one $$$0$$$ and one $$$1$$$: $$$[10]00101100\to [01]00101100$$$.  It is illegal to select the prefix of length $$$4$$$ for the third operation, because it has three $$$0$$$'s and one $$$1$$$. Can you transform the string $$$a$$$ into the string $$$b$$$ using some finite number of operations (possibly, none)?

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 3\cdot 10^5$$$) — the length of the strings $$$a$$$ and $$$b$$$. The following two lines contain strings $$$a$$$ and $$$b$$$ of length $$$n$$$, consisting of symbols $$$0$$$ and $$$1$$$. The sum of $$$n$$$ across all test cases does not exceed $$$3\cdot 10^5$$$.

For each test case, output "YES" if it is possible to transform $$$a$$$ into $$$b$$$, or "NO" if it is impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is shown in the statement.In the second test case, we transform $$$a$$$ into $$$b$$$ by using zero operations.In the third test case, there is no legal operation, so it is impossible to transform $$$a$$$ into $$$b$$$.In the fourth test case, here is one such transformation:   Select the length $$$2$$$ prefix to get $$$100101010101$$$.  Select the length $$$12$$$ prefix to get $$$011010101010$$$.  Select the length $$$8$$$ prefix to get $$$100101011010$$$.  Select the length $$$4$$$ prefix to get $$$011001011010$$$.  Select the length $$$6$$$ prefix to get $$$100110011010$$$. In the fifth test case, the only legal operation is to transform $$$a$$$ into $$$111000$$$. From there, the only legal operation is to return to the string we started with, so we cannot transform $$$a$$$ into $$$b$$$.

// Vicfred
// https://codeforces.com/contest/1504/problem/B
// greedy
import std.stdio;

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

while(t--) {
    int n;
    readf("%s\n", &n);
    string a, b;
    readf("%s\n", &a);
    readf("%s\n", &b);

    a ~= '0';
    b ~= '0';

    int cumulative = 0;
    bool valid = true;
    for(uint i = 0; i < n; ++i) {
        if(a[i] == '0')
            cumulative += 1;
        else
            cumulative -= 1;
        if((a[i] == b[i]) != (a[i+1] == b[i+1]) && cumulative != 0) {
            valid = false;
            break;
        }
    }
    if(valid)
        "YES".writeln;
    else
        "NO".writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new long[](n+1);
		foreach (i; 0..n)
		{
			cnt[i+1] = cnt[i];
			if (a[i] == '1')
				++cnt[i+1];
			else
				--cnt[i+1];
		}

		bool ok = true;
		long inv;
		foreach_reverse (i; 0..n)
		{
			auto x = a[i]-'0';
			auto y = b[i]-'0';
			if ((x^inv) == y) continue;

			if (cnt[i+1] != 0)
			{
				debug writeln("i:", i);
				ok = false;
				break;
			}
			inv ^= 1;
		}
		ans[ti] = ok;
	}

	foreach (e; ans)
	{
		writeln(e ? "YES" : "NO");
	}
	stdout.flush;
	debug readln;
}

// Vicfred
// https://codeforces.com/contest/1504/problem/B
// greedy
import std.stdio;

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

while(t--) {
    int n;
    readf("%s\n", &n);
    string a, b;
    readf("%s\n", &a);
    readf("%s\n", &b);

    int cumulative = 0;
    bool valid = true;
    for(uint i = 0; i < n - 1; ++i) {
        if(a[i] == '0')
            cumulative += 1;
        else
            cumulative -= 1;
        if((a[i] == b[i]) != (a[i+1] == b[i+1]) && cumulative != 0) {
            valid = false;
            break;
        }
    }
    if(valid)
        "YES".writeln;
    else
        "NO".writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1504/problem/B
// greedy
import std.stdio;

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

while(t--) {
    int n;
    readf("%s\n", &n);
    string a, b;
    readf("%s\n", &a);
    readf("%s\n", &b);

    int cumulative = 0;
    bool valid = true;
    for(uint i = 0; i < n - 1; ++i) {
        if(a[i] == '0')
            cumulative += 1;
        else
            cumulative -= 1;
        if((a[i] == b[i]) && a[i+1] != b[i+1] && cumulative != 0) {
            valid = false;
            break;
        }
    }
    if(valid)
        "YES".writeln;
    else
        "NO".writeln;
}
}


Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions:   Length of the substring is at least $$$2$$$  'a' occurs strictly more times in this substring than 'b'  'a' occurs strictly more times in this substring than 'c'  Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^{5})$$$  — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \le n \le 10^{6})$$$  — the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting only of characters 'a', 'b' and 'c'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^{6}$$$.

For each test case, output the length of the smallest substring which satisfies the given conditions or print $$$-1$$$ if there is no such substring.

NoteConsider the first test case. In the substring "aa", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring "aa" satisfies the condition and the answer is $$$2$$$. The substring "a" also satisfies this condition, however its length is not at least $$$2$$$.In the second test case, it can be shown that in none of the substrings of "cbabb" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, "cacabccc", the length of the smallest substring that satisfies the conditions is $$$3$$$.

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

void solve(){
    auto n = scan!int;
    auto w = scan!(dchar[]);
    auto check = new long[n];
    int st = -1;
    for(int i = 0; i < n; ++i){
        if(w[i] == 'a'){
            st = i;
            break;
        }
    }
    if(st == -1){
        writeln(-1);
        return;
    }
    long cntb = 0, cntc = 0;
    ll res = 10;
    for(int i = st+1; i < n; ++i){
        if(w[i] == 'b'){
            ++cntb;
        }else if(w[i] == 'c'){
            ++cntc;
        }else{
            if(cntb <= 1 && cntc <= 1){
                res = min(2 + cntc + cntb, res);
            }
            if(cntb == 2 && !cntc){
                if(check[i-3] == 2){
                    res = min(7, res);
                }
                check[i] = 1;
            }else if(cntc == 2 && !cntb){
                if(check[i-3] == 1){
                    res = min(7, res);
                }
                check[i] = 2;
            }
            cntb = 0;
            cntc = 0;
        }
    }

    if(res > 9){
        writeln(-1);
    }else{
        writeln(res);
    }
}

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

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

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

void main() {
    int cases = to!int(strip(readln()));

    // per testcase
    for (int t = 0; t < cases; t++) {
        int n;
        readf!"%d\n"(n);

        string s;
        readf!"%s\n"(s);

        /*int best_left = 0;
        int best_right = 0;
        int best_value = int.max;
        int left = 0;
        int right = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == 'a') {
                left = right;
                right = i;

                int value = right - left - 1;
                if ((value < best_value && s[left] == 'a' && s[right] == 'a' && left != right) || (value == best_value && value == 2 && s[left+1] != s[left+2])) {
                    best_left = left;
                    best_right = right;
                    best_value = value;
                }
            }
        }

        // output cases
        if (best_value > 2) {
            writeln(-1);
        }
        else if (best_value == 2) {
            if (s[best_left+1] != s[best_left+2]) {
                writeln(4);
            } else writeln(-1);
        }
        else if (best_value == 1 || best_value == 0) {
            writeln(best_value+2);
        }
        else {
            writeln(-1);
        }*/
        int best = -1;

        for (int i = 0; i < n-1; i++) {
            if (s[i] == 'a' && s[i+1] == 'a') {
                best = 2;
            }
        }

        if (best == 2) {
            writeln(best);
            continue;
        }

        for (int i = 0; i < n-2; i++) {
            if (s[i] == 'a' && s[i+1] != 'a' && s[i+2] == 'a') {
                best = 3;
            }
        }

        if (best == 3) {
            writeln(best);
            continue;
        }

        for (int i = 0; i < n-3; i++) {
            if (s[i] == 'a' && s[i+1] != s[i+2] && s[i+3] == 'a') {
                best = 4;
            }
        }

        if (best == 4) {
            writeln(best);
            continue;
        }

        for (int i = 0; i < n-6; i++) {
            if (s[i] == 'a' && s[i+1] == s[i+2] && s[i+3] == 'a' && s[i+4] == s[i+5] && s[i+6] == 'a' && s[i+1] != s[i+4]) {
                best = 7;
            }
        }

        writeln(best);
    }
}

/*
cabbabbcbbcbcbababcbcbababbabcbcaaa

abcbbcbcbababbcbcbcbbbabbcbcbbabbcbcbcbabaabcbcbababca

abba 2
abbcbbcbcba vs abba -> abba 2
aba vs abba -> aba 1
abba vs aba -> aba 1
abcbca vs aba -> aba 1
aa vs aba -> aa 0 -> return

"aa" -> that
"aba"/"aca" -> ye
"abca"/"acba" -> ye*/

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

void solve(){
    auto n = scan!int;
    auto w = scan!(dchar[]);
    auto check = new long[n];
    int st = -1;
    for(int i = 0; i < n; ++i){
        if(w[i] == 'a'){
            st = i;
            break;
        }
    }
    if(st == -1){
        writeln(-1);
        return;
    }
    long cntb = 0, cntc = 0;
    ll res = 10;
    for(int i = st+1; i < n; ++i){
        if(w[i] == 'b'){
            ++cntb;
        }else if(w[i] == 'c'){
            ++cntc;
        }else{
            if(cntb <= 1 && cntc <= 1){
                res = min(2 + cntc + cntb, res);
            }
            if(cntb == 2){
                if(check[i-3] == 2){
                    res = min(7, res);
                }
                check[i] = 1;
            }else if(cntc == 2){
                if(check[i-3] == 1){
                    res = min(7, res);
                }
                check[i] = 2;
            }
            cntb = 0;
            cntc = 0;
        }
    }

    if(res > 9){
        writeln(-1);
    }else{
        writeln(res);
    }
}

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

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

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

void solve(){
    auto n = scan!int;
    auto w = scan!(dchar[]);
    auto check = new long[n];
    int st = -1;
    for(int i = 0; i < n; ++i){
        if(w[i] == 'a'){
            st = i;
            break;
        }
    }
    if(st == -1){
        writeln(-1);
        return;
    }
    long cntb = 0, cntc = 0;
    ll res = 10;
    for(int i = st+1; i < n; ++i){
        if(w[i] == 'b'){
            ++cntb;
        }else if(w[i] == 'c'){
            ++cntc;
        }else{
            if(cntb <= 1 && cntc <= 1){
                res = min(2 + cntc + cntb, res);
            }
            if(cntb == 2){
                if(check[i-3] == 2){
                    res = min(7, res);
                }
                check[i] = 1;
            }else if(cntc == 2){
                if(check[i-3] == 1){
                    res = min(7, res);
                }
                check[i] = 2;
            }
            cntb = 0;
            cntc = 0;
        }
    }

    if(res > 4){
        writeln(-1);
    }else{
        writeln(res);
    }
}

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

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

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

void solve(){
    auto n = scan!int;
    auto w = scan!(dchar[]);
    int st = -1;
    for(int i = 0; i < n; ++i){
        if(w[i] == 'a'){
            st = i;
            break;
        }
    }
    if(st == -1){
        writeln(-1);
        return;
    }
    long cntb = 0, cntc = 0;
    ll res = 10;
    for(int i = st+1; i < n; ++i){
        if(w[i] == 'b'){
            ++cntb;
        }else if(w[i] == 'c'){
            ++cntc;
        }else{
            if(cntb <= 1 && cntc <= 1){
                res = min(2 + cntc + cntb, res);
            }
            cntb = 0;
            cntc = 0;
        }
    }
    if(res > 4){
        writeln(-1);
    }else{
        writeln(res);
    }
}

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

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

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

void main() {
    int cases = to!int(strip(readln()));

    // per testcase
    for (int t = 0; t < cases; t++) {
        int n;
        readf!"%d\n"(n);

        string s;
        readf!"%s\n"(s);

        /*int best_left = 0;
        int best_right = 0;
        int best_value = int.max;
        int left = 0;
        int right = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == 'a') {
                left = right;
                right = i;

                int value = right - left - 1;
                if ((value < best_value && s[left] == 'a' && s[right] == 'a' && left != right) || (value == best_value && value == 2 && s[left+1] != s[left+2])) {
                    best_left = left;
                    best_right = right;
                    best_value = value;
                }
            }
        }

        // output cases
        if (best_value > 2) {
            writeln(-1);
        }
        else if (best_value == 2) {
            if (s[best_left+1] != s[best_left+2]) {
                writeln(4);
            } else writeln(-1);
        }
        else if (best_value == 1 || best_value == 0) {
            writeln(best_value+2);
        }
        else {
            writeln(-1);
        }*/
        int best = -1;

        for (int i = 0; i < n-1; i++) {
            if (s[i] == 'a' && s[i+1] == 'a') {
                best = 2;
            }
        }

        if (best == 2) {
            writeln(best);
            continue;
        }

        for (int i = 0; i < n-2; i++) {
            if (s[i] == 'a' && s[i+1] != 'a' && s[i+2] == 'a') {
                best = 3;
            }
        }

        if (best == 3) {
            writeln(best);
            continue;
        }

        for (int i = 0; i < n-3; i++) {
            if (s[i] == 'a' && s[i+1] != s[i+2] && s[i+3] == 'a') {
                best = 4;
            }
        }

        writeln(best);
    }
}

/*
cabbabbcbbcbcbababcbcbababbabcbcaaa

abcbbcbcbababbcbcbcbbbabbcbcbbabbcbcbcbabaabcbcbababca

abba 2
abbcbbcbcba vs abba -> abba 2
aba vs abba -> aba 1
abba vs aba -> aba 1
abcbca vs aba -> aba 1
aa vs aba -> aa 0 -> return

"aa" -> that
"aba"/"aca" -> ye
"abca"/"acba" -> ye*/

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

void main() {
    int cases = to!int(strip(readln()));

    // per testcase
    for (int t = 0; t < cases; t++) {
        int n;
        readf!"%d\n"(n);

        string s;
        readf!"%s\n"(s);

        int best_left = 0;
        int best_right = 0;
        int best_value = int.max;
        int left = 0;
        int right = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == 'a') {
                left = right;
                right = i;

                int value = right - left - 1;
                if ((value < best_value && s[left] == 'a' && s[right] == 'a' && left != right) || (value == best_value && value == 2 && s[left+1] != s[left+2])) {
                    best_left = left;
                    best_right = right;
                    best_value = value;
                }
            }
        }

        // output cases
        if (best_value > 2) {
            writeln(-1);
        }
        else if (best_value == 2) {
            if (s[best_left+1] != s[best_left+2]) {
                writeln(4);
            } else writeln(-1);
        }
        else if (best_value == 1 || best_value == 0) {
            writeln(best_value+2);
        }
        else {
            writeln("something went terribly wrong...");
        }
    }
}

/*
cabbabbcbbcbcbababcbcbababbabcbcaaa

abba 2
abbcbbcbcba vs abba -> abba 2
aba vs abba -> aba 1
abba vs aba -> aba 1
abcbca vs aba -> aba 1
aa vs aba -> aa 0 -> return

"aa" -> that
"aba"/"aca" -> ye
"abca"/"acba" -> ye*/

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

void main() {
    int cases = to!int(strip(readln()));

    // per testcase
    for (int t = 0; t < cases; t++) {
        int n;
        readf!"%d\n"(n);

        string s;
        readf!"%s\n"(s);

        int best_left = 0;
        int best_right = 0;
        int best_value = int.max;
        int left = 0;
        int right = 0;
        for (int i = 0; i < n; i++) {
            if (s[i] == 'a') {
                left = right;
                right = i;

                int value = right - left - 1;
                if (value < best_value && s[left] == 'a' && s[right] == 'a' && left != right) {
                    best_left = left;
                    best_right = right;
                    best_value = value;
                }
            }
        }

        // output cases
        if (best_value > 2) {
            writeln(-1);
        }
        else if (best_value == 2) {
            if (s[best_left+1] != s[best_left+2]) {
                writeln(4);
            } else writeln(-1);
        }
        else if (best_value == 1 || best_value == 0) {
            writeln(best_value+2);
        }
        else {
            writeln("something went terribly wrong...");
        }
    }
}

/*
cabbabbcbbcbcbababcbcbababbabcbcaaa

abba 2
abbcbbcbcba vs abba -> abba 2
aba vs abba -> aba 1
abba vs aba -> aba 1
abcbca vs aba -> aba 1
aa vs aba -> aa 0 -> return

"aa" -> that
"aba"/"aca" -> ye
"abca"/"acba" -> ye*/