In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.We will consider an extremely simplified subset of Python with only two types of statements.Simple statements are written in a single line, one per line. An example of a simple statement is assignment.For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.

The first line contains a single integer N (1 ≤ N ≤ 5000) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.

Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109 + 7.

NoteIn the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.simple statementfor statement    for statement        simple statementIn the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.for statement    simple statement    for statement        simple statementorfor statement    simple statementfor statement    simple statement

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

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

auto getAddrTuple() {
    return tuple();
}

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

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

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

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

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

enum mod = 10^^9 + 7;

int n;
char[5000] prog;
int[5001][ ] dp;

int dyn(int pos, int level, bool canDedent) {
    if (pos == n)
        return 1;
    if (~dp[pos][level])
        return dp[pos][level];
    const isLoop = prog[pos] == 'f';
    int result = dyn(pos + 1, level + isLoop, !isLoop);
    if (level && canDedent)
        result = (result + dyn(pos, level - 1, canDedent)) % mod;
    return (dp[pos][level] = result);
}

void main() {
    dp = uninitializedArray!(int[5001][ ])(5000);
    while (read(n)) {
        prog[0 .. n].each!read();
        memSet(dp, 0xFF);
        writeln(dyn(0, 0, false));
    }

    stdout.flush();
    _Exit(0);
}

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

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

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

    char[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp.front;
    }

    debug { arr.writeln; }

    auto dp = new int[][] (n+1, n+1);
    dp[1][0] = 1;
    foreach (i; 2 .. n+1) {
        int sm = 0;
        foreach_reverse (j; 0 .. n+1) {
            sm = (sm + dp[i-1][j]) % MD;
            if (arr[i-2] == 'f') {
                if (j > 0) { dp[i][j] = (dp[i][j] + dp[i-1][j-1]) % MD; }
            } else {
                dp[i][j] = (dp[i][j] + sm) % MD;
            }
        }
    }

    debug { dp.writeln; }

    auto ans = dp[n].fold!((r, v) => (r + v) % MD)(0);
    ans.writeln;
}

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

immutable mod = 10^^9 + 7;

