You are a coach at your local university. There are $$$n$$$ students under your supervision, the programming skill of the $$$i$$$-th student is $$$a_i$$$.You have to form $$$k$$$ teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than $$$k$$$ (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than $$$5$$$. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).It is possible that some students not be included in any team at all.Your task is to report the maximum possible total number of students in no more than $$$k$$$ (and at least one) non-empty balanced teams.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the number of students and the maximum number of teams, correspondingly. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is a programming skill of the $$$i$$$-th student.

Print one integer — the maximum possible total number of students in no more than $$$k$$$ (and at least one) non-empty balanced teams.

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;

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

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array;

    debug { arr.writeln; }

    arr.sort();

    auto dp = new int[][] (n+1, k+1);
    foreach (ref rw; dp) rw.fill(0);

    int prev = 0;
    foreach (i; 1 .. n+1) {
        int mnval = arr[i] - 5;
        while (arr[prev+1] < mnval) { prev += 1; }

        foreach (j; 1 .. k+1) {
            dp[i][j] = max(dp[i-1][j], dp[prev][j-1] + i - prev);
        }
    }

    debug { dp.each!writeln; }

    dp[n][k].writeln;
}

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;

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

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array;

    debug { arr.writeln; }

    arr.sort();

    auto dp = new int[][] (n+1, k+1);
    foreach (ref rw; dp) rw.fill(0);

    foreach (i; 1 .. n+1) {
        int mnval = arr[i] - 5;
        auto bigger = arr[1 .. $].assumeSorted.upperBound(mnval - 1);

        int prev = n - (bigger.length.to!int);

        foreach (j; 1 .. k+1) {
            dp[i][j] = max(dp[i-1][j], dp[prev][j-1] + i - prev);
        }
    }

    debug { dp.each!writeln; }

    dp[n][k].writeln;
}


You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

For each test case print one integer — the maximum distance between two rivaling students which you can obtain.

NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.

import std.stdio;
import std.algorithm;

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int n, x, a, b;
    readf(" %s %s %s %s", &n, &x, &a, &b);
    if(a > b) swap(a, b);
    int d = min(x, a - 1);
    a -= d;
    x -= d;
    d = min(n - b, x);
    b += d;
    x -= d;
    writef("%s\n", b - a);
  }
}

import std.stdio;
import std.math;
int main()
{
	int a=0;
	readf(" %d", &a);
	for (int i=0; i<a; i++)
	{
		int b=0;
		int c=0;
		int d=0;
		int e=0;
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		readf(" %d", &e);
		if (abs(d-e)+c>=b)
		{
			writeln(b-1);
		}
		else
		{
			writeln(abs(d-e)+c);
		}
	}
	return 0;
}

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto a = RD!int-1;
		auto b = RD!int-1;
		auto aa = min(a, b);
		auto bb = max(a, b);
		auto cnt1 = min(aa, x);
		x -= cnt1;
		aa -= cnt1;
		auto cnt2 = min(n-bb-1, x);
		bb += cnt2;
		ans[i] = bb - aa;
	}

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

import std.stdio;
import std.math;
int main()
{
	int a=0;
	readf(" %d", &a);
	for (int i=0; i<a; i++)
	{
		int b=0;
		int c=0;
		int d=0;
		int e=0;
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		readf(" %d", &e);
		if (abs(d-e)+c>=b)
		{
			writeln(b-2);
		}
		else
		{
			writeln(abs(d-e)+c);
		}
	}
	return 0;
}


Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j < i)

The first line of input contains a string s of length n (1 ≤ n ≤ 3·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.

The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.

NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx.

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;

void main()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r();
    auto t = r();

    debug { writeln(s, ' ', t); }

    int n = s.length.to!int;
    auto ans = new dchar[] (n);
    auto sl = DList!dchar(s.sort().array[0 .. (n+1) / 2]);
    auto tl = DList!dchar(t.sort().array[(n+1) / 2 .. $]);

    debug { sl.each!write; writeln; tl.each!write; writeln; }

    int lft = 0, rt = n-1;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = sl.front;
                sl.removeFront();
                lft += 1;
            } else {
                ans[rt] = sl.back;
                sl.removeBack();
                rt -= 1;
            }
        } else {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = tl.back;
                tl.removeBack();
                lft += 1;
            } else {
                ans[rt] = tl.front;
                tl.removeFront();
                rt -= 1;
            }
        }
    }

    ans.writeln;
}

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;

void main()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r();
    auto t = r();

    debug { writeln(s, ' ', t); }

    int n = s.length.to!int;
    auto ans = new dchar[] (n);
    auto sl = DList!dchar(s.sort().array[0 .. (n+1) / 2]);
    auto tl = DList!dchar(t.sort().array[(n+1)/2 .. $]);

    debug { writeln(sl.back, ' ', tl.front); }

    int lft = 0, rt = n-1;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = sl.front;
                sl.removeFront();
                lft += 1;
            } else {
                ans[rt] = sl.back;
                sl.removeBack();
                rt -= 1;
            }
        } else {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = tl.back;
                tl.removeBack();
                lft += 1;
            } else {
                ans[rt] = tl.front;
                tl.removeFront();
                rt -= 1;
            }
        }
    }

    ans.writeln;
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const S = readToken();
      const T = readToken();
      const N = cast(int)(S.length);

      auto as = new int[N];
      auto bs = new int[N];
      foreach (i; 0 .. N) {
        as[i] = S[i] - 'a';
        bs[i] = T[i] - 'a';
      }
      as.sort;
      bs.sort;
      int al = 0, ar = (N + 1) / 2;
      int bl = N - N / 2, br = N;

      auto cs = new int[N];
      int cl = 0, cr = N;
      for (; ; ) {
        // min
        if (al == ar) {
          break;
        }
        if (bl == br || as[al] < bs[br - 1]) {
          cs[cl++] = as[al++];
        } else {
          cs[--cr] = as[--ar];
        }
        // max
        if (bl == br) {
          break;
        }
        if (al == ar || bs[br - 1] > as[al]) {
          cs[cl++] = bs[--br];
        } else {
          cs[--cr] = bs[bl++];
        }
      }

      auto ans = new char[N];
      foreach (i; 0 .. N) {
        ans[i] = cast(char)('a' + cs[i]);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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;

void main()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r();
    auto t = r();

    debug { writeln(s, ' ', t); }

    int n = s.length.to!int;
    auto ans = new dchar[] (n);
    auto sl = DList!dchar(s.sort().array[0 .. (n+1) / 2]);
    auto tl = DList!dchar(t.sort().array[(n+1)/2 .. $]);

    debug { writeln(sl.back, ' ', tl.front); }

    int lft = 0, rt = n-1;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            if (i == n-1 || sl.front <= tl.back) {
                ans[lft] = sl.front;
                sl.removeFront();
                lft += 1;
            } else {
                ans[rt] = sl.back;
                sl.removeBack();
                rt -= 1;
            }
        } else {
            if (i == n-1 || sl.front <= tl.back) {
                ans[lft] = tl.back;
                tl.removeBack();
                lft += 1;
            } else {
                ans[rt] = tl.front;
                tl.removeFront();
                rt -= 1;
            }
        }
    }

    ans.writeln;
}

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 MX = 5000;

void main()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r().sort();
    auto t = r().sort();

    debug { writeln(s, ' ', t); }

    string ans;
    int sidx = 0, tidx = t.length.to!int - 1;
    foreach (i; 0 .. s.length) {
        if (i % 2 == 0) {
            ans ~= s[sidx];
            sidx += 1;
        } else {
            ans ~= t[tidx];
            tidx -= 1;
        }
    }

    ans.writeln;
}


Aleksey has $$$n$$$ friends. He is also on a vacation right now, so he has $$$m$$$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $$$m$$$ days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 100\,000$$$) standing for the number of friends and the number of days to play, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains an integer $$$k_i$$$ ($$$1\leq k_i\leq n$$$), followed by $$$k_i$$$ distinct integers $$$f_{i1}$$$, ..., $$$f_{ik_i}$$$ ($$$1\leq f_{ij}\leq n$$$), separated by spaces — indices of available friends on the day $$$i$$$. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$100\,000$$$. It's guaranteed that the sum of all $$$k_i$$$ over all days of all test cases doesn't exceed $$$200\,000$$$.

Print an answer for each test case. If there is no way to achieve the goal, print "NO". Otherwise, in the first line print "YES", and in the second line print $$$m$$$ space separated integers $$$c_1$$$, ..., $$$c_m$$$. Each $$$c_i$$$ must denote the chosen friend on day $$$i$$$ (and therefore must be one of $$$f_{ij}$$$). No value must occur more than $$$\left\lceil\dfrac{m}{2}\right\rceil$$$ times. If there is more than one possible answer, print any of them.

import std.stdio;
import std.container;
import std.algorithm;

/*
a[i]-a[i-1] = c (mod m)
a[1] = s mod m
m > a[i] for i=1,...,n

arbitrary s
m | a[1]-s
m | a[i]-(a[i-1]+c) = a[i]-a[i-1]-c

1 positive, 1 negative at MAX
a = -b => mod is a-(-b).

if only positive or only negative, m can be arbitrary large
if >1 pos or >1 neg, impossible.
*/

void main() {
    int t; readf(" %d",&t);
    while (t--) {
        int n,m; readf(" %d %d",&n,&m);
        int[][] a = new int[][](m+1);
        int[] id = new int[m+1];
        foreach (int i, ref e; id) {e=i;}
        //writeln("id=",id);
        foreach (i; 1..m+1) {
            int k_i; readf(" %d",&k_i);
            foreach(j; 0..k_i) {
                int x; readf(" %d",&x);
                a[i] ~= x;
            }
            sort((a[i])[0..$]);
        }
        auto cmp = delegate bool(int i, int j) {
            if (a[i].length != a[j].length) return a[i].length < a[j].length;
            return a[i]<a[j];
        };
        sort!(cmp)(id[1..$]);
        //writeln(id);

        int[] cnt = new int[n+1];
        bool feasible = true;
        int[] sol = new int[m+1];
        foreach (i; id[1..$]) {
            bool flag = false;
            int[] b = a[i];
            foreach (e; b) {
                if (cnt[e]<(m+1)/2) {
                    flag = true;
                    sol[i] = e;
                    ++cnt[e];
                    break;
                }
            }
            if (!flag) {
                feasible = false;
                break;
            }
        }
        if (feasible) {
            writeln("YES");
            foreach (e; sol[1..$]) {
                write(e," ");
            }
            writeln();
        }
        else writeln("NO");
    }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
bool DEBUG = 0; void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void main(string[] args){ if(args.canFind("-debug")) DEBUG = 1;
if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve; }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ std.stdio.write(t, " "), print(a); }
string unsplit(T)(T xs, string d=" "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; } T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){ T m=(l+r)/2; (f(m)?l:r)=m; return f(l)?f(r-1)?r:mid(l,r,f):l; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void gen(){ // テストケース
	int t = uniform(1, 5);
	t.print;
	foreach(_; 0 .. t){
		int n = uniform(1, 5), m = uniform(1, 5);
		print(n, m);
		foreach(j; 0 .. m){
			int[] as;
			foreach(i; 0 .. n) if(uniform(0, 2) == 0) as ~= i;
			if(as.length == 0) as ~= uniform(0, n);
			as.randomShuffle;
			print(as.length, as.map!(a => a + 1).unsplit);
		}
	}
}
void jury(){ // 愚直解
	int q = scan!int;
	int[] ns, ms;
	int[][][] ar = new int[][][](q);
	foreach(t; 0 .. q){
		int n = scan!int, m = scan!int;
		ns ~= n, ms ~= m;
		foreach(j; 0 .. m){
			int k = scan!int;
			int[] as = scan!int(k).map!(x => x - 1).array;
			ar[t] ~= as;
		}
	}
	foreach(t; 0 .. q){
		string yesno = scan;
		if(yesno == "NO") "NO".print;
		else{
			int[] ans = scan!int(ms[t]).map!(a => a - 1).array;
			int[] cnt = new int[](ns[t]);
			foreach(j, an; ans){
				if( ! ar[t][j].canFind(an)) print("not available", j + 1);
				cnt[an] += 1;
			}
			foreach(i; 0 .. ns[t]) if(cnt[i] > (ms[t] + 1) / 2) print("too much", i + 1);
			"YES".print;
			ans.map!(a => a + 1).unsplit.print;
		}
	}
}
void solve(){ // 提出解
	A: foreach(_; 0 .. scan!int){
		int n = scan!int, m = scan!int;
		int ceilm2 = (m + 1) / 2;
		int[][] ass;
		int[][] lones = new int[][](n);
		int[][] others = new int[][](n);
		foreach(j; 0 .. m){
			int k = scan!int;
			int[] as = scan!int(k).map!(x => x - 1).array;
			if(as.length == 1) lones[as[0]] ~= j;
			else foreach(a; as) others[a] ~= j;
			ass ~= as;
		}
		log("ass:", ass);
		log("lones:", lones);
		log("others:", others);

		foreach(i; 0 .. n){
			if(lones[i].length > ceilm2){
				"NO".print;
				continue A;
			}
		}
		int[][] us = new int[][](n);
		int[] ans = new int[](m);
		ans.fill(-1);

		int foundi = -1;
		B: foreach(i; 0 .. n){
			if(lones[i].length + others[i].length >= ceilm2){
				// found
				foundi = i;
				foreach(j; lones[i]) us[i] ~= j, ans[j] = i;
				foreach(j; others[i]){
					if(us[i].length == ceilm2) break;
					us[i] ~= j, ans[j] = i;
				}
				log("i:", i, "found", "us:", us, "ans:", ans);
				break B;
			}
		}
		foreach(j; 0 .. m){
			if(ans[j] >= 0) continue;
			if(ass[j][0] == foundi) ans[j] = ass[j][1];
			else ans[j] = ass[j][0];
		}

		"YES".print;
		ans.map!(a => a + 1).array.unsplit.print;

	}
}
/*
一人での出現回数がceil(m/2)を超えている人がいる場合
	→NO
複数名での出現を含めてならceil(m/2)を超えている人がいる場合
	→その人にぴったりceil(m/2)回を取らせればあとはてきとうでよい
	　そのために、一人での出現回はその人にとらせ、
	　あとはceil(m/2)になるまでとらせる。その人はもう終わり。
出現回数ceil(m/2)を超えている人がいない場合
	→絶対安全なのでてきとうに取ればよい
*/

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
bool DEBUG = 0; void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void main(string[] args){ if(args.canFind("-debug")) DEBUG = 1;
if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve; }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ std.stdio.write(t, " "), print(a); }
string unsplit(T)(T xs, string d=" "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; } T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){ T m=(l+r)/2; (f(m)?l:r)=m; return f(l)?f(r-1)?r:mid(l,r,f):l; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void gen(){ // テストケース
}
void jury(){ // 愚直解
}
void solve(){ // 提出解
	A: foreach(_; 0 .. scan!int){
		int n = scan!int, m = scan!int;
		int ceilm2 = (m + 1) / 2;
		int[][] ass;
		int[][] lones = new int[][](n);
		int[][] others = new int[][](n);
		foreach(j; 0 .. m){
			int k = scan!int;
			int[] as = scan!int(k).map!(x => x - 1).array;
			if(as.length == 1) lones[as[0]] ~= j;
			else foreach(a; as) others[a] ~= j;
			ass ~= as;
		}
		log("ass:", ass);
		log("lones:", lones);
		log("others:", others);

		foreach(i; 0 .. n){
			if(lones[i].length > ceilm2){
				"NO".print;
				continue A;
			}
		}
		int[][] us = new int[][](n);
		int[] ans = new int[](m);
		ans.fill(-1);

		B: foreach(i; 0 .. n){
			if(lones[i].length + others[i].length >= ceilm2){
				// found
				foreach(j; lones[i]) us[i] ~= j, ans[j] = i;
				foreach(j; others[i]){
					if(us[i].length == ceilm2) break;
					us[i] ~= j, ans[j] = i;
				}
				foreach(j; 0 .. m){
					if(ans[j] >= 0) continue;
					if(ass[j][0] == i) ans[j] = ass[j][1];
					else ans[j] = ass[j][0];
				}
				log("i:", i, "found", "us:", us, "ans:", ans);
				break B;
			}
		}

		"YES".print;
		ans.map!(a => a + 1).array.unsplit.print;

	}
}
/*
一人での出現回数がceil(m/2)を超えている人がいる場合
	→NO
複数名での出現を含めてならceil(m/2)を超えている人がいる場合
	→その人にぴったりceil(m/2)回を取らせればあとはてきとうでよい
	　そのために、一人での出現回はその人にとらせ、
	　あとはceil(m/2)になるまでとらせる。その人はもう終わり。
出現回数ceil(m/2)を超えている人がいない場合
	→絶対安全なのでてきとうに取ればよい
*/


Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$)  — the length of the given permutation. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ ($$$1 \leq a_{i} \leq n$$$)  — the initial permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.