void main() {
    int n;
    scan(n);

    auto dp = new int[][](n + 1, n + 1);
    dp[0][0] = 1;

    auto s = new int[](n + 1);
    s[0] = 1;

    foreach (i ; 1 .. n + 1) {
        char c;
        scan(c);

        if (c == 's') {
            foreach (j ; 0 .. n + 1) {
                dp[i][j] += s[j];
            }
        }
        else {
            foreach (j ; 0 .. n + 1) {
                if (j-1 >= 0) (dp[i][j] += dp[i-1][j-1]) %= mod;
            }
        }

        s[] = dp[i].dup;
        foreach_reverse (j ; 0 .. n) {
            (s[j] += s[j+1]) %= mod;
        }
    }

    int ans;

    foreach (j ; 0 .. n + 1) {
        (ans += dp[n-1][j]) %= mod;
    }

    debug {
        iota(n+1).each!(i => writeln(dp[i][0 .. 10]));
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

immutable mod = 10^^9 + 7;

void main() {
    int n;
    scan(n);

    auto dp = new int[][](n + 1, n + 2);
    dp[0][0] = 1;

    foreach (i ; 1 .. n + 1) {
        char c;
        scan(c);

        foreach_reverse (j ; 0 .. n + 1) {
            if (c == 'f') {
                if (j-1 >= 0) dp[i][j] = dp[i-1][j-1];
            }
            else {
                dp[i][j] = (dp[i-1][j] + dp[i][j+1]) % mod;
            }
        }
    }

    debug {
        writefln("%(%(%s %)\n%)", dp);
    }

    int ans;

    foreach (j ; 0 .. n + 1) {
        (ans += dp[n-1][j]) %= mod;
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

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

auto getAddrTuple() {
    return tuple();
}

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

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

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

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

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

enum mod = 10^^9 + 7;

int n;
char[5000] prog;
int[5001][ ] dp;

int dyn(int first, int last) {
    if (first == last)
        return 1;
    if (~dp[first][last])
        return dp[first][last];
    int result = 0;
    if (prog[first] == 's')
        result = dyn(first + 1, last);
    else
        foreach (end; first + 1 .. last)
            if (prog[end] == 's')
                result = (result + dyn(first + 1, end + 1) * dyn(end + 1, last)) % mod;
    return (dp[first][last] = result);
}

void main() {
    dp = uninitializedArray!(int[5001][ ])(5000);
    while (read(n)) {
        prog[0 .. n].each!read();
        memSet(dp, 0xFF);
        writeln(dyn(0, n));
    }

    stdout.flush();
    _Exit(0);
}

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

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

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

    char[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp.front;
    }

    debug { arr.writeln; }

    auto dp = new int[][] (n+1, n+1);
    dp[1][0] = 1;
    foreach (i; 2 .. n+1) {
        foreach (j; 0 .. n+1) {
            if (arr[i-2] == 'f') {
                if (j > 0) { dp[i][j] = (dp[i][j] + dp[i-1][j-1]) % MD; }
            } else {
                dp[i][j] = (dp[i][j] + dp[i-1][j]) % MD;
                if (j > 0) { dp[i][j-1] = (dp[i][j-1] + dp[i-1][j]) % MD; }
            }
        }
    }

    debug { dp.writeln; }

    auto ans = dp[n].fold!((r, v) => (r + v) % MD)(0);
    ans.writeln;
}

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

immutable mod = 10^^9 + 7;

void main() {
    int n;
    scan(n);

    auto dp = new int[][](n + 1, 5000 + 1);
    dp[0][0] = 1;

    foreach (i ; 0 .. n) {
        char c;
        scan(c);

        if (c == 's') {
            foreach (j ; 0 .. 5000 + 1) {
                if (j-1 >= 0) (dp[i+1][j-1] += dp[i][j]) %= mod;
                (dp[i+1][j] += dp[i][j]) %= mod;
            }
        }
        else {
            foreach (j ; 0 .. 5000 + 1) {
                if (j+1 <= 5000) (dp[i+1][j+1] += dp[i][j]) %= mod;
            }
        }
    }

    int ans;

    foreach (j ; 0 .. 5000 + 1) {
        (ans += dp[n-1][j]) %= mod;
    }

    debug {
        iota(n+1).each!(i => writeln(dp[i][0 .. 10]));
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


There are $$$n$$$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $$$x$$$ be the number of such pairs of students in a split. Pairs $$$(a, b)$$$ and $$$(b, a)$$$ are the same and counted only once.For example, if there are $$$6$$$ students: "olivia", "jacob", "tanya", "jack", "oliver" and "jessica", then:  splitting into two classrooms ("jack", "jacob", "jessica", "tanya") and ("olivia", "oliver") will give $$$x=4$$$ ($$$3$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom),  splitting into two classrooms ("jack", "tanya", "olivia") and ("jessica", "oliver", "jacob") will give $$$x=1$$$ ($$$0$$$ chatting pairs in the first classroom, $$$1$$$ chatting pair in the second classroom). You are given the list of the $$$n$$$ names. What is the minimum $$$x$$$ we can obtain by splitting the students into classrooms?Note that it is valid to place all of the students in one of the classrooms, leaving the other one empty.

The first line contains a single integer $$$n$$$ ($$$1\leq n \leq 100$$$) — the number of students. After this $$$n$$$ lines follow. The $$$i$$$-th line contains the name of the $$$i$$$-th student. It is guaranteed each name is a string of lowercase English letters of length at most $$$20$$$. Note that multiple students may share the same name.

The output must consist of a single integer $$$x$$$ — the minimum possible number of chatty pairs.

7
kambei
gorobei
shichiroji
kyuzo
heihachi
katsushiro
kikuchiyo

NoteIn the first sample the minimum number of pairs is $$$1$$$. This can be achieved, for example, by putting everyone except jose in one classroom, and jose in the other, so jorge and jerry form the only chatty pair.In the second sample the minimum number of pairs is $$$2$$$. This can be achieved, for example, by putting kambei, gorobei, shichiroji and kyuzo in one room and putting heihachi, katsushiro and kikuchiyo in the other room. In this case the two pairs are kambei and kyuzo, and katsushiro and kikuchiyo.In the third sample the minimum number of pairs is $$$4$$$. This can be achieved by placing three of the students named mike in one classroom and the other two students in another classroom. Thus there will be three chatty pairs in one classroom and one chatty pair in the other classroom.

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;
		int [char] s;
		foreach (i; 0..n)
		{
			auto t = readln.strip;
			s[t[0]] += 1;
		}
		int res = 0;
		foreach (k, v; s)
		{
			int a = v / 2;
			int b = v - a;
			res += a * (a - 1) / 2;
			res += b * (b - 1) / 2;
		}
		writeln (res);
	}
}

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

int f (int x) {
  return (x * (x - 1) ) / 2;
}

void main() {
  int n = readln.strip.to!int;
  int[26] c;
  foreach (i; 0 .. n) {
    auto s = readln;
    ++c[s[0].to!int - 97];
  }
  int res;
  foreach (i; 0 .. 26) {
    int m = c[i] >> 1;
    res += f (m) + f (c[i] - m);
  }
  writeln (res);
}

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

alias Tree = RBT!long;

void main() {
  GC.disable();

  int n;
  readf(" %s\n", n);
  int[26] counter;
  counter[] = 0;
  foreach(i; 0..n) {
    string s  = readln().strip;
      counter[ s[0] - 'a' ] ++;
  }

  int total = 0;
  foreach(i; 0..26) {
    int c = counter[i];
    int c1 = c/2;
    int c2= c - c1;
    total += c1 * (c1-1)/2 + c2*(c2-1)/2;
  }

  writeln(total);

}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD!int;
	auto cnt = new long[](30);
	foreach (i; 0..N)
	{
		auto s = RD!string;
		++cnt[s[0]-'a'];
	}

	long ans;
	foreach (e; cnt)
	{
		auto x = (e+1) / 2;
		auto y = e / 2;
		ans += x * (x-1) / 2;
		ans += y * (y-1) / 2;
	}

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

module _;
void main() {
	import std.stdio, std.conv, std.string;
	int n =readln.strip.to!int;
	int[char] cnt;
	foreach(i; 0..n) {
		cnt[readln[0]]++;
	}
	int ans = 0;
	foreach(k; cnt.byKey) {
		ans += cnt[k]*(cnt[k]-1)/2;
		int half = cnt[k]/2;
		ans -= half * (cnt[k]-half);
	}
	writeln(ans);
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD!int;
	auto cnt = new long[](30);
	foreach (i; 0..N)
	{
		auto s = RD!string;
		++cnt[s[0]-'a'];
	}
	cnt.sort!"a > b"();
	auto x = (cnt[0]+1) / 2;
	auto y = cnt[0] / 2;
	long ans;
	ans += x * (x-1) / 2;
	ans += y * (y-1) / 2;

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


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.

The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

import std.stdio, std.algorithm;

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);

    int b;
    readf("%d", &b);

    bool[] bHappy = new bool[n];
    for (int i = 0; i < b; ++i) {
        int t;
        readf(" %d", &t);
        bHappy[t] = true;
    }

    readf("\n");

    int g;
    readf("%d", &g);

    bool[] gHappy = new bool[m];
    assert(gHappy[0] == false);
    for (int i = 0; i < g; ++i) {
        int t;
        readf(" %d", &t);
        gHappy[t] = true;
    }

    for (int i = 0; i < 10000; ++i) {
        if (bHappy[i%n]) {
            gHappy[i%m] = true;
        } else if (gHappy[i%m]) {
            bHappy[i%n] = true;
        }
    }

    bool allHappy = true;
    for (int i = 0; i < n && allHappy; ++i) {
        if (!bHappy[i]) {
            allHappy = false;
        }
    }

    for (int i = 0; i < m && allHappy; ++i) {
        if (!gHappy[i]) {
            allHappy = false;
        }
    }

    if (allHappy) {
        writeln("Yes");
    } else {
        writeln("No");
    }
}

import std.stdio, std.algorithm;

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);

    int b;
    readf("%d", &b);

    bool[] bHappy = new bool[n];
    for (int i = 0; i < b; ++i) {
        int t;
        readf(" %d", &t);
        bHappy[t] = true;
    }

    readf("\n");

    int g;
    readf("%d", &g);

    bool[] gHappy = new bool[m];
    assert(gHappy[0] == false);
    for (int i = 0; i < g; ++i) {
        int t;
        readf(" %d", &t);
        gHappy[t] = true;
    }

    for (int i = 0; i < 1000; ++i) {
        if (bHappy[i%n]) {
            gHappy[i%m] = true;
        } else if (gHappy[i%m]) {
            bHappy[i%n] = true;
        }
    }

    bool allHappy = true;
    for (int i = 0; i < n && allHappy; ++i) {
        if (!bHappy[i]) {
            allHappy = false;
        }
    }

    for (int i = 0; i < m && allHappy; ++i) {
        if (!gHappy[i]) {
            allHappy = false;
        }
    }

    if (allHappy) {
        writeln("Yes");
    } else {
        writeln("No");
    }
}


There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(1 \le n, m \le 2 \cdot 10^{5})$$$ — the number of dormitories and the number of letters. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{10})$$$, where $$$a_i$$$ equals to the number of rooms in the $$$i$$$-th dormitory. The third line contains a sequence $$$b_1, b_2, \dots, b_m$$$ $$$(1 \le b_j \le a_1 + a_2 + \dots + a_n)$$$, where $$$b_j$$$ equals to the room number (among all rooms of all dormitories) for the $$$j$$$-th letter. All $$$b_j$$$ are given in increasing order.