NoteIn the first permutation, it is already sorted so no exchanges are needed.It can be shown that you need at least $$$2$$$ exchanges to sort the second permutation.$$$[3, 2, 4, 5, 1, 6, 7]$$$Perform special exchange on range ($$$1, 5$$$)$$$[4, 1, 2, 3, 5, 6, 7]$$$Perform special exchange on range ($$$1, 4$$$)$$$[1, 2, 3, 4, 5, 6, 7]$$$

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto p0 = enumerate (p);
		auto p1 = p0.find !(q{a[0] != a[1]});
		auto p2 = p1.find !(q{a[0] == a[1]});
		auto p3 = p2.find !(q{a[0] != a[1]});
		writeln (p1.empty ? 0 : p3.empty ? 1 : 2);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int(-1);

		int mode;
		foreach (i; 0..n)
		{
			if (a[i] == i)
			{
				if (mode == 1)
					mode = 2;
			}
			else
			{
				if (mode == 0)
					mode = 1;
				else if (mode == 2)
					mode = 3;
			}
		}

		if (mode == 0) continue;
		else if (mode == 1 || mode == 2)
			ans[ti] = 1;
		else
			ans[ti] = 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;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto s = n.iota.map !(i => i == p[i]).sum;
		writeln (s == n ? 0 : s == 0 ? 1 : 2);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto p0 = enumerate (p);
		writeln (p0);
		auto p1 = p0.find !(q{a[0] != a[1]});
		auto p2 = p1.find !(q{a[0] == a[1]});
		auto p3 = p2.find !(q{a[0] != a[1]});
		writeln (p1.empty ? 0 : p3.empty ? 1 : 2);
	}
}


The only difference between easy and hard versions is a number of elements in the array.You are given an array $$$a$$$ consisting of $$$n$$$ integers. The value of the $$$i$$$-th element of the array is $$$a_i$$$.You are also given a set of $$$m$$$ segments. The $$$j$$$-th segment is $$$[l_j; r_j]$$$, where $$$1 \le l_j \le r_j \le n$$$.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array $$$a = [0, 0, 0, 0, 0]$$$ and the given segments are $$$[1; 3]$$$ and $$$[2; 4]$$$ then you can choose both of them and the array will become $$$b = [-1, -2, -2, -1, 0]$$$.You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array $$$a$$$ and obtain the array $$$b$$$ then the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 300, 0 \le m \le 300$$$) — the length of the array $$$a$$$ and the number of segments, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$), where $$$a_i$$$ is the value of the $$$i$$$-th element of the array $$$a$$$. The next $$$m$$$ lines are contain two integers each. The $$$j$$$-th of them contains two integers $$$l_j$$$ and $$$r_j$$$ ($$$1 \le l_j \le r_j \le n$$$), where $$$l_j$$$ and $$$r_j$$$ are the ends of the $$$j$$$-th segment.

In the first line of the output print one integer $$$d$$$ — the maximum possible value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ if $$$b$$$ is the array obtained by applying some subset of the given segments to the array $$$a$$$. In the second line of the output print one integer $$$q$$$ ($$$0 \le q \le m$$$) — the number of segments you apply. In the third line print $$$q$$$ distinct integers $$$c_1, c_2, \dots, c_q$$$ in any order ($$$1 \le c_k \le m$$$) — indices of segments you apply to the array $$$a$$$ in such a way that the value $$$\max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i$$$ of the obtained array $$$b$$$ is maximum possible. If there are multiple answers, you can print any.

NoteIn the first example the obtained array $$$b$$$ will be $$$[0, -4, 1, 1, 2]$$$ so the answer is $$$6$$$.In the second example the obtained array $$$b$$$ will be $$$[2, -3, 1, -1, 4]$$$ so the answer is $$$7$$$.In the third example you cannot do anything so the answer is $$$0$$$.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto LR = new Tuple!(int, int, int)[](M);
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        LR[i] = tuple(s[0]-1, s[1]-1, i);
    }
    LR.sort();

    auto pq = new BinaryHeap!(Array!(Tuple!(int, int, int)), "a[1] > b[1]")();
    auto st = new LazySegmentTree!(long, long, min, (a,b)=>a+b, (a,b)=>a+b, (a,b)=>a, 1L<<59, 0L)(N+1);
    st.table[] = 0L;

    foreach (i; 0..N) st.update(i, i, A[i]);
    foreach (i; 0..M) st.update(LR[i][0], LR[i][1], -1);

    int p = 0;
    long maxv = 0;
    long maxi = 0;

    foreach (i; 0..N) {
        while (p < M && LR[p][0] == i) {
            st.update(LR[p][0], LR[p][1], 1);
            pq.insert(LR[p]);
            ++p;
        }
        while (!pq.empty && pq.front[1] < i) {
            st.update(pq.front[0], pq.front[1], -1);
            pq.removeFront;
        }

        long tmp = st.query(i, i) - st.query(0, N-1);
        if (tmp >= maxv)  {
            maxv = tmp;
            maxi = i;
        }
    }

    Tuple!(int, int, int)[] seg;
    foreach (i; 0..M) {
        if (LR[i][1] < maxi || LR[i][0] > maxi) {
            seg ~= LR[i];
        }
    }

    maxv.writeln;
    seg.sort!"a[2] < b[2]";
    seg.length.writeln;
    foreach (sg; seg) {
        write(sg[2]+1, " ");
    }
    writeln;
}

class LazySegmentTree(T, L, alias opTT, alias opTL, alias opLL, alias opPrd, T eT, L eL) {
    T[] table;
    L[] lazy_;
    int n;
    int size;

    this(int n) {
        this.n = n;
        size = 1;
        while (size <= n) size <<= 1;
        size <<= 1;
        table = new T[](size);
        lazy_ = new L[](size);
        table[] = eT;
        lazy_[] = eL;
    }

    void push(int i, int a, int b) {
        if (lazy_[i] == eL) return;
        table[i] = opTL(table[i], opPrd(lazy_[i], b - a + 1));
        if (i * 2 + 1 < size) {
            lazy_[i*2] = opLL(lazy_[i*2], lazy_[i]);
            lazy_[i*2+1] = opLL(lazy_[i*2+1], lazy_[i]);
        }
        lazy_[i] = eL;
    }

    T query(int l, int r) {
        if (l > r) return eT;
        return query(l, r, 1, 0, n-1);
    }

    T query(int l, int r, int i, int a, int b) {
        if (b < l || r < a) return eT;
        push(i, a, b);
        if (l <= a && b <= r) {
            return table[i];
        } else {
            return opTT(query(l, r, i*2, a, (a+b)/2), query(l, r, i*2+1, (a+b)/2+1, b));
        }
    }

    void update(int l, int r, L val) {
        if (l > r) return;
        update(l, r, 1, 0, n-1, val);
    }