Print $$$m$$$ lines. For each letter print two integers $$$f$$$ and $$$k$$$ — the dormitory number $$$f$$$ $$$(1 \le f \le n)$$$ and the room number $$$k$$$ in this dormitory $$$(1 \le k \le a_f)$$$ to deliver the letter.

NoteIn the first example letters should be delivered in the following order:  the first letter in room $$$1$$$ of the first dormitory  the second letter in room $$$9$$$ of the first dormitory  the third letter in room $$$2$$$ of the second dormitory  the fourth letter in room $$$13$$$ of the second dormitory  the fifth letter in room $$$1$$$ of the third dormitory  the sixth letter in room $$$12$$$ of the third dormitory

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		long [] s;
		s ~= 0;
		foreach (c; a)
		{
			s ~= s.back + c;
		}
		auto r = s.assumeSorted ();

		auto b = readln.splitter.map !(to !(long)).array;
		foreach (x; b)
		{
			auto p = r.lowerBound (x);
			auto pos = p.length;
			writeln (pos, " ", x - p.back);
		}
	}
}

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

  int n, m; rd(n, m);
  auto as=readln.split.to!(long[]);
  auto bs=readln.split.to!(long[]);

  auto dub=new long[](n+1);
  foreach(i; 0..n) dub[i+1]=dub[i]+as[i];
  dub~=1_000_000_000_000_000_000;
  int x=0;
  foreach(b; bs){
    while(dub[x+1]<b) x++;
    // dub[x] < b <= dub[x+1]
    writeln(x+1, " ", b-dub[x]);
  }
}

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


Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event.

The first input line contains integer n (1 ≤ n ≤ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≤ ai < bi ≤ 109) — the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order.

Print the only integer — the answer to the problem.

NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third — in the second and the second — in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0.

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

struct R {
    int from, to;
}

void main() {
    int N; scanf("%d\n", &N);
    auto rs = new R[N];
    foreach (i; 0 .. N) {
        int a, b; scanf("%d %d\n", &a, &b);
        rs[i] = R(a, b);
    }
    rs.sort!"a.from == b.from ? a.to < b.to : a.from < b.from";
    int count = 0;
    auto used = new bool[N];
    foreach (int i, r; rs) {
        used[i] = true;
        foreach (j; i + 1 .. N) {
            if (used[j]) break;
            auto r1 = rs[j];
            if (r.from < r1.from && r1.to < r.to) {
                used[j] = true;
                count++;
            } else {
                break;
            }
        }
    }
    writeln(count);
}


Let's denote the Manhattan distance between two points $$$p_1$$$ (with coordinates $$$(x_1, y_1)$$$) and $$$p_2$$$ (with coordinates $$$(x_2, y_2)$$$) as $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$$$. For example, the distance between two points with coordinates $$$(1, 3)$$$ and $$$(4, 2)$$$ is $$$|1 - 4| + |3 - 2| = 4$$$.You are given two points, $$$A$$$ and $$$B$$$. The point $$$A$$$ has coordinates $$$(0, 0)$$$, the point $$$B$$$ has coordinates $$$(x, y)$$$.Your goal is to find a point $$$C$$$ such that:  both coordinates of $$$C$$$ are non-negative integers;  $$$d(A, C) = \dfrac{d(A, B)}{2}$$$ (without any rounding);  $$$d(B, C) = \dfrac{d(A, B)}{2}$$$ (without any rounding). Find any point $$$C$$$ that meets these constraints, or report that no such point exists.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the point $$$B$$$.

For each test case, print the answer on a separate line as follows:   if it is impossible to find a point $$$C$$$ meeting the constraints, print "-1 -1" (without quotes);  otherwise, print two non-negative integers not exceeding $$$10^6$$$ — the coordinates of point $$$C$$$ meeting the constraints. If there are multiple answers, print any of them. It can be shown that if any such point exists, it's possible to find a point with coordinates not exceeding $$$10^6$$$ that meets the constraints.

NoteExplanations for some of the test cases from the example:  In the first test case, the point $$$B$$$ has coordinates $$$(49, 3)$$$. If the point $$$C$$$ has coordinates $$$(23, 3)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|49 - 0| + |3 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|23 - 0| + |3 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|23 - 49| + |3 - 3| = 26$$$.  In the second test case, the point $$$B$$$ has coordinates $$$(2, 50)$$$. If the point $$$C$$$ has coordinates $$$(1, 25)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|2 - 0| + |50 - 0| = 52$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|1 - 0| + |25 - 0| = 26$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|1 - 2| + |25 - 50| = 26$$$.  In the third and the fourth test cases, it can be shown that no point with integer coordinates meets the constraints.  In the fifth test case, the point $$$B$$$ has coordinates $$$(42, 0)$$$. If the point $$$C$$$ has coordinates $$$(21, 0)$$$, then the distance from $$$A$$$ to $$$B$$$ is $$$|42 - 0| + |0 - 0| = 42$$$, the distance from $$$A$$$ to $$$C$$$ is $$$|21 - 0| + |0 - 0| = 21$$$, and the distance from $$$B$$$ to $$$C$$$ is $$$|21 - 42| + |0 - 0| = 21$$$.

immutable multi = true;

void solve(int tc)
{
	auto x = readInt!int;
	auto y = readInt!int;
	int dist(int x0, int y0, int x1, int y1)
	{
		return abs(x1 - x0) + abs(y1 - y0);
	}
	auto hs = (x + y) / 2;
	if (hs*2 != x + y) return writeln(-1, " ", -1);
	// ox + oy = hs
	// oy = hs - ox
	foreach(ox; 0 .. x + 1)
	{
		auto oy = hs - ox;
		if (dist(x, y, ox, oy) == hs) return writeln(ox, " ", oy);
	}
	return writeln(-1, " ", -1);
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

//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 long[][](t);
	foreach (ti; 0..t)
	{
		auto x = RD;
		auto y = RD;

		if ((x+y) % 2)
			ans[ti] = [-1, -1];
		else
		{
			auto a = min(x, (x+y)/2);
			ans[ti] = [a, (x+y)/2 - a];
		}
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}


A sequence of positive integers is called great for a positive integer $$$x$$$, if we can split it into pairs in such a way that in each pair the first number multiplied by $$$x$$$ is equal to the second number. More formally, a sequence $$$a$$$ of size $$$n$$$ is great for a positive integer $$$x$$$, if $$$n$$$ is even and there exists a permutation $$$p$$$ of size $$$n$$$, such that for each $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$) $$$a_{p_{2i-1}} \cdot x = a_{p_{2i}}$$$. Sam has a sequence $$$a$$$ and a positive integer $$$x$$$. Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence $$$a$$$ to make it great for the number $$$x$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$2 \le x \le 10^6$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the minimum number of integers that can be added to the end of $$$a$$$ to make it a great sequence for the number $$$x$$$.

NoteIn the first test case, Sam got lucky and the sequence is already great for the number $$$4$$$ because you can divide it into such pairs: $$$(1, 4)$$$, $$$(4, 16)$$$. Thus we can add $$$0$$$ numbers.In the second test case, you can add numbers $$$1$$$ and $$$14$$$ to the sequence, then you can divide all $$$8$$$ integers into such pairs: $$$(1, 2)$$$, $$$(1, 2)$$$, $$$(2, 4)$$$, $$$(7, 14)$$$. It is impossible to add less than $$$2$$$ integers to fix the sequence.

void main() { runSolver(); }

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

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

      int[long] numCounts;
      foreach(a; A.sort.reverse) {
        if((a * X) in numCounts) {
          numCounts[a * X]--;
          if (numCounts[a * X] == 0) numCounts.remove(a * X);
        }
        else numCounts[a]++;
      }

      return numCounts.values.sum;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

import std.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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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 long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD;
		auto a = RDA;

		long[long] cnt;
		foreach (i; 0..n)
			++cnt[a[i]];

		foreach (key; cnt.keys.sort)
		{
			auto y = key * x;
			auto z = min(cnt.get(y, 0), cnt[key]);
			cnt[key] -= z;
			cnt[y] -= z;
			ans[ti] += cnt[key];
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		int j = 0;
		int res = 0;
		foreach (i; 0..n)
		{
			if (a[i] == 0)
			{
				continue;
			}
			while (j < n && a[j] < a[i] * 1L * x)
			{
				j += 1;
			}
			if (j < n && a[j] == a[i] * 1L * x)
			{
				a[j] = 0;
			}
			else
			{
				res += 1;
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

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

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

      int[long] numCounts;
      foreach(a; A) {
        if (a % X == 0 && ((a / X) in numCounts)) {
          numCounts[a / X]--;
          if (numCounts[a / X] == 0) numCounts.remove(a / X);
        }
        else if((a * X) in numCounts) {
          numCounts[a * X]--;
          if (numCounts[a * X] == 0) numCounts.remove(a * X);
        }
        else numCounts[a]++;
      }

      return numCounts.values.sum;
    }

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

  outputForAtCoder(&solve);
}

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

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

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


Given a permutation $$$a_1, a_2, \dots, a_n$$$ of integers from $$$1$$$ to $$$n$$$, and a threshold $$$k$$$ with $$$0 \leq k \leq n$$$, you compute a sequence $$$b_1, b_2, \dots, b_n$$$ as follows. For every $$$1 \leq i \leq n$$$ in increasing order, let $$$x = a_i$$$.   If $$$x \leq k$$$, set $$$b_{x}$$$ to the last element $$$a_j$$$ ($$$1 \leq j < i$$$) that $$$a_j > k$$$. If no such element $$$a_j$$$ exists, set $$$b_{x} = n+1$$$.  If $$$x > k$$$, set $$$b_{x}$$$ to the last element $$$a_j$$$ ($$$1 \leq j < i$$$) that $$$a_j \leq k$$$. If no such element $$$a_j$$$ exists, set $$$b_{x} = 0$$$. Unfortunately, after the sequence $$$b_1, b_2, \dots, b_n$$$ has been completely computed, the permutation $$$a_1, a_2, \dots, a_n$$$ and the threshold $$$k$$$ are discarded. Now you only have the sequence $$$b_1, b_2, \dots, b_n$$$. Your task is to find any possible permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ that produce the sequence $$$b_1, b_2, \dots, b_n$$$. It is guaranteed that there exists at least one pair of permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ that produce the sequence $$$b_1, b_2, \dots, b_n$$$.A permutation of integers from $$$1$$$ to $$$n$$$ is a sequence of length $$$n$$$ which contains all integers from $$$1$$$ to $$$n$$$ exactly once.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the length of the permutation $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq n+1$$$), indicating the elements of the sequence $$$b$$$. It is guaranteed that there exists at least one pair of permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ that produce the sequence $$$b_1, b_2, \dots, b_n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the threshold $$$k$$$ ($$$0 \leq k \leq n$$$) in the first line, and then output the permutation $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) in the second line such that the permutation $$$a_1, a_2, \dots, a_n$$$ and threshold $$$k$$$ produce the sequence $$$b_1, b_2, \dots, b_n$$$. If there are multiple solutions, you can output any of them.

NoteFor the first test case, permutation $$$a = [1,3,2,4]$$$ and threshold $$$k = 2$$$ will produce sequence $$$b$$$ as follows.   When $$$i = 1$$$, $$$x = a_i = 1 \leq k$$$, there is no $$$a_j$$$ ($$$1 \leq j < i$$$) that $$$a_j > k$$$. Therefore, $$$b_1 = n + 1 = 5$$$.  When $$$i = 2$$$, $$$x = a_i = 3 > k$$$, the last element $$$a_j$$$ that $$$a_j \leq k$$$ is $$$a_1$$$. Therefore, $$$b_3 = a_1 = 1$$$.  When $$$i = 3$$$, $$$x = a_i = 2 \leq k$$$, the last element $$$a_j$$$ that $$$a_j > k$$$ is $$$a_2$$$. Therefore, $$$b_2 = a_2 = 3$$$.  When $$$i = 4$$$, $$$x = a_i = 4 > k$$$, the last element $$$a_j$$$ that $$$a_j \leq k$$$ is $$$a_3$$$. Therefore, $$$b_4 = a_3 = 2$$$.  Finally, we obtain sequence $$$b = [5,3,1,2]$$$. For the second test case, permutation $$$a = [1,2,3,4,5,6]$$$ and threshold $$$k = 3$$$ will produce sequence $$$b$$$ as follows.   When $$$i = 1, 2, 3$$$, $$$a_i \leq k$$$, there is no $$$a_j$$$ ($$$1 \leq j < i$$$) that $$$a_j > k$$$. Therefore, $$$b_1 = b_2 = b_3 = n + 1 = 7$$$.  When $$$i = 4, 5, 6$$$, $$$a_i > k$$$, the last element $$$a_j$$$ that $$$a_j \leq k$$$ is $$$a_3$$$. Therefore, $$$b_4 = b_5 = b_6 = a_3 = 3$$$.  Finally, we obtain sequence $$$b = [7,7,7,3,3,3]$$$. For the third test case, permutation $$$a = [6,5,4,3,2,1]$$$ and threshold $$$k = 3$$$ will produce sequence $$$b$$$ as follows.   When $$$i = 1, 2, 3$$$, $$$a_i > k$$$, there is no $$$a_j$$$ ($$$1 \leq j < i$$$) that $$$a_j \leq k$$$. Therefore, $$$b_4 = b_5 = b_6 = 0$$$.  When $$$i = 4, 5, 6$$$, $$$a_i \leq k$$$, the last element $$$a_j$$$ that $$$a_j > k$$$ is $$$a_3$$$. Therefore, $$$b_1 = b_2 = b_3 = a_3 = 4$$$.  Finally, we obtain sequence $$$b = [4,4,4,0,0,0]$$$.

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

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

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