    void update(int l, int r, int i, int a, int b, L val) {
        if (b < l || r < a) {
            push(i, a, b);
        } else if (l <= a && b <= r) {
            lazy_[i] = opLL(lazy_[i], val);
            push(i, a, b);
        } else {
            push(i, a, b);
            update(l, r, i*2, a, (a+b)/2, val);
            update(l, r, i*2+1, (a+b)/2+1, b, val);
            table[i] = opTT(table[i*2], table[i*2+1]);
        }
    }
}

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;

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

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

    Tuple!(int, int, int)[] s;

    foreach (i; 0 .. m) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        --le, --r;
        s ~= tuple(le, r, i+1);
    }

    s.sort();

    auto rbt = make!(RedBlackTree!(int, "a < b", true));
    foreach (e; arr) { rbt.insert(e); }

    debug { rbt.writeln; }

    int mx = 0;
    int[] ans;
    auto curseg = make!(RedBlackTree!int);
    auto ends = new Tuple!(int, int)[][] (n);
    int sidx = 0;
    foreach (i; 0 .. n) {
        while (sidx < m && s[sidx][0] == i) {
            foreach (j; s[sidx][0] .. s[sidx][1] + 1) {
                rbt.removeKey(arr[j]);
                arr[j] -= 1;
                rbt.insert(arr[j]);

                curseg.insert(s[sidx][2]);
            }

            ends[s[sidx][1]] ~= tuple(s[sidx][0], s[sidx][2]);
            sidx += 1;
        }

        if (rbt.back - arr[i] > mx) {
            ans = [];
            foreach (e; curseg) { ans ~= e; }
            mx = rbt.back - arr[i];
        }

        foreach (t; ends[i]) {
            int end = t[0], segid = t[1];
            foreach (j; end .. i+1) {
                rbt.removeKey(arr[j]);
                arr[j] += 1;
                rbt.insert(arr[j]);

                curseg.removeKey(segid);
            }
        }
    }

    mx.writeln;
    ans.length.writeln;
    ans.writefln!"%(%s %)";
}


You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.

NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.

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

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

    while (t--) {
        int n, x;
        readf("%s %s", &n, &x);
        readln;

        auto s = readln.chomp;

        auto tot = s.count!(v => v == '0').to!int - s.count!(v => v == '1').to!int;

        if (tot == 0) {
            int cur = 0, mx = 0, mn = 0;
            foreach (e; s) {
                if (e == '0') { cur += 1; }
                else { cur -= 1; }

                mx = max(mx, cur);
                mn = min(mn, cur);
            }

            writeln(mn <= x && x <= mx ? -1 : 0);
            continue;
        }

        int ans = 0, cur = 0;
        foreach (e; s) {
            if ((x-cur) % tot == 0 && (x-cur) / tot >= 0) { ans += 1; }

            if (e == '0') { cur += 1; }
            else { cur -= 1; }
        }

        ans.writeln;
    }
}

//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 sign (int x) {
  if (!x) return 0;
  if (x > 0) return 1;
  return -1;
}

long test () {
  auto s = readln.splitter.map!(to!int);
  immutable n = s.front;
  s.popFront;
  immutable x = s.front;
  auto t = readln[0 .. n];
  auto a = new int[n+1];
  foreach (i; 0 .. n) {
    a[i+1] = a[i] + (t[i] == '1' ? -1 : 1);
  }
  debug stderr.writeln (a);
  immutable m = a.back;
  if (m == 0) {
    return (minElement (a) <= x && x <= maxElement (a)) ? -1 : 0;
  }
  long r = 0;
  foreach (i; 0 .. n) {
    int delta = x - a[i];
    if (m > 0) {
      if (delta >= 0 && !(delta % m)) ++r;
    } else {
      if (delta <= 0 && !((-delta) % (-m))) ++r;
    }
  }
  return r;
}

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


There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.

The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j.

Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.

NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = new int[](N);
    auto B = new int[](N);
    auto AB = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        AB[i] = tuple(s[0], s[1]);
    }
    AB.sort();
    foreach (i; 0..N) {
        A[i] = AB[i][0];
        B[i] = AB[i][1];
    }

    auto dp = new int[](N);
    foreach (i; 0..N) {
        auto lb = A.assumeSorted.lowerBound(A[i] - B[i]).length;
        if (lb > 0) dp[i] += dp[lb-1];
        dp[i] += 1;
    }

    writeln(N - dp.reduce!max);
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Point = Tuple !(int, q{a}, int, q{b});
		auto p = new Point [n];
		foreach (ref q; p)
		{
			readf (" %s %s", &q.a, &q.b);
		}
		sort (p);
		p = Point (int.min / 2, 0) ~ p;

		int res = n - 1;
		auto f = new int [n + 1];
		f[0] = 1;
		foreach (i, ref q; p)
		{
			int lo = 0;
			int hi = i - 1;
			while (lo < hi)
			{
				int me = (lo + hi + 1) >> 1;
				if (p[me].a + q.b >= q.a)
				{
					hi = me - 1;
				}
				else
				{
					lo = me;
				}
			}
			debug {writeln (p[i].a, ": ", p[lo].a);}
			f[i] = f[lo] + (i - lo - 1);
			res = min (res, f[i] + (n - i));
		}
		debug {writeln (f);}
		writeln (res);
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = new int[](N);
    auto B = new int[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        A[i] = s[0];
        B[i] = s[1];
    }

    auto dp = new int[](N);
    foreach (i; 0..N) {
        auto lb = A.assumeSorted.lowerBound(A[i] - B[i]).length;
        if (lb > 0) dp[i] += dp[lb-1];
        dp[i] += 1;
    }

    writeln(N - dp.reduce!max);
}


Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that:   r ≥ 2;  for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds;  each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:   no pair of tubes has common cells;  each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

NotePicture for the first sample:   Picture for the second sample:

import std.stdio;

void main() {
    int n, m, k;
    while (readf(" %s %s %s", &n, &m, &k)) {
        int x = 0, y = 0;
        void go() {
            if (x & 1) {
                y--;
                if (y < 0) {
                    x++;
                    y++;
                }
            } else {
                y++;
                if (y == m) {
                    x++;
                    y--;
                }
            }
        }
        foreach(i; 0..k) {
            struct pos { int x, y; }
            pos[] cur;
            if (i == k - 1) {
                while (x < n) {
                    cur ~= pos(x, y);
                    go();
                }
            } else {
                foreach (_; 0..2) {
                    cur ~= pos(x, y);
                    go();
                }
            }
            write(cur.length);
            foreach(p; cur)
                writef(" %s %s", p.x + 1, p.y + 1);
            writeln();
        }
    }
}


Monocarp is playing Minecraft and wants to build a wall of cacti. He wants to build it on a field of sand of the size of $$$n \times m$$$ cells. Initially, there are cacti in some cells of the field. Note that, in Minecraft, cacti cannot grow on cells adjacent to each other by side — and the initial field meets this restriction. Monocarp can plant new cacti (they must also fulfil the aforementioned condition). He can't chop down any of the cacti that are already growing on the field — he doesn't have an axe, and the cacti are too prickly for his hands.Monocarp believes that the wall is complete if there is no path from the top row of the field to the bottom row, such that:   each two consecutive cells in the path are adjacent by side;  no cell belonging to the path contains a cactus. Your task is to plant the minimum number of cacti to build a wall (or to report that this is impossible).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$; $$$n \times m \le 4 \cdot 10^5$$$) — the number of rows and columns, respectively. Then $$$n$$$ rows follow, $$$i$$$-th row contains a string $$$s_i$$$ of length $$$m$$$, where $$$s_{i, j}$$$ is '#', if a cactus grows at the intersection of the $$$i$$$-th row and the $$$j$$$-th column. Otherwise, $$$s_{i, j}$$$ is '.'. The sum of $$$n \times m$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case, print NO in the first line if it is impossible to build a cactus wall without breaking the rules. Otherwise, print YES in the first line, then print $$$n$$$ lines of $$$m$$$ characters each — the field itself, where the $$$j$$$-th character of the $$$i$$$-th line is equal to '#', if there is a cactus on the intersection of the $$$i$$$-th row and the $$$j$$$-th column, otherwise it is '.'. If there are multiple optimal answers, print any of them.

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

enum int INF = 1<<28;

alias Tuple!(int, "to", long, "cost") Edge;
alias Tuple!(int, "v", long, "cost") State;

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    auto F = iota(N).map!(_ => readln.chomp).array;
    bool check(int y, int x) {
        const auto dy = [-1, 0, 1, 0];
        const auto dx = [0, 1, 0, -1];
        // is it possible to place cacti at (y, x)?
        if (y < 0 || y >= N) return false;
        if (x < 0 || x >= M) return false;
        for (int k = 0; k < 4; k++) {
            int ny = y + dy[k];
            int nx = x + dx[k];
            if (ny < 0 || ny >= N) continue;
            if (nx < 0 || nx >= M) continue;
            if (F[ny][nx] == '#') return false;
        }
        return true;
    }

    int idx(int y, int x) {
        return y * M + x;
    }

    auto G = new Edge[][N * M];

    for (int y = 0; y < N; y++) {
        for (int x = 0; x < M; x++) {
            if (check(y, x)) {
                const dy = [-1, 1, 1, -1];
                const dx = [1, 1, -1, -1];
                for (int k = 0; k < 4; k++) {
                    int ny = y + dy[k];
                    int nx = x + dx[k];
                    if (check(ny, nx)) {
                        G[idx(y, x)] ~= Edge(idx(ny, nx), F[ny][nx] == '.' ? 1 : 0);
                    }
                }
            }
        }
    }

    auto PQ = heapify!"a.cost > b.cost"(new State[0], 0);
    auto D = new long[](N*M);
    D[] = long.max;
    auto P = new int[](N*M);
    P[] = -1;
    for (int y = 0; y < N; y++) {
        D[idx(y, 0)] = (F[y][0] == '#' ? 0 : 1);
        PQ.insert(State(idx(y, 0), D[idx(y, 0)]));
    }
    while (! PQ.empty) {
        State cur = PQ.front; PQ.popFront;
        if (D[cur.v] != cur.cost) continue; // this state is not optimal
        foreach (e; G[cur.v]) {
            auto nextv = e.to;
            auto nexts = State(nextv, cur.cost + e.cost);
            if (D[nexts.v] > nexts.cost) {
                D[nexts.v] = nexts.cost;
                P[nexts.v] = cur.v;
                PQ.insert(nexts);
            }
        }
    }
    long ans = long.max;
    int lasti = -1;
    for (int y = 0; y < N; y++) {
        if (ans > D[idx(y, M-1)]) {
            lasti = idx(y,M-1);
            ans = D[idx(y, M-1)];
        }
    }
    if (lasti < 0) {
        writeln("NO");
        return;
    }
    writeln("YES");

    int X(int i) {
        return i % M;
    }
    int Y(int i) {
        return i / M;
    }

    char[][] A = F.map!(L => L.dup).array;
    int i = lasti;
    while (i >= 0) {
        int x = X(i);
        int y = Y(i);
        A[y][x] = '#';
        i = P[i];
    }
    foreach (L; A) {
        writeln(L);
    }
}

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

enum int INF = 1<<28;

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    auto F = iota(N).map!(_ => readln.chomp).array;
    auto dy = [-1, 0, 1, 0];
    auto dx = [0, 1, 0, -1];
    bool check(int y, int x) {
        // is it possible to place cacti at (y, x)?
        if (y < 0 || y >= N) return false;
        if (x < 0 || x >= M) return false;
        for (int k = 0; k < 4; k++) {
            int ny = y + dy[k];
            int nx = x + dx[k];
            if (ny < 0 || ny >= N) continue;
            if (nx < 0 || nx >= M) continue;
            if (F[ny][nx] == '#') return false;
        }
        return true;
    }

    auto dp = new int[][](M, N); {
        foreach (ref L; dp) L[] = INF;
    }
    auto prev = new int[][](M, N); {
        foreach (ref L; prev) L[] = -1;
    }
    for (int y = 0; y < N; y++) {
        if (! check(y, 0)) continue;
        int c = 0;
        if (F[y][0] == '.') c = 1;
        dp[0][y] = c;
    }

    for (int x = 1; x < M; x++) {
        for (int y = 0; y < N; y++) {
            int c = (F[y][x] == '.' ? 1 : 0);
            if (! check(y, x)) continue;
            if (y-1 >= 0 && dp[x][y] > c + dp[x-1][y-1]) {
                dp[x][y] = c + dp[x-1][y-1];
                prev[x][y] = y-1;
            }
            if (y+1 < N && dp[x][y] > c + dp[x-1][y+1]) {
                dp[x][y] = c + dp[x-1][y+1];
                prev[x][y] = y+1;
            }
        }
    }
    int mincost = INF;
    int lasty = -1;
    for (int y = 0; y < N; y++) {
        if (mincost > dp[M-1][y]) {
            mincost = dp[M-1][y];
            lasty = y;
        }
    }
    if (lasty == -1) {
        writeln("NO");
        return;
    }
    writeln("YES");
    int cy = lasty;
    char[][] A = F.map!(L => L.dup).array;
    for (int x = M - 1; x >= 0; x--) {
        A[cy][x] = '#';
        cy = prev[x][cy];
    }
    foreach (L; A) {
        writeln(L);
    }
}

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

enum int INF = 1<<28;

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    auto F = iota(N).map!(_ => readln.chomp).array;
    auto dp = new int[][](M, N); {
        foreach (ref L; dp) L[] = INF;
    }
    auto prev = new int[][](M, N); {
        foreach (ref L; prev) L[] = -1;
    }
    for (int y = 0; y < N; y++) {
        int c = 0;
        if (F[y][0] == '.') c = 1;
        dp[0][y] = c;
    }

    auto dy = [-1, 0, 1, 0];
    auto dx = [0, 1, 0, -1];
    bool check(int y, int x) {
        // is it possible to place cacti at (y, x)?
        if (y < 0 || y >= N) return false;
        if (x < 0 || x >= M) return false;
        for (int k = 0; k < 4; k++) {
            int ny = y + dy[k];
            int nx = x + dx[k];
            if (ny < 0 || ny >= N) continue;
            if (nx < 0 || nx >= M) continue;
            if (F[ny][nx] == '#') return false;
        }
        return true;
    }

    for (int x = 1; x < M; x++) {
        for (int y = 0; y < N; y++) {
            int c = (F[y][x] == '.' ? 1 : 0);
            if (! check(y, x)) continue;
            if (y-1 >= 0 && dp[x][y] > c + dp[x-1][y-1]) {
                dp[x][y] = c + dp[x-1][y-1];
                prev[x][y] = y-1;
            }
            if (y+1 < N && dp[x][y] > c + dp[x-1][y+1]) {
                dp[x][y] = c + dp[x-1][y+1];
                prev[x][y] = y+1;
            }
        }
    }
    int mincost = INF;
    int lasty = -1;
    for (int y = 0; y < N; y++) {
        if (mincost > dp[M-1][y]) {
            mincost = dp[M-1][y];
            lasty = y;
        }
    }
    if (lasty == -1) {
        writeln("NO");
        return;
    }
    writeln("YES");
    int cy = lasty;
    char[][] A = F.map!(L => L.dup).array;
    for (int x = M - 1; x >= 0; x--) {
        A[cy][x] = '#';
        cy = prev[x][cy];
    }
    foreach (L; A) {
        writeln(L);
    }
}


You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.

If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.

import std.stdio;
import std.string;
import std.conv;
import std.regex;
import std.file;
void main()
{

    string[] inp=split(strip(readln()));
    int n=to!int(inp[0]);
    int p=to!int(inp[1]);
    int q=to!int(inp[2]);
    string s = strip(readln());
    //writeln(n);
    for(int i = 0;i <= n;i++)
    {
        for(int j = 0;j <= n ;j++)
        {
            if(i * p + j * q == n)
            {
                writeln(i + j);
                for(int k = 0;k < i;k++){
                    writeln(s[k*p .. (k+1)*p]);
                }
                string res=s[i*p..$];
                for(int k = 0;k < j;k++){
                    writeln(res[k*q .. (k+1)*q]);
                }
                return;

            }
        }
    }
    writeln("-1");

}

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