void solve() {
    int N = read!int;
    auto B = readarray!int;

    int k_lb = 0, k_ub = N + 1;
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x < b) {
            k_lb = max(k_lb, x);
            k_ub = min(k_ub, b - 1);
        } else if (x > b) {
            k_lb = max(k_lb, b);
            k_ub = min(k_ub, x - 1);
        } else {
            assert(false);
        }
    }

    int k = k_lb;
    Array!int L, U;
    auto G = new int[][N+2];
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x <= k) {
            G[b] ~= x;
        } else {
            G[b] ~= x;
        }
    }

    foreach (c; 0 .. N + 2) {
        G[c].sort!((i, j) => G[i].length < G[j].length);
    }

    int[] as;
    DList!int Q;
    if (! G[0].empty) { Q.insert(0); }
    else if (! G[N+1].empty) { Q.insert(N+1); }
    else assert(false);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        as ~= c;
        foreach (v; G[c]) {
            Q.insert(v);
        }
    }

    writeln(k);
    writefln("%(%s %)", as[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[] B;
int K;
int[] A;

void solve() {
  auto minL = new int[N + 1];
  auto maxR = new int[N + 1];
  minL[0] = N + 2;
  foreach (i; 0 .. N) {
    minL[i + 1] = min(minL[i], B[i]);
  }
  maxR[N] = -1;
  foreach_reverse (i; 0 .. N) {
    maxR[i] = max(B[i], maxR[i + 1]);
  }
  {
    int[] ks;
    foreach (k; 0 .. N + 1) {
      if (minL[k] > k && k >= maxR[k]) {
        ks ~= k;
      }
    }
    debug {
      writeln("ks = ", ks);
    }
    assert(ks.length == 1);
    K = ks[0];
  }

  auto graph = new int[][N + 2];
  foreach (i; 0 .. N) {
    graph[B[i]] ~= i + 1;
  }
  auto us = [0, N + 1];
  for (int j = 0; j < us.length; ++j) {
    graph[us[j]].sort!((v, w) => (graph[v].length < graph[w].length));
    foreach (v; graph[us[j]]) {
      us ~= v;
    }
  }
  assert(us.length == N + 2);
  A = us[2 .. $];
}

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

        solve;

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

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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = readln.splitter.map !(to !(int)).array;
		auto s = new int [] [n + 2];
		foreach (int i, ref c; b)
		{
			s[c] ~= i + 1;
		}

		int [] a;
		int cur = 0;
		bool up = false;
		int k = 0;
		if (s[cur].empty)
		{
			cur = n + 1;
			up = true;
		}

		while (true)
		{
			int next = NA;
			foreach (v; s[cur])
			{
				if (up)
				{
					k = max (k, v);
				}
				if (!s[v].empty)
				{
					next = v;
				}
			}

			foreach (v; s[cur])
			{
				if (v != next)
				{
					a ~= v;
				}
			}
			s[cur] = null;
			if (next == NA)
			{
				break;
			}
			a ~= next;

			up ^= true;
			cur = next;
		}

		writeln (k);
		writefln !("%(%s %)") (a.map !(q{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 main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N = read!int;
    auto B = readarray!int;

    int k_lb = 0, k_ub = N + 1;
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x < b) {
            k_lb = max(k_lb, x);
            k_ub = min(k_ub, b - 1);
        } else if (x > b) {
            k_lb = max(k_lb, b);
            k_ub = min(k_ub, x - 1);
        } else {
            assert(false);
        }
    }

    int k = k_lb;
    Array!int L, U;
    auto G = new int[][N+2];
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x <= k) {
            G[b] ~= x;
        } else {
            G[b] ~= x;
        }
    }

    foreach (c; 0 .. N + 1) {
        G[c].sort!((i, j) => G[i].length < G[j].length);
    }

    int[] as;
    DList!int Q;
    if (! G[0].empty) { Q.insert(0); }
    else if (! G[N+1].empty) { Q.insert(N+1); }
    else assert(false);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        as ~= c;
        foreach (v; G[c]) {
            Q.insert(v);
        }
    }

    writeln(k);
    writefln("%(%s %)", as[1..$]);
}

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

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

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