void main ()
{
	int n, p, q;
	string buf;
	while ((buf = readln).formattedRead (" %s %s %s", &n, &p, &q) > 0)
	{
		string s = readln.strip;
		string [] res;
		while (true)
		{
			if (s.length % q == 0)
			{
				res ~= s.chunks (q).map !(text).array;
				s = "";
				break;
			}
			if (s.length < p)
			{
				break;
			}
			res ~= s[0..p];
			s = s[p..$];
		}
		if (s.empty)
		{
			writefln ("%s\n%-(%s\n%)", res.length, res);
		}
		else
		{
			writeln (-1);
		}
	}
}

module main;

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

int main()
{
    int n, p, q;

    readf(" %d %d %d", &n, &p, &q);
    readln();

    auto s = readln().strip();

    if (n % p == 0) {
        writeln(n / p);

        for (int i = 0; i < n; i += p)
            writeln(s[i..i + p]);
    } else if (n % q == 0) {
        writeln(n / q);

        for (int i = 0; i < n; i += q)
            writeln(s[i..i + q]);
    } else {
        auto temp = n;
        int count;

        while (temp % q != 0 && temp > 0)
            temp -= p, count++;

        if (temp < 0)
            writeln(-1);
        else {
            writeln(count + temp / q);

            for (int i = 0; i < temp; i += q)
                writeln(s[i..i + q]);

            for (int i = temp; i < n; i += p)
                writeln(s[i..i + p]);
        }
    }

	return 0;
}

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

void main ()
{
	int n, p, q;
	string buf;
	while ((buf = readln).formattedRead (" %s %s %s", &n, &p, &q) > 0)
	{
		string s = readln.strip;
		string [] res;
		while (s.length >= p)
		{
			if (s.length % q == 0)
			{
				res ~= s.chunks (q).map !(text).array;
				s = "";
				break;
			}
			res ~= s[0..p];
			s = s[p..$];
		}
		if (s.empty)
		{
			writefln ("%s\n%-(%s\n%)", res.length, res);
		}
		else
		{
			writeln (-1);
		}
	}
}

module main;

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

int main()
{
    int n, p, q;

    readf(" %d %d %d", &n, &p, &q);
    readln();

    auto s = readln().strip();

    if (n % p == 0) {
        writeln(n / p);

        for (int i = 0; i < n; i += p)
            writeln(s[i..i + p]);
    } else if (n % q == 0) {
        writeln(n / q);

        for (int i = 0; i < n; i += q)
            writeln(s[i..i + q]);
    } else {
        auto temp = n;

        while (temp % q != 0 && temp > 0)
            temp -= p;

        if (temp < 0)
            writeln(-1);
        else {
            for (int i = 0; i < temp; i += q)
                writeln(s[i..i + q]);

            for (int i = temp; i < n; i += p)
                writeln(s[i..i + p]);
        }
    }

	return 0;
}


You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and π. For example, opposite directions vectors have angle equals to π.

First line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of vectors. The i-th of the following n lines contains two integers xi and yi (|x|, |y| ≤ 10 000, x2 + y2 > 0) — the coordinates of the i-th vector. Vectors are numbered from 1 to n in order of appearing in the input. It is guaranteed that no two vectors in the input share the same direction (but they still can have opposite directions).

Print two integer numbers a and b (a ≠ b) — a pair of indices of vectors with the minimal non-oriented angle. You can print the numbers in any order. If there are many possible answers, print any.

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = n.iota.map !(_ => readln.split.map !(to !(real)))
		.map !(c => atan2 (c[1], c[0]))
		.enumerate.map !(reverse).array;
	sort (a);
	a ~= a[0];
	a[n][0] += 2 * PI;
	auto b = n.iota.map !(i => tuple (a[i + 1][0] - a[i][0],
		a[i][1], a[i + 1][1])).array;
	sort (b);
	writeln (b[0][1] + 1, ' ', b[0][2] + 1);
}

import std.algorithm, std.math, std.range, std.stdio, std.typecons;

void main ()
{
    int n;
    while (readf (" %s", &n) > 0)
    {
        alias Vector = Tuple !(real, q{alpha}, int, q{num});
        auto a = new Vector [n];
        foreach (i, ref c; a)
        {
            real x, y;
            readf (" %s %s", &x, &y);
            c.alpha = atan2 (y, x);
            c.num = i + 1;
        }
        a.schwartzSort !(q{a.alpha});
        a ~= Vector (a[0].alpha + 2 * PI, a[0].num);
        auto p = n.iota.minPos !((i, j) =>
            a[i + 1].alpha - a[i].alpha <
            a[j + 1].alpha - a[j].alpha).front;
        writeln (a[p].num, ' ', a[p + 1].num);
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Vector = Tuple !(real, q{x}, real, q{y},
		    real, q{alpha}, int, q{num});
		auto a = new Vector [n];
		foreach (i, ref c; a)
		{
			readf (" %s %s", &c.x, &c.y);
			c.alpha = atan2 (c.y, c.x);
			c.num = i + 1;
		}
		a.schwartzSort !(q{a.alpha});
		a ~= Vector (a[0].x, a[0].y, a[0].alpha + 2 * PI, a[0].num);
		auto p = n.iota.minPos !((i, j) =>
		    a[i + 1].alpha - a[i].alpha <
		    a[j + 1].alpha - a[j].alpha).front;
		writeln (a[p].num, ' ', a[p + 1].num);
	}
}


Vitaly gave Maxim $$$n$$$ numbers $$$1, 2, \ldots, n$$$ for his $$$16$$$-th birthday. Maxim was tired of playing board games during the celebration, so he decided to play with these numbers. In one step Maxim can choose two numbers $$$x$$$ and $$$y$$$ from the numbers he has, throw them away, and add two numbers $$$x + y$$$ and $$$|x - y|$$$ instead. He wants all his numbers to be equal after several steps and the sum of the numbers to be minimal.Help Maxim to find a solution. Maxim's friends don't want to wait long, so the number of steps in the solution should not exceed $$$20n$$$. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than $$$20n$$$ moves.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 25\,000$$$) — the number of test cases. Each test case contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — the number of integers given to Maxim. It is guaranteed that the total sum of $$$n$$$ doesn't exceed $$$5 \cdot 10^4$$$.

For each test case print $$$-1$$$ if it's impossible to make all numbers equal. Otherwise print a single integer $$$s$$$ ($$$0 \le s \le 20n$$$) — the number of steps. Then print $$$s$$$ lines. The $$$i$$$-th line must contain two integers $$$x_i$$$ and $$$y_i$$$ — numbers that Maxim chooses on the $$$i$$$-th step. The numbers must become equal after all operations. Don't forget that you not only need to make all numbers equal, but also minimize their sum. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than $$$20n$$$ moves.

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