void solve() {
    int N = read!int;
    auto B = readarray!int;

    int k_lb = 0, k_ub = N + 1;
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x < b) {
            k_lb = max(k_lb, x);
            k_ub = min(k_ub, b - 1);
        } else if (x > b) {
            k_lb = max(k_lb, b);
            k_ub = min(k_ub, x - 1);
        } else {
            assert(false);
        }
    }

    int k = k_lb;
    Array!int L, U;
    auto G = new int[][N+2];
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x <= k) {
            G[b] ~= x;
        } else {
            G[b] ~= x;
        }
    }

    int[] as;
    DList!int Q;
    if (! G[0].empty) { Q.insert(0); }
    else if (! G[N+1].empty) { Q.insert(N+1); }
    else assert(false);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        as ~= c;
        foreach (v; G[c]) {
            Q.insert(v);
        }
    }

    writeln(k);
    writefln("%(%s %)", as[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[] B;
int K;
int[] A;

void solve() {
  auto minL = new int[N + 1];
  auto maxR = new int[N + 1];
  minL[0] = N + 2;
  foreach (i; 0 .. N) {
    minL[i + 1] = min(minL[i], B[i]);
  }
  maxR[N] = -1;
  foreach_reverse (i; 0 .. N) {
    maxR[i] = max(B[i], maxR[i + 1]);
  }
  {
    int[] ks;
    foreach (k; 0 .. N + 1) {
      if (minL[k] > k && k >= maxR[k]) {
        ks ~= k;
      }
    }
    debug {
      writeln("ks = ", ks);
    }
    assert(ks.length == 1);
    K = ks[0];
  }

  auto graph = new int[][N + 2];
  foreach (i; 0 .. N) {
    graph[B[i]] ~= i + 1;
  }
  auto us = [0, N + 1];
  for (int j = 0; j < us.length; ++j) {
    foreach (v; graph[us[j]]) {
      us ~= v;
    }
  }
  assert(us.length == N + 2);
  A = us[2 .. $];
}

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

        solve;

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


William has an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. In one move he can swap two neighboring items. Two items $$$a_i$$$ and $$$a_j$$$ are considered neighboring if the condition $$$|i - j| = 1$$$ is satisfied.William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ which is the total number of items in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ which are William's array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output the minimal number of operations needed or $$$-1$$$ if it is impossible to get the array to a state when no neighboring numbers have the same parity.

NoteIn the first test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 1, 6]$$$ In the second test case the array initially does not contain two neighboring items of the same parity.In the third test case the following sequence of operations would satisfy the requirements:   swap(3, 4). Array after performing the operation: $$$[1, 1, 2, 1, 2, 2]$$$  swap(2, 3). Array after performing the operation: $$$[1, 2, 1, 1, 2, 2]$$$  swap(4, 5). Array after performing the operation: $$$[1, 2, 1, 2, 1, 2]$$$ In the fourth test case it is impossible to satisfy the requirements.In the fifth test case the following sequence of operations would satisfy the requirements:   swap(2, 3). Array after performing the operation: $$$[6, 3, 2, 4, 5, 1]$$$  swap(4, 5). Array after performing the operation: $$$[6, 3, 2, 5, 4, 1]$$$

immutable multi = true;

void solve(int tc)
{
	int n = readInt!int;
	auto a = ma(n, readInt!int%2);
	auto m1 = n/2;
	auto m2 = n - m1;
	int fe = void;
	int[2] c;
	c[0] = cast(int)a.count!(ai => ai == 0);
	c[1] = n - c[0];
	if (c[0] != m2 && c[1] != m2) return writeln(-1);
	long allOps = long.max;
	void tryFe(int fe)
	{
	        if (c[fe] != m2) return;
		int[] lfe = null;
		foreach(i, ai; a)
		{
			if (ai == fe)
			{
				lfe ~= cast(int)i;
			}
		}
		debug writeln("lfe ", lfe);
		long ops = 0;
		foreach(i; 0 .. n)
		{
			if (i%2 == 0)
			{
				assert(lfe.length > 0);
				ops += abs(lfe[0] - i);
				lfe = lfe[1 .. $];
			}
		}
		allOps = min(allOps, ops);
	}
	tryFe(0); tryFe(1);
	allOps.writeln;
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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

long solve(int[] a, bool tie)
{
    int even_cnt = cast(int)a.count(0);
    int odd_cnt = cast(int)a.length - even_cnt;

    if (abs(even_cnt - odd_cnt) > 1)
      return -1;

    int odd_i, even_i;
    int[] arr;
    if (odd_cnt == even_cnt) {
      if (tie)
        odd_i = 1;
      else
        even_i = 1;
    } else if (odd_cnt < even_cnt) {
      odd_i = 1;
    } else {
      even_i = 1;
    }

    foreach (x ; a) {
      if (x) {
        arr ~= odd_i;
        odd_i += 2;
      } else {
        arr ~= even_i;
        even_i += 2;
      }
    }
    long ans = 0;
    foreach (i ; 0 .. cast(int)a.length) {
      ans += abs(arr[i] - i);
    }
    assert(ans % 2 == 0);
    return ans / 2;
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readln.formattedRead!" %d "(n);
    auto a = readln.strip.split.map!(x => x.to!int % 2).array;
    writeln(min(solve(a, true), solve(a, false)));
  }
}

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

long solve (int [] a, int pos)
{
	auto n = a.length.to !(int);
	auto half = (n + 1 - pos) / 2;
	auto total = a.sum;
	if (total != half)
	{
		return long.max;
	}
	long res = 0;
	foreach (int i, ref c; a)
	{
		if (c & 1)
		{
			res += abs (i - pos);
			pos += 2;
		}
	}
	return res;
}

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;
		a[] %= 2;
		auto res = long.max;
		res = min (res, solve (a, 0));
		res = min (res, solve (a, 1));
		if (res == long.max)
		{
			res = -1;
		}
		writeln (res);
	}
}


Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P = [p1, p2, ..., pn], where pi denotes the number of page that should be read i-th in turn.Sometimes Vladik’s mom sorted some subsegment of permutation P from position l to position r inclusive, because she loves the order. For every of such sorting Vladik knows number x — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has px changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.

First line contains two space-separated integers n, m (1 ≤ n, m ≤ 104) — length of permutation and number of times Vladik's mom sorted some subsegment of the book. Second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — permutation P. Note that elements in permutation are distinct. Each of the next m lines contains three space-separated integers li, ri, xi (1 ≤ li ≤ xi ≤ ri ≤ n) — left and right borders of sorted subsegment in i-th sorting and position that is interesting to Vladik.

For each mom’s sorting on it’s own line print "Yes", if page which is interesting to Vladik hasn't changed, or "No" otherwise.

NoteExplanation of first test case:   [1, 2, 3, 4, 5] — permutation after sorting, 3-rd element hasn’t changed, so answer is "Yes".  [3, 4, 5, 2, 1] — permutation after sorting, 1-st element has changed, so answer is "No".  [5, 2, 3, 4, 1] — permutation after sorting, 3-rd element hasn’t changed, so answer is "Yes".  [5, 4, 3, 2, 1] — permutation after sorting, 4-th element hasn’t changed, so answer is "Yes".  [5, 1, 2, 3, 4] — permutation after sorting, 3-rd element has changed, so answer is "No".

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

__gshared:

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

auto getAddrTuple() {
    return tuple();
}

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

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

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

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

int[10^^4] p;

void main() {
    int n, m;
    while (read(n, m)) {
        foreach (ref x; p[0 .. n])
            read(x);
        while (m--) {
            int left, right, pos;
            read(left, right, pos);
            left--;
            const x = p[pos - 1];
            const lte = p[left .. right].filter!(y => y <= x).walkLength();
            writeln(pos == left + lte ? "Yes" : "No");
        }
        debug writeln();
    }
}

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

void main(){
    int N, M, l, r, x;

    readVars(N, M);
    auto p = readln.split.to!(int[]);

    int cnt;

    foreach(i ; 0 .. M){
        readVars(l, r, x);
        l--;
        x--;

        cnt = 0;

        foreach(j ; l .. r){
            cnt += (p[j] < p[x]);
        }

        if (cnt == x - l) {
            writeln("Yes");
        } else {
            writeln("No");
        }
    }
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        throw new Exception("args num < input num");
    }
}


Pak Chanek has $$$n$$$ two-dimensional slices of cheese. The $$$i$$$-th slice of cheese can be represented as a rectangle of dimensions $$$a_i \times b_i$$$. We want to arrange them on the two-dimensional plane such that:  Each edge of each cheese is parallel to either the x-axis or the y-axis.  The bottom edge of each cheese is a segment of the x-axis.  No two slices of cheese overlap, but their sides can touch.  They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of slices of cheese Pak Chanek has. The $$$i$$$-th of the next $$$n$$$ lines of each test case contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i,b_i \leq 10^9$$$) — the dimensions of the $$$i$$$-th slice of cheese. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a line containing an integer representing the minimum possible perimeter of the constructed shape.

NoteIn the first test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+5+1+1+1+1+3+1+5+1+2+3=26$$$. It can be shown that we cannot get a smaller perimeter.Consider the following invalid arrangement.Even though the perimeter of the shape above is $$$24$$$, it does not satisfy all conditions of the problem. The bottom edge of the $$$1 \times 1$$$ slice of cheese is not a segment of the x-axis.In the second test case, a way of getting the minimum possible perimeter is to arrange the slices of cheese as follows.We can calculate that the perimeter of the constructed shape is $$$2+2+2+3+2+3+2+2+2+4=24$$$. It can be shown that we cannot get a smaller perimeter.

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

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

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

void solve() {
    int n = read!int;
    long a, b, maxV, res;
    foreach(i; 0 .. n) {
        scanf("%lld %lld\n", &a, &b);
        res += min(a,b);
        if (max(a,b) > maxV)
            maxV = max(a,b);
    }
    res <<= 1;
    maxV <<= 1;
    writeln(res + maxV);
}

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;
    Tuple!(long, long)[] a;
    foreach (i ; 0 .. n) {
      long ai, bi;
      readf!" %d %d "(ai, bi);
      a ~= tuple(min(ai, bi), max(ai, bi));
    }
    a.sort!((x, y) => x[1] < y[1]);
    long ans = a[0][0] * 2 + a[0][1];
    foreach (i ; 1 .. a.length) {
      ans += a[i][0] * 2 + (a[i][1] - a[i - 1][1]);
    }
    ans += a.back[1];
    writeln(ans);
  }
}

import std.algorithm;
import std.conv;
import std.math;
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);
		long res = 0;
		long hi = 0;
		foreach (i; 0..n)
		{
			long a, b;
			readf !(" %s %s") (a, b);
			if (a > b)
			{
				swap (a, b);
			}
			res += a * 2;
			hi = max (hi, b);
		}
		readln;
		writeln (res + hi * 2);
	}
}


You are given a rooted tree with $$$n$$$ vertices, the root of the tree is the vertex $$$1$$$. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree $$$1$$$.Arkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empty set of vertices of the tree. On the second stage Vasily puts some integers into all leaves of the tree. On the third stage Arkady can perform several (possibly none) operations of the following kind: choose some vertex $$$v$$$ he bought on the first stage and some integer $$$x$$$, and then add $$$x$$$ to all integers in the leaves in the subtree of $$$v$$$. The integer $$$x$$$ can be positive, negative of zero.A leaf $$$a$$$ is in the subtree of a vertex $$$b$$$ if and only if the simple path between $$$a$$$ and the root goes through $$$b$$$.Arkady's task is to make all integers in the leaves equal to zero. What is the minimum total cost $$$s$$$ he has to pay on the first stage to guarantee his own win independently of the integers Vasily puts on the second stage? Also, we ask you to find all such vertices that there is an optimal (i.e. with cost $$$s$$$) set of vertices containing this one such that Arkady can guarantee his own win buying this set on the first stage.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \le c_i \le 10^9$$$), where $$$c_i$$$ is the price of the $$$i$$$-th vertex. Each of the next $$$n - 1$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$), denoting an edge of the tree.

In the first line print two integers: the minimum possible cost $$$s$$$ Arkady has to pay to guarantee his own win, and the number of vertices $$$k$$$ that belong to at least one optimal set. In the second line print $$$k$$$ distinct integers in increasing order the indices of the vertices that belong to at least one optimal set.

NoteIn the second example all sets of two vertices are optimal. So, each vertex is in at least one optimal set.

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

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

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

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

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

int N;
long[] C;
int[] A, B;

int[][] G;
int zeit;
int[] dis, fin;

void dfs(int u, int p) {
  dis[u] = zeit;
  bool isLeaf = true;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      isLeaf = false;
    }
  }
  if (isLeaf) {
    ++zeit;
  }
  fin[u] = zeit;
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      zeit = 0;
      dis = new int[N];
      fin = new int[N];
      dfs(0, -1);

      alias Entry = Tuple!(long, "cost", int, "a", int, "b", int, "id");
      auto es = new Entry[N];
      foreach (u; 0 .. N) {
        es[u] = Entry(C[u], dis[u], fin[u], u);
      }
      es.sort;

      auto uf = new int[zeit + 1];
      uf[] = -1;
      long total = 0;
      int[] ans;
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].cost == es[k].cost; ++k) {}
        foreach (l; j .. k) {
          if (uf.root(es[l].a) != uf.root(es[l].b)) {
            ans ~= es[l].id;
          }
        }
        foreach (l; j .. k) {
          if (uf.connect(es[l].a, es[l].b)) {
            total += es[l].cost;
          }
        }
      }

      ans.sort;
      writeln(total, " ", ans.length);
      foreach (index, u; ans) {
        if (index > 0) write(" ");
        write(u + 1);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

int N;
long[] C;
int[] A, B;

int[][] G;
int zeit;
int[] dis, fin;

void dfs(int u, int p) {
  dis[u] = zeit;
  bool isLeaf = true;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      isLeaf = false;
    }
  }
  if (isLeaf) {
    ++zeit;
  }
  fin[u] = zeit;
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      zeit = 0;
      dis = new int[N];
      fin = new int[N];
      dfs(0, -1);

      alias Entry = Tuple!(long, "cost", int, "a", int, "b");
      auto es = new Entry[N];
      foreach (u; 0 .. N) {
        es[u] = Entry(C[u], dis[u], fin[u]);
      }
      es.sort;

      auto uf = new int[zeit + 1];
      uf[] = -1;
      long total = 0;
      long thr = -1;
      foreach (ref e; es) {
        if (uf.connect(e.a, e.b)) {
          total += e.cost;
          thr = e.cost;
        }
      }

      int[] ans;
      foreach (u; 0 .. N) {
        if (C[u] <= thr) {
          ans ~= u;
        }
      }
      writeln(total, " ", ans.length);
      foreach (index, u; ans) {
        if (index > 0) write(" ");
        write(u + 1);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$.Let $$$\operatorname{MEX}$$$ of a binary string be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the string. For example, $$$\operatorname{MEX}$$$ of $$$001011$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the string at least once, $$$\operatorname{MEX}$$$ of $$$1111$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the string and $$$0 < 2$$$.A binary string $$$s$$$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string.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.What is the minimal sum of $$$\operatorname{MEX}$$$ of all substrings pieces can be?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single binary string $$$s$$$ ($$$1 \le |s| \le 10^5$$$). It's guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal sum of $$$\operatorname{MEX}$$$ of all substrings that it is possible to get by cutting $$$s$$$ optimally.

NoteIn the first test case the minimal sum is $$$\operatorname{MEX}(0) + \operatorname{MEX}(1) = 1 + 0 = 1$$$.In the second test case the minimal sum is $$$\operatorname{MEX}(1111) = 0$$$.In the third test case the minimal sum is $$$\operatorname{MEX}(01100) = 2$$$.

immutable multi = true;

void solve(int)
{
	auto s = readString;
	int i = 0;
	int[2] cnt;
	while (i < s.length)
	{
		char ch = s[i];
		while (i+1 < s.length && s[i+1] == ch) i++;
		cnt[ch-'0']++;
		i++;
	}
	if (cnt[0] == 0)
	{
		return writeln(0);
	}
	if (cnt[1] == 0)
	{
		return writeln(1);
	}
	if (cnt[0] == 1)
	{
		return writeln(1);
	}
	return writeln(2);
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(i; 0..t){
	auto str = readln.strip();
	string result;
	while (str.length > 0)
	{
		result ~= str[0];
		str = str.stripLeft(str[0]);
	}
	if (result.length > 3)
		writeln(2);
	else if (result == "0")
		writeln(1);
	else if (result == "1")
		writeln(0);
	else if (result == "01" || result == "10")
		writeln(1);
	else if (result == "101")
		writeln(1);
	else
		writeln(2);
    }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    auto s = readln.strip;
    long ans = 0;
    char last = 0;
    foreach (ch ; s) {
      if (last != ch) {
        ans += (ch == '0');
      }
      last = ch;
    }
    writeln(min(2, ans));
  }
}

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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