bool solve(const(int) N) {
  debug {
    writeln("N = ", N);
  }
  if (N == 2) {
    return false;
  }

  int[] xs, ys;
  void oper(int x, int y) {
    xs ~= x;
    ys ~= y;
  }

  int E;
  for (E = 0; 1 << E < N; ++E) {}

  auto cnt = new int[(1 << E) + 1];
  cnt[1 .. N + 1] += 1;
  foreach (e; 0 .. E) {
    foreach_reverse (f; 1 .. E + 1) {
      for (int y = 1 << e; y < 1 << (f - 1); y += (1 << (e + 1))) {
        const x = (1 << f) - y;
        const z = x + y, w = x - y;
        for (; cnt[x] > 0 && cnt[y] > 0; ) {
          oper(x, y);
          --cnt[x];
          --cnt[y];
          ++cnt[z];
          ++cnt[w];
        }
      }
    }
  }
  debug {
    writeln("cnt = ", cnt);
  }
  foreach (x; 1 .. (1 << E) + 1) {
    if (cnt[x] > 0) {
      assert(!(x & x - 1));
    }
  }

  foreach (e; 0 .. E) {
    const x = 1 << e;
    if (cnt[x] >= 2) {
      oper(x, x);
      --cnt[x];
      --cnt[x];
      ++cnt[x << 1];
      ++cnt[0];
      goto found;
    }
  }
  assert(false);
 found:
  debug {
    writeln("cnt = ", cnt);
  }
  foreach (e; 0 .. E) {
    const x = 1 << e;
    for (; cnt[x] > 0; ) {
      oper(x, 0);
      oper(x, x);
      --cnt[x];
      ++cnt[x << 1];
    }
  }
  oper(1 << E, 0);

  //*
  writeln(xs.length);
  foreach (i; 0 .. xs.length) {
    writeln(xs[i], " ", ys[i]);
  }
  //*/
  return true;
}

void main() {
  debug {
    foreach (N; 2 .. 100 + 1) {
      solve(N);
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;

        const res = solve(N);
        if (!res) {
          writeln(-1);
        }
      }
    }
  } 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)); }

bool solve(const(int) N) {
  debug {
    writeln("N = ", N);
  }
  if (N == 2) {
    return false;
  }

  int[] xs, ys;
  void oper(int x, int y) {
    xs ~= x;
    ys ~= y;
  }

  int E;
  for (E = 0; 1 << E < N; ++E) {}

  auto cnt = new int[(1 << E) + 1];
  cnt[1 .. N + 1] += 1;
  foreach (e; 0 .. E) {
    foreach_reverse (f; 1 .. E + 1) {
      for (int y = 1 << e; y < 1 << (f - 1); y += (1 << (e + 1))) {
        const x = (1 << f) - y;
        const z = x + y, w = x - y;
        for (; cnt[x] > 0 && cnt[y] > 0; ) {
          oper(x, y);
          --cnt[x];
          --cnt[y];
          ++cnt[z];
          ++cnt[w];
        }
      }
    }
  }
  debug {
    writeln("cnt = ", cnt);
  }
  foreach (x; 1 .. (1 << E) + 1) {
    if (cnt[x] > 0) {
      assert(!(x & x - 1));
    }
  }

  foreach (e; 0 .. E) {
    const x = 1 << e;
    if (cnt[x] >= 2) {
      oper(x, x);
      --cnt[x];
      --cnt[x];
      ++cnt[x << 1];
      ++cnt[0];
      goto found;
    }
  }
  assert(false);
 found:
  debug {
    writeln("cnt = ", cnt);
  }
  foreach (e; 0 .. E) {
    const x = 1 << e;
    for (; cnt[x] > 0; ) {
      oper(x, 0);
      oper(x, 0);
      --cnt[x];
      ++cnt[x << 1];
    }
  }
  oper(1 << E, 0);

  //*
  writeln(xs.length);
  foreach (i; 0 .. xs.length) {
    writeln(xs[i], " ", ys[i]);
  }
  //*/
  return true;
}

void main() {
  debug {
    foreach (N; 2 .. 100 + 1) {
      solve(N);
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;

        const res = solve(N);
        if (!res) {
          writeln(-1);
        }
      }
    }
  } 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)); }

bool solve(const(int) N) {
  if (N == 2) {
    return false;
  }
  const e = bsr(N + 1);
  if (!(N == (1 << e) - 1 || N == (1 << e))) {
    return false;
  }

  int[] xs, ys;
  void oper(int x, int y) {
    xs ~= x;
    ys ~= y;
  }

  const half = 1 << (e - 1);
  foreach (f; 0 .. e) {
    for (int x = 1 << f; x < half; x += 1 << f) {
      oper((1 << e) - x, x);
    }
  }
  oper(half, half);
  foreach (i; 2 .. e) {
    oper(half, 0);
    oper(half, half);
  }
  oper(1 << e, 0);

  writeln(xs.length);
  foreach (i; 0 .. xs.length) {
    writeln(xs[i], " ", ys[i]);
  }
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        debug {
          writeln("N = ", N);
        }

        const res = solve(N);
        if (!res) {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}


We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value  should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and".

The first line contains two integers n, m (1 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≤ li ≤ ri ≤ n, 0 ≤ qi < 230) describing the i-th limit.

If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≤ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.

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

immutable int LOG_N = 17;
immutable int MED_N = 1 << LOG_N;
immutable int MAX_N = MED_N << 1;

__gshared int [MAX_N] t;

void make_or (int l, int r, int v)
{
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			t[l] |= v;
			l++;
		}
		if (!(r & 1))
		{
			t[r] |= v;
			r--;
		}
	}
}

void or_to_and ()
{
	foreach (i; 1..MED_N)
	{
		t[2 * i + 0] |= t[i];
		t[2 * i + 1] |= t[i];
	}

	foreach_reverse (i; 1..MED_N)
	{
		t[i] = t[2 * i + 0] & t[2 * i + 1];
	}
}

int take_and (int l, int r)
{
	int res = (1 << 30) - 1;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res &= t[l];
			l++;
		}
		if (!(r & 1))
		{
			res &= t[r];
			r--;
		}
	}
	return res;
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		alias Query = Tuple !(int, "l", int, "r", int, "q");
		auto a = new Query [m];
		foreach (ref x; a)
		{
			readf (" %s %s %s", &x.l, &x.r, &x.q);
		}

		t[] = 0;

		foreach (ref x; a)
		{
			make_or (x.l, x.r, x.q);
		}

		or_to_and ();

		bool ok = true;
		foreach (ref x; a)
		{
			int s = take_and (x.l, x.r);
			if (s != x.q)
			{
				ok = false;
				break;
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln ("%(%s %)", t[MED_N + 1..MED_N + n + 1]);
		}
		else
		{
			writeln ("NO");
		}
	}
}


Mojtaba and Arpa are playing a game. They have a list of n numbers in the game.In a player's turn, he chooses a number pk (where p is a prime number and k is a positive integer) such that pk divides at least one number in the list. For each number in the list divisible by pk, call it x, the player will delete x and add  to the list. The player who can not make a valid choice of p and k loses.Mojtaba starts the game and the players alternatively make moves. Determine which one of players will be the winner if both players play optimally.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of elements in the list. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the list.

If Mojtaba wins, print "Mojtaba", otherwise print "Arpa" (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first sample test, Mojtaba can't move.In the second sample test, Mojtaba chooses p = 17 and k = 1, then the list changes to [1, 1, 1, 1].In the third sample test, if Mojtaba chooses p = 17 and k = 1, then Arpa chooses p = 17 and k = 1 and wins, if Mojtaba chooses p = 17 and k = 2, then Arpa chooses p = 17 and k = 1 and wins.

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

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

void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//freopen("output.txt", "w", core.stdc.stdio.stdout);
		/*StopWatch sw;
		sw.start;
		scope (exit)
		{
			sw.stop;
			stderr.writefln("\nTime: %d ms", sw.peek.msecs);
		}*/
	}
	int n;
	loop: while (read(n))
	{
		auto a = arread!int;
		int[][int] g;
		foreach (x; a)
		{
			for (int i = 2; i * i <= x; i++)
			{
				if (x % i == 0)
				{
					int cnt;
					while (x % i == 0)
					{
						cnt++;
						x /= i;
					}
					g[i] ~= cnt;
				}
			}
			if (x > 1)
				g[x] ~= 1;
		}
		int[int[]] q;
		int grandi(int[] v)
		{
			if (v.empty)
				return 0;
			if (v in q)
				return q[v];
			int[int] mex;
			foreach (c; 1 .. v.back + 1)
			{
				int[] v1;
				foreach (x; v)
				{
					if (x < c)
						v1 ~= x;
					else if (x > c)
						v1 ~= x - c;
				}
				mex[grandi(v1.sort().uniq().array)] = 1;
			}
			for (int x;; x++)
			{
				if (x !in mex)
					return q[v.idup] = x;
			}
			assert(0);
		}

		int ans;
		foreach (z; g)
		{
			ans ^= grandi(z.sort().uniq().array);
		}
		writeln(ans ? "Mojtaba" : "Arpa");
	}
}