//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 long[](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;

		long cnt = s[0] == '0' ? 1 : 0;
		foreach (i; 0..s.length-1)
		{
			if (s[i] == '1' && s[i+1] == '0')
				++cnt;
		}
		ans[ti] = min(cnt, 2);
	}

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

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

int solve (string s)
{
	s = s.strip ('1');
	if (s.empty)
	{
		return 0;
	}
	if (s.all !(q{a == '0'}))
	{
		return 1;
	}
	return 2;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.solve.writeln;
	}
}


You are given array ai of length n. You may consecutively apply two operations to this array:  remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins;  change some elements of the array by at most 1, and pay b coins for each change. Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.

The first line of the input contains integers n, a and b (1 ≤ n ≤ 1 000 000, 0 ≤ a, b ≤ 109) — the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively. The second line contains n integers ai (2 ≤ ai ≤ 109) — elements of the array.

Print a single number — the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.

NoteIn the first sample the optimal way is to remove number 3 and pay 1 coin for it.In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2·3 + 2 = 8 coins.

module acmd;

import std.stdio;
import std.conv;
import std.algorithm;
import std.string;
import std.container;
import std.array;
import std.numeric;
import std.range;

int[] nums;
long a, b;

long solve () {
   int[] divs;
   int snum = nums[0];
   for (int i = 2; i * i <= snum; i++) {
      if (snum % i == 0) {
         divs ~= i;
         snum /= i;
      }
      while (snum % i == 0)
         snum /= i;
   }
   if (snum > 1)
      divs ~= snum;
   long mincost = (nums.length - 1) * a;
   foreach (div; divs) {
      const long inf = mincost + mincost;
      auto dp = Array!(long[3])(repeat!(long[3])([0L, inf, inf], nums.length));
      foreach (i, num; nums[1 .. $]) {
         i++;
         if (num % div == 0) {
            dp[i][0] = dp[i - 1][0];
            dp[i][1] = min (dp[i - 1][0], dp[i - 1][1]) + a;
            dp[i][2] = min (dp[i - 1][1], dp[i - 1][2]);
         } else if ((num - 1) % div == 0 || (num + 1) % div == 0) {
            dp[i][0] = dp[i - 1][0] + b;
            dp[i][1] = min (dp[i - 1][0], dp[i - 1][1]) + a;
            dp[i][2] = min (dp[i - 1][1], dp[i - 1][2]) + b;
         } else {
            dp[i][0] = inf;
            dp[i][1] = min (dp[i - 1][0], dp[i - 1][1]) + a;
            dp[i][2] = inf;
         }
      }
      mincost = min (mincost, dp[$ - 1][0], dp[$ - 1][1], dp[$ - 1][2]);
   }
   return mincost;
}

int main () {
   version (offline_judje) {
      stdin.reopen ("input.txt", "rt");
   }

   int n;
   readf!"%d %d %d\n" (n, a, b);
   nums = to!(int[])(readln.split);
   long ans = solve ();
   nums[0]--; ans = min (ans, solve () + b);
   nums[0] += 2; ans = min (ans, solve () + b);
   nums[0]--;
   nums.reverse ();
   ans = min (ans, solve ());
   nums[0]--; ans = min (ans, solve () + b);
   nums[0] += 2; ans = min (ans, solve () + b);
   writeln (ans);

   return 0;
}


Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya  if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value  for any positive integer x?Note, that  means the remainder of x after dividing it by y.

The first line of the input contains two integers n and k (1 ≤ n,  k ≤ 1 000 000) — the number of ancient integers and value k that is chosen by Pari. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 1 000 000).

Print "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.

NoteIn the first sample, Arya can understand  because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what  is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7.

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

immutable int NA = -1;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto c = readln.split.map !(to !(int)).array;
		int [] p;
		int [] q;
		int [] r;
		for (int d = 2; d <= k; d++)
		{
			if (k % d == 0)
			{
				p ~= d;
				q ~= 0;
				r ~= 0;
				do
				{
					q[$ - 1]++;
					k /= d;
				}
				while (k % d == 0);
			}
		}
		foreach (cur; c)
		{
			foreach (i; 0..p.length)
			{
				int s = 0;
				while (cur % p[i] == 0)
				{
					cur /= p[i];
					s++;
				}
				r[i] = max (r[i], s);
			}
		}
		writeln (p.length.iota.all
		    !(x => q[x] <= r[x]) ? "Yes" : "No");
	}
}

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

immutable int MAXN = cast(int)1e6;

int[MAXN + 5] Pr, nx, cnt;

void sieve() {
	Pr[0] = Pr[1] = 0;
	foreach(i; 2..MAXN) Pr[i] = 1;
	foreach(i; 2..MAXN) if (Pr[i]) {
		for(int j = i; j <= MAXN; j += i) nx[j] = i, Pr[j] = 0;
	}
}

int N, K;

void add(int x, void function(ref int a, in int b) f) {
	while (x > 1) {
		int c = 0, t = nx[x];
		while (x % t == 0) {
			++c; x /= t;
		}
		f(cnt[t], c);
	}
}

void main() {
	sieve();
	readf("%d %d", &N, &K);
	foreach(i; 1..N+1) {
		int inp; readf(" %d", &inp);
		add(inp, function(ref int a, in int b) { a = max(a, b); });
	}
	add(K, function(ref int a, in int b) { a -= b; });
	foreach (i; cnt) if (i < 0) {
		writef("No\n"); return;
	}
	writef("Yes\n");
}