import std.algorithm, std.array, std.conv, std.functional, std.range, std.stdio;
alias T = int, g = memoize!h;
T [T] f, x;
T h (T v) {
	T s;
	foreach (k; 1..30) if (v >= 1 << k) s |= 1 << g ((v >> k) | (v & ((1 << k) - 1)));
	return 30.iota.countUntil !(r => !(s & (1 << r)));
}
void main () {
	readln;
	foreach (c; readln.split.map !(to!T)) {
		foreach (d; 2..8 ^^ 5) if (!(c % d)) f[d] |= 1 << (1 + 30.iota.countUntil !(k => !!((c /= d) % d)));
		if (c > 1) x[c] = 1;
	}
	writeln (f.byValue.map!g.fold!q{a ^ b} (0) - (x.length & 1) ? "Mojtaba" : "Arpa");
}

import std.algorithm, std.array, std.conv, std.functional, std.stdio, std.string;
immutable int limit = 1 << 16;

alias g = memoize !(gImpl);
int gImpl (int v) {
	int s;
	foreach (k; 1..30)
		if (v >= 1 << k)
			s |= 1 << g ((v >> k) | (v & ((1 << k) - 1)));
	int r = 0;
	while (s & (1 << r))
		r += 1;
	return r;
}

void main () {
	int n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(int)).array;
	auto f = new int [limit];
	bool [int] once;

	foreach (c; a) {
		for (int d = 2; d < limit; d++)
			if (c % d == 0) {
				int k = 0;
				while (c % d == 0) {
					c /= d;
					k += 1;
				}
				f[d] |= 1 << k;
			}
		if (c > 1)
			once[c] = true;
	}

	int res = once.length & 1;
	foreach (v; f)
		res ^= g (v);
	writeln (res ? "Mojtaba" : "Arpa");
}

import std.algorithm, std.array, std.conv, std.range, std.stdio;
alias T = int;
T [T] f, x, g;
T h (T v) {
	if (v !in g) {
		T s;
		foreach (k; 1..30) if (v >= 1 << k) s |= 1 << h ((v >> k) | (v & ((1 << k) - 1)));
		g[v] = 30.iota.countUntil !(r => !(s & (1 << r)));
	}
	return g[v];
}
void main () {
	readln;
	foreach (c; readln.split.map !(to!T)) {
		foreach (d; 2..8 ^^ 5) if (!(c % d)) f[d] |= 1 << (1 + 30.iota.countUntil !(k => !!((c /= d) % d)));
		if (c > 1) x[c] = 1;
	}
	writeln (f.byValue.map!h.fold!q{a ^ b} (0) - (x.length & 1) ? "Mojtaba" : "Arpa");
}

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

immutable int limit = 1 << 16;

alias g = memoize !(gImpl);

int gImpl (int v)
in
{
	debug {writeln (v);}
}
out (res)
{
	debug {writeln ("g (", v, ") = ", res);}
}
body
{
	int s;
	foreach (k; 1..30)
	{
		if (v >= 1 << k)
		{
			s |= 1 << g ((v >> k) | (v & ((1 << k) - 1)));
		}
	}

	int r = 0;
	while (s & (1 << r))
	{
		r += 1;
	}
	return r;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto f = new int [limit];
		bool [int] once;

		foreach (c; a)
		{
			for (int d = 2; d < limit; d++)
			{
				if (c % d == 0)
				{
					int k = 0;
					while (c % d == 0)
					{
						c /= d;
						k += 1;
					}
					debug {writeln (d, ": ", k);}
					f[d] |= 1 << k;
				}
			}
			if (c > 1)
			{
				once[c] = true;
			}
		}

		int res = once.length & 1;
		foreach (v; f)
		{
			res ^= g (v);
		}

		writeln (res ? "Mojtaba" : "Arpa");
	}
}

import std.algorithm, std.conv, std.range, std.stdio;
int [int] f, x, g;
int h (int v) {
	if (v !in g) {
		int s, k;
		for (k = 2; v >= k; k <<= 1) s |= 1 << h (v / k | (v & (k - 1)));
		g[v] = 30.iota.countUntil !(r => !(s & (1 << r)));
	}
	return g[v];
}
void main () {
	readln;
	foreach (c; readln.split.map !(to!int)) {
		foreach (d; 2..8 ^^ 5) if (!(c % d)) f[d] |= 1 << (1 + 30.iota.countUntil !(k => !!((c /= d) % d)));
		if (c > 1) x[c] = 1;
	}
	writeln (f.byValue.map!h.fold!q{a ^ b} (x.length & 1) ? "Mojtaba" : "Arpa");
}

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

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

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

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

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

      int[int] fs;
      foreach (i; 0 .. N) {
        int a = A[i];
        for (int p = 2; p^^2 <= a; ++p) {
          if (a % p == 0) {
            int e;
            do {
              ++e;
              a /= p;
            } while (a % p == 0);
            fs[p] |= 1 << e;
          }
        }
        if (a > 1) {
          fs[a] |= 1 << 1;
        }
      }
      debug {
        writeln("fs = ", fs);
      }

      long[int] cache;
      long calc(int f) {
        long ret;
        cache.update(f, {
          long app;
          if (f) {
            foreach (e; 1 .. bsr(f) + 1) {
              const ff = ((f & ((1 << e) - 1)) | (f >> e)) & ~1;
              app |= 1L << calc(ff);
            }
          }
          ret = bsf(~app);
          debug {
            writefln("calc %b = %s", f, ret);
          }
          return ret;
        }, (ref long r) {
          return ret = r;
        });
        return ret;
      }

      long ans;
      foreach (p, f; fs) {
        ans ^= calc(f);
      }
      writeln(ans ? "Mojtaba" : "Arpa");
    }
  } catch (EOFException e) {
  }
}

import std.algorithm, std.array, std.conv, std.functional, std.range, std.stdio;
alias T = int, g = memoize!h;
T [T] f, x;
T h (T v) {
	T s;
	foreach (k; 1..30) if (v >= 1 << k) s |= 1 << g ((v >> k) | (v & ((1 << k) - 1)));
	return 30.iota.countUntil !(r => !(s & (1 << r)));
}
void main () {
	readln;
	foreach (c; readln.split.map !(to!T)) {
		foreach (d; 2..8 ^^ 5) if (!(c % d)) f[d] |= 1 << 30.iota.countUntil !(k => !!((c /= d) % d));
		if (c > 1) x[c] = 1;
	}
	writeln (f.byValue.map!g.fold!q{a ^ b} (0) - (x.length & 1) ? "Mojtaba" : "Arpa");
}

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

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

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

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

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

      int[int] fs;
      foreach (i; 0 .. N) {
        int a = A[i];
        for (int p = 2; p^^2 <= a; ++p) {
          if (a % p == 0) {
            int e;
            do {
              ++e;
              a /= p;
            } while (a % p == 0);
            fs[p] |= 1 << e;
          }
        }
        if (a > 1) {
          fs[a] |= 1 << 1;
        }
      }
      debug {
        writeln("fs = ", fs);
      }

      int[int] cache;
      int calc(int f) {
        int ret;
        cache.update(f, {
          int app;
          if (f) {
            foreach (e; 1 .. bsf(f) + 1) {
              const ff = ((f & ((1 << e) - 1)) | (f >> e)) & ~1;
              app |= 1 << calc(ff);
            }
          }
          ret = bsf(~app);
          debug {
            writefln("calc %b = %s", f, ret);
          }
          return ret;
        }, (ref int r) {
          return ret = r;
        });
        return ret;
      }

      int ans;
      foreach (p, f; fs) {
        ans ^= calc(f);
      }
      writeln(ans ? "Mojtaba" : "Arpa");
    }
  } catch (EOFException e) {
  }
}