Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 104) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 ≤ aij ≤ 104).

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

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.stdio, std.bitmanip;

void main() {
    auto s = readln.split.map!(to!int).array;
    auto N = s[0];
    auto M = s[1];
    auto D = s[2];
    auto A = new int[](N*M);
    foreach (i; 0..N) {
        s = readln.split.map!(to!int).array;
        foreach (j; 0..M)
            A[i*M+j] = s[j];
    }

    N = N*M;
    foreach (i; 1..N) {
        if ((A[i] - A[0]) % D != 0) {
            writeln(-1);
            return;
        }
    }

    auto m = A[0] % D;
    foreach (i; 0..N)
        A[i] = (A[i] - m) / D;

    int f(int x) {
        int ret;
        foreach (a; A)
            ret += abs(a-x);
        return ret;
    }

    int hi = 10^^4;
    int lo = 0;
    while (hi - lo > 2) {
        auto mid1 = (2*hi+lo)/3;
        auto mid2 = (hi+2*lo)/3;
        if (f(mid1) >= f(mid2))
            hi = mid1;
        else
            lo = mid2;
    }

    writeln([f(lo), f(lo+1), f(lo+2), f(lo+3)].reduce!(min));
}


Bizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a single integer — the minimum number of strokes needed to paint the whole fence.

NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke.

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

void main() {
    int N; scanf("%d\n", &N);
    int[] A = readln.chomp.split(" ").map!(to!int).array;

    int dfs(int s, int t, int d) {
        //writeln([s, t, d]);
        if (s == t) return 0;
        if (s + 1 == t) {
            return (A[s] > d ? 1 : 0);
        }
        int[] min_x;
        int min_v = int.max;
        for (int i = s; i < t; i++) {
            if (min_v > A[i]) {
                min_v = A[i];
                min_x = [i];
            } else if (min_v == A[i]) {
                min_x ~= i;
            }
        }

        int r = min_v - d;
        int Ret = r;

        Ret += dfs(s, min_x[0], min_v);
        for (int i = 0; i < cast(int)(min_x.length) - 1; i++) {
            if (min_x[i] == min_x[i + 1]) continue;
            Ret += dfs(min_x[i] + 1, min_x[i + 1], min_v);
        }
        Ret += dfs(min_x[$ - 1] + 1, t, min_v);

        //writeln([s, t, d], min_x, [Ret]);
        return min(Ret, t - s);
    }

    writeln(dfs(0, N, 0));
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;

size_t n;
long[5000] staticA;

long solve(long[] arr)
{
  debug writeln("solving ", arr);
  auto res = cast(long) arr.length;
  auto mn = arr.fold!min;
  arr[] -= mn;
  debug writeln("after cropping: ", arr);
  long cmps = mn;
  int nocmps = 0;
  int i = 0;
  while(i < arr.length)
    {
      while(i < arr.length && arr[i] == 0) i++;
      if (i == arr.length)  { debug writeln("returns ", min(arr.length, cmps)); return min(arr.length, cmps); }
      debug assert(arr[i] > 0);
      int starti = i;
      while(i < arr.length && arr[i] > 0) i++;
      if (i > starti)
	cmps += solve(arr[starti .. i]);
      if (cmps >= res) { debug writeln("returns ", res); return res; }
    }
  debug assert(cmps < res);
  debug writeln("returns ", cmps);
  return cmps;
}

void main(string[] args)
{
  n = next!size_t;
  auto a = staticA[0 .. n];
  foreach(ref ai; a) ai = next!long;
  solve(a).writeln;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}


You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).

The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively. Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).

If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.

NoteIn the first example you can remove edge , and the graph becomes acyclic.In the second example you have to remove at least two edges (for example,  and ) in order to make the graph acyclic.

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.stdio, std.string, std.traits, std.typecons,
	std.uni;

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;
/// struct vector as c++ vector
struct Vec(T)
{
	private Array!T buf;
	alias buf this;
	this(this)
	{
		buf = buf.dup;
	}
	/// construct from length
	this(U)(U length)
			if (is(U == int) || is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint))
	{
		buf.length = length;
	}
	/// construct from length and default value
	this(U, X)(U length, X val)
			if (isImplicitlyConvertible!(X, T) || (is(U == int)
				|| is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint)))
	{
		buf.length = length;
		foreach (ref x; buf[])
		{
			x = val;
		}
	}
	/// construct from other array
	this(U)(U[] values...) if (isImplicitlyConvertible!(U, T))
	{
		buf = Array!(T)(values);
	}
	/// construct from other range
	this(Range)(Range r)
			if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range,
				T) && !is(Range == T[]))
	{
		buf = Array!(T)(r);
	}
	/// integer length
	int size() @property const
	{
		return cast(int) buf.length;
	}
}
///modulo
const int 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 biggcd(BigInt a, BigInt b)
		{
			BigInt res = 1;
			while (b)
			{
				if ((a & 1) && (b & 1))
				{
					a -= b;
					a >>= 1;
				}
				else if (a & 1)
				{
					b >>= 1;
				}
				else if (b & 1)
				{
					a >>= 1;
				}
				else
				{
					res <<= 1;
					a >>= 1;
					b >>= 1;
				}
				if (a < b)
					swap(a, b);
			}
			return res * a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///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))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///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))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///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 assumeSorted(a).contains(g);
		}
	}
	///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;
	}

	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///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()
{
	int n, m;
	read(n, m);
	auto g = new int[][n + 1];
	foreach (ii; 0 .. m)
	{
		int x, y;
		read(x, y);
		g[x] ~= y;
	}
	int[] cycle;
	auto u = new int[n + 1];
	auto par = new int[n + 1];
	bool dfs(int v, int p)
	{
		if (u[v] == 2)
			return false;
		if (u[v] == 1)
		{
			int x = p;
			while (x != v)
			{
				cycle ~= x;
				x = par[x];
			}
			reverse(cycle);
			cycle ~= v;
			return true;
		}
		u[v] = 1;
		par[v] = p;
		foreach (x; g[v])
		{
			if (dfs(x, v))
				return true;
		}
		u[v] = 2;
		return false;
	}

	foreach (i; 1 .. n + 1)
	{
		if (!u[i])
			dfs(i, -1);
		if (!cycle.empty)
			break;
	}
	if (cycle.empty)
	{
		writeln("YES");
		return;
	}
	cycle ~= cycle[0];
	pii ban;

	bool dfs0(int v)
	{
		if (u[v] == 2)
			return false;
		if (u[v] == 1)
			return true;
		u[v] = 1;
		foreach (x; g[v])
		{
			if (ban == make_pair(v, x))
				continue;
			if (dfs0(x))
				return true;
		}
		u[v] = 2;
		return false;
	}

	foreach (i; 1 .. cycle.length)
	{
		ban = make_pair(cycle[i - 1], cycle[i]);
		u[] = 0;
		bool fl = true;
		foreach (v; 1 .. n + 1)
		{
			if (!u[v])
			{
				fl = fl && !dfs0(v);
			}
		}
		if (fl)
		{
			writeln("YES");
			return;
		}
	}
	writeln("NO");
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.stdio, std.string, std.traits, std.typecons,
	std.uni;

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;
/// struct vector as c++ vector
struct Vec(T)
{
	private Array!T buf;
	alias buf this;
	this(this)
	{
		buf = buf.dup;
	}
	/// construct from length
	this(U)(U length)
			if (is(U == int) || is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint))
	{
		buf.length = length;
	}
	/// construct from length and default value
	this(U, X)(U length, X val)
			if (isImplicitlyConvertible!(X, T) || (is(U == int)
				|| is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint)))
	{
		buf.length = length;
		foreach (ref x; buf[])
		{
			x = val;
		}
	}
	/// construct from other array
	this(U)(U[] values...) if (isImplicitlyConvertible!(U, T))
	{
		buf = Array!(T)(values);
	}
	/// construct from other range
	this(Range)(Range r)
			if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range,
				T) && !is(Range == T[]))
	{
		buf = Array!(T)(r);
	}
	/// integer length
	int size() @property const
	{
		return cast(int) buf.length;
	}
}
///modulo
const int 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 biggcd(BigInt a, BigInt b)
		{
			BigInt res = 1;
			while (b)
			{
				if ((a & 1) && (b & 1))
				{
					a -= b;
					a >>= 1;
				}
				else if (a & 1)
				{
					b >>= 1;
				}
				else if (b & 1)
				{
					a >>= 1;
				}
				else
				{
					res <<= 1;
					a >>= 1;
					b >>= 1;
				}
				if (a < b)
					swap(a, b);
			}
			return res * a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///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))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///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))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///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 assumeSorted(a).contains(g);
		}
	}
	///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;
	}

	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///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()
{
	int n, m;
	read(n, m);
	auto g = new int[][n + 1];
	foreach (ii; 0 .. m)
	{
		int x, y;
		read(x, y);
		g[x] ~= y;
	}
	int[] cycle;
	auto u = new int[n + 1];
	auto par = new int[n + 1];
	bool dfs(int v, int p)
	{
		if (u[v] == 2)
			return false;
		if (u[v] == 1)
		{
			int x = p;
			while (x != v)
			{
				cycle ~= x;
				x = par[x];
			}
			cycle ~= v;
			return true;
		}
		u[v] = 1;
		par[v] = p;
		foreach (x; g[v])
		{
			if (dfs(x, v))
				return true;
		}
		u[v] = 2;
		return false;
	}

	foreach (i; 1 .. n + 1)
	{
		if (!u[i])
			dfs(i, -1);
		if (!cycle.empty)
			break;
	}
	if (cycle.empty)
	{
		writeln("YES");
		return;
	}
	cycle ~= cycle[0];
	pii ban;

	bool dfs0(int v)
	{
		if (u[v] == 2)
			return false;
		if (u[v] == 1)
			return true;
		u[v] = 1;
		foreach (x; g[v])
		{
			if (ban == make_pair(v, x))
				continue;
			if (dfs0(x))
				return true;
		}
		u[v] = 2;
		return false;
	}

	foreach (i; 1 .. cycle.length)
	{
		ban = make_pair(cycle[i - 1], cycle[i]);
		u[] = 0;
		bool fl = true;
		foreach (v; 1 .. n + 1)
		{
			if (!u[v])
			{
				fl = fl && !dfs0(v);
			}
		}
		if (fl)
		{
			writeln("YES");
			return;
		}
	}
	writeln("NO");
}


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

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

void main() {
    int n; readf("%d\n", &n);
    auto as = stdin.readln.split.map!(to!int);
    int m; readf("%d\n", &m);
    auto bs = stdin.readln.split.map!(to!int);
    int max = 0, c = 0;
    foreach (a; as) {
        foreach (b; bs) {
            if (b % a == 0) {
                if (max == b / a) {
                    c++;
                } else if (max < b / a) {
                    max = b / a;
                    c = 1;
                }
            }
        }
    }
    writeln(c);
}

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

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

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                double[] arr = new double[n];
                foreach (ref i; arr) i = cin.readDouble;
                int m = cin.readInt;
                double[] brr = new double[m];
                foreach (ref i; brr) i = cin.readDouble;
                double maxRatio = -99999.0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (brr[i] % arr[j] == 0)
                                        maxRatio = max(maxRatio, brr[i] / arr[j]);
                        }
                }
                int count = 0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (abs(brr[i] / arr[j] - maxRatio) < 0.00001) count++;
                        }
                }
                writeln(count);
        }
}

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

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

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                double[] arr = new double[n];
                foreach (ref i; arr) i = cin.readDouble;
                int m = cin.readInt;
                double[] brr = new double[m];
                foreach (ref i; brr) i = cin.readDouble;
                double maxRatio = -99999.0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (brr[i] % arr[j] == 0)
                                        maxRatio = max(maxRatio, brr[i] / arr[j]);
                        }
                }
                int count = 0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (brr[i] % arr[j] == 0 && brr[i] / arr[j] == maxRatio) count++;
                        }
                }
                writeln(count);
        }
}


Polycarp has to solve exactly $$$n$$$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $$$k$$$ days. It means that Polycarp has exactly $$$k$$$ days for training!Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $$$k$$$ days. He also doesn't want to overwork, so if he solves $$$x$$$ problems during some day, he should solve no more than $$$2x$$$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $$$x$$$ problems during some day, he should solve at least $$$x+1$$$ problem during the next day.More formally: let $$$[a_1, a_2, \dots, a_k]$$$ be the array of numbers of problems solved by Polycarp. The $$$i$$$-th element of this array is the number of problems Polycarp solves during the $$$i$$$-th day of his training. Then the following conditions must be satisfied:   sum of all $$$a_i$$$ for $$$i$$$ from $$$1$$$ to $$$k$$$ should be $$$n$$$;  $$$a_i$$$ should be greater than zero for each $$$i$$$ from $$$1$$$ to $$$k$$$;  the condition $$$a_i < a_{i + 1} \le 2 a_i$$$ should be satisfied for each $$$i$$$ from $$$1$$$ to $$$k-1$$$. Your problem is to find any array $$$a$$$ of length $$$k$$$ satisfying the conditions above or say that it is impossible to do it.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9, 1 \le k \le 10^5$$$) — the number of problems Polycarp wants to solve and the number of days Polycarp wants to train.

If it is impossible to find any array $$$a$$$ of length $$$k$$$ satisfying Polycarp's rules of training, print "NO" in the first line. Otherwise print "YES" in the first line, then print $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ in the second line, where $$$a_i$$$ should be the number of problems Polycarp should solve during the $$$i$$$-th day. If there are multiple answers, you can print any.

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

void main ()
{
	long n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto add = k * 1L * (k + 1) / 2;
		n -= add;
		if (n < 0)
		{
			writeln ("NO");
			continue;
		}
		auto a = new long [k];
		auto quot = n / k;
		auto rem = n % k;
		foreach (i; 0..k)
		{
			a[i] = quot + (i < rem);
		}
		reverse (a);

		foreach (i; 0..k)
		{
			a[i] += i + 1;
		}
		if (k > 1 && a[0] == 1 && a[1] == 3)
		{
			a[1] -= 1;
			a[k - 1] += 1;
			if (k >= 2 && a[k - 2] * 2 < a[k - 1])
			{
				writeln ("NO");
				continue;
			}
		}
		writeln ("YES");
		writefln ("%(%s %)", a);
	}
}


Doremy is asked to test $$$n$$$ contests. Contest $$$i$$$ can only be tested on day $$$i$$$. The difficulty of contest $$$i$$$ is $$$a_i$$$. Initially, Doremy's IQ is $$$q$$$. On day $$$i$$$ Doremy will choose whether to test contest $$$i$$$ or not. She can only test a contest if her current IQ is strictly greater than $$$0$$$.If Doremy chooses to test contest $$$i$$$ on day $$$i$$$, the following happens:   if $$$a_i>q$$$, Doremy will feel she is not wise enough, so $$$q$$$ decreases by $$$1$$$;  otherwise, nothing changes.  If she chooses not to test a contest, nothing changes.Doremy wants to test as many contests as possible. Please give Doremy a solution.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 10^9$$$) — the number of contests and Doremy's IQ in the beginning. The second line contains $$$n$$$ integers $$$a_1,a_2,\cdots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the difficulty of each contest. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, you need to output a binary string $$$s$$$, where $$$s_i=1$$$ if Doremy should choose to test contest $$$i$$$, and $$$s_i=0$$$ otherwise. The number of ones in the string should be maximum possible, and she should never test a contest when her IQ is zero or less. If there are multiple solutions, you may output any.

NoteIn the first test case, Doremy tests the only contest. Her IQ doesn't decrease.In the second test case, Doremy tests both contests. Her IQ decreases by $$$1$$$ after testing contest $$$2$$$.In the third test case, Doremy tests contest $$$1$$$ and $$$2$$$. Her IQ decreases to $$$0$$$ after testing contest $$$2$$$, so she can't test contest $$$3$$$.

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

void solve() {
    int N, Q; readf("%d %d\n", &N, &Q);
    auto A = readln.chomp.split(" ").map!(to!int).array;

    // M[k]: minimum IQ required to test all problems of [k, n)
    auto M = new int[N];
    M[N-1] = 1;
    for (int i = N-2; i >= 0; i--) {
        int q = M[i+1];
        if (q >= A[i]) {
            M[i] = q;
        } else {
            M[i] = q + 1;
        }
    }

    char[] buf = new char[N]; buf[] = '0';
    int ans = 0;
    for (int k = 0; k < N; k++) {
        if (Q >= M[k]) {
            ans += N - k;
            buf[k..$] = '1';
            break;
        } else {
            if (Q >= A[k]) {
                ans++;
                buf[k] = '1';
            }
        }
    }
    writeln(buf);
}

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

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

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

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

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

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

        auto ans = new char[N];
        ans[] = '0';

        int x = 0;
        foreach_reverse (i; 0 .. N) {
          if (x >= A[i]) {
            ans[i] = '1';
          } else {
            if (x < Q) {
              ans[i] = '1';
              ++x;
            }
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

// cheese-cracker [2022-07-16]

void solve(){
    int n = scan!int;
    long q = scan;
    auto arr = scanArray;
    long k = 0;
    dchar[] res;
    for(int i = n-1; i >= 0; --i){
        if(k >= arr[i]){
            res ~= '1';
        }else{
            if(k < q){
                res ~= '1';
                ++k;
            }else{
                res ~= '0';
            }
        }
    }
    res.reverse;
    writeln(res);
}

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

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


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$. A bi-table is a table that has exactly two rows of equal length, each being a binary string.Let $$$\operatorname{MEX}$$$ of a bi-table be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the bi-table. For example, $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 0011\\ 1010 \end{bmatrix}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the bi-table at least once. $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 111\\ 111 \end{bmatrix}$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the bi-table, and $$$0 < 2$$$.You are given a bi-table with $$$n$$$ columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table.What is the maximal sum of $$$\operatorname{MEX}$$$ of all resulting bi-tables can be?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of the description of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of columns in the bi-table. Each of the next two lines contains a binary string of length $$$n$$$ — the rows of the bi-table. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the maximal sum of $$$\operatorname{MEX}$$$ of all bi-tables that it is possible to get by cutting the given bi-table optimally.

NoteIn the first test case you can cut the bi-table as follows:  $$$\begin{bmatrix} 0\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 10\\ 10 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 1\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$0$$$. $$$\begin{bmatrix} 0\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 0\\ 0 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$1$$$. $$$\begin{bmatrix} 0\\ 0 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$1$$$.The sum of $$$\operatorname{MEX}$$$ is $$$8$$$.

immutable multi = true;

void solve(int)
{
	int n = readInt!int;
	string[2] tb;
	tb[0] = readString;
	tb[1] = readString;
	auto mx = new int[](n);
	foreach(i, ref mxi; mx)
	{
		if (tb[0][i] != tb[1][i])
		{
			mx[i] = 2;
		}
		else if (tb[0][i] == '0')
		{
			mx[i] = 1;
		}
		else
		{
			mx[i] = 0;
		}
	}
	auto ans = new int[](n);
	int calc(int i)
	{
		if (i == 0) return mx[i];
		if (mx[i] == 2) return 2 + ans[i-1];
		int opt1 = mx[i] + ans[i-1];
		int opt2 = 0;
		if (mx[i] != mx[i-1])
		{
			int prev = (i-2 >= 0)? ans[i-2] : 0;
			opt2 = prev + 2;
		}
		return max(opt1, opt2);
	}
	foreach(i; 0 .. n) ans[i] = calc(i);
	ans[n-1].writeln;
}

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

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

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

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

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

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

int mex(int[] arr)
{
	if (arr.maxElement == 2)
		return 2;
	else if (arr.minElement == arr.maxElement)
		return 1 - arr.minElement;
	else
		return 2;
}

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(j; 0..t){
	int str_l;
	scanf("%d", &str_l);
	getchar();
	auto str1 = readln.strip();
	auto str2 = readln.strip();
	int[] result;
	for (int i = 0; i < str_l; i++)
	{
		if (str1[i] == str2[i])
		{
			result ~= cast(int)(str1[i] - '0');
		}
		else
			result ~= 2;
	}
	int[] mex_res;
	debug{writeln(result);}
	for (int i = 0; i < str_l; i++)
	{
		mex_res ~= mex(result[i..i+1]);
	}
	debug{writeln(mex_res);}
	for (int i = 0; i < str_l; i++)
	{
		if (mex_res[i] == 0)
		{
			if (i == 0)
			{
				if (mex_res[i+1] == 1)
				{
					if (mex(result[i..i+2]) == 2)
						mex_res[i+1]++;
				}
			}
			else if (i == str_l - 1)
			{
				if (mex_res[i-1] == 1)
				{
					if (mex(result[i-1..i+1]) == 2)
						mex_res[i-1]++;
				}
			}
			else
			{
				if (mex_res[i-1] == 1)
				{
					if (mex(result[i-1..i+1]) == 2)
						mex_res[i-1]++;
				}
				else if (mex_res[i+1] == 1)
				{
					if (mex(result[i..i+2]) == 2)
						mex_res[i+1]++;
				}
			}
		}
	}
	writeln(mex_res.sum);
    }
}

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split("").map!(x => (1 << x.to!int)).array;
    auto b = readln.strip.split("").map!(x => (1 << x.to!int)).array;
    foreach (i ; 0 .. n)
      a[i] |= b[i];
    long[] mexval = [0L, 1L, 0L, 2L];
    long[][] ans = new long[][](n + 1, 2);
    int[][] bits = new int[][](n + 1, 2);
    ans[0][0] = mexval[a[0]];
    ans[0][1] = 0;
    bits[0][0] = 0;
    bits[0][1] = a[0];
    foreach (i ; 1 .. n) {
      // break sequence
      long ans1 = ans[i - 1][0] + mexval[bits[i - 1][0] | a[i]];
      long ans2 = ans[i - 1][1] + mexval[bits[i - 1][1] | a[i]];
      ans[i][0] = max(ans1, ans2);
      bits[i][0] = 0;
      // continue sequence
      if (ans[i - 1][0] + mexval[a[i]] >= ans[i - 1][1] + mexval[a[i] | bits[i - 1][1]]) {
        ans[i][1] = ans[i - 1][0];
        bits[i][1] = a[i];
      } else {
        ans[i][1] = ans[i - 1][1];
        bits[i][1] = bits[i - 1][1] | a[i];
      }
    }
    writeln(max(ans[n - 1][0] + mexval[bits[n - 1][0]], ans[n - 1][1] + mexval[bits[n - 1][1]]));
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s1 = RD!string;
		auto s2 = RD!string;

		long last = -1;
		foreach (i; 0..n)
		{
			if (last == -1)
			{
				if (s1[i] != s2[i])
				{
					ans[ti] += 2;
					last = -1;
				}
				else if (s1[i] == '0')
				{
					ans[ti] += 1;
					last = 0;
				}
				else
					last = 1;
			}
			else if (last == 0)
			{
				if (s1[i] != s2[i])
				{
					ans[ti] += 2;
					last = -1;
				}
				else if (s1[i] == '0')
				{
					ans[ti] += 1;
					last = 0;
				}
				else
				{
					ans[ti] += 1;
					last = -1;
				}
			}
			else
			{
				if (s1[i] != s2[i])
				{
					ans[ti] += 2;
					last = -1;
				}
				else if (s1[i] == '0')
				{
					ans[ti] += 2;
					last = -1;
				}
				else
					last = 1;
			}
			debug writeln("i:", i, " ", ans[ti]);
		}
	}

	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 a = readln.strip.map !(q{a - '0'}).array;
		auto b = readln.strip.map !(q{a - '0'}).array;

		int mex (int lo, int hi)
		{
			bool [3] c;
			foreach (i; lo..hi)
			{
				c[a[i]] = true;
				c[b[i]] = true;
			}
			int res = 0;
			while (c[res])
			{
				res += 1;
			}
			return res;
		}

		auto f = new int [n + 1];
		f[0] = 0;
		f[1] = mex (0, 1);
		foreach (i; 2..n + 1)
		{
			foreach (j; 1..3)
			{
				f[i] = max (f[i], mex (i - j, i) + f[i - j]);
			}
		}
		writeln (f[n]);
	}
}


DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Print a single integer — the largest possible value of the resulting string DZY could get.

NoteIn the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

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

void main() {
    string S = readln.chomp;
    int K; scanf("%d\n", &K);
    int[char] W;
    foreach (char c; 'a' .. 'z' + 1) {
        int w; scanf("%d", &w);
        W[c] = w;
    }

    long Ans = 0;
    foreach (i, c; S) {
        Ans += W[c] * (i + 1);
    }

    int Max = 0;
    foreach (char c; 'a' .. 'z' + 1) {
        Max = max(Max, W[c]);
    }

    foreach (i; 0 .. K) {
        Ans += Max * (S.length + i + 1);
    }

    writeln(Ans);
}

//http://codeforces.com/contest/447/problem/B
import std.stdio;

int C_OFFSET = 97;

void main(){
  string s;
  int n;
  int max_id = 0;
  int[26] val;
  readf("%s\n" ,&s);
  readf("%s\n" ,&n);
  for(int i = 0; i < 26; i++){
    int v;
    readf("%s " ,&v);
    val[i] = v;
    if (val[max_id] < v){
      max_id = i;
    }
  }
  writeln(run(s,n,max_id,val));
}

long run(string s, int n, int max_id, int[] val){
  int[] a;
  foreach(char c;s){
    int cval = c - C_OFFSET;
    if(cval >= 0 && cval < 26){
      a ~= c - C_OFFSET;
    }
  }

  for(int i = 0; i < n; i++){
    a ~= max_id;
  }

  return s_prod(a,val);
}

long s_prod(int[] a, int[] val){
  long sum = 0;
  foreach(i,x; a){
    sum += (i+1)*val[x];
  }
  return sum;
}

// TEST CASE AREA
void test_case(){
  long[][] rs;
  rs ~= [run("abc",3,1,[1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]),41];

  array_assert(rs);
}

void array_assert(long[][] rs){
  int i = 1;
  bool failed = false;

  writefln("TEST");

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

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

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

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

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

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

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

immutable L = 26;

string S;
long K;
long[] W;

void main(string[] args) {
	try {
	for (; ; ) {
		S = readToken;
		K = readLong;
		W = new long[L];
		foreach (i; 0 .. L) {
			W[i] = readLong;
		}

		long ans;
		foreach (i, c; S) {
			ans += W[c - 'a'] * (i + 1);
		}
		const wMax = W.reduce!max;
		foreach (k; 0 .. K) {
			ans += wMax * (S.length + 1 + k);
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}


You are given an array $$$a$$$ of $$$n$$$ integers, and another integer $$$k$$$ such that $$$2k \le n$$$.You have to perform exactly $$$k$$$ operations with this array. In one operation, you have to choose two elements of the array (let them be $$$a_i$$$ and $$$a_j$$$; they can be equal or different, but their positions in the array must not be the same), remove them from the array, and add $$$\lfloor \frac{a_i}{a_j} \rfloor$$$ to your score, where $$$\lfloor \frac{x}{y} \rfloor$$$ is the maximum integer not exceeding $$$\frac{x}{y}$$$.Initially, your score is $$$0$$$. After you perform exactly $$$k$$$ operations, you add all the remaining elements of the array to the score.Calculate the minimum possible score you can get.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$0 \le k \le \lfloor \frac{n}{2} \rfloor$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$).

Print one integer — the minimum possible score you can get.

NoteLet's consider the example test.In the first test case, one way to obtain a score of $$$2$$$ is the following one:  choose $$$a_7 = 1$$$ and $$$a_4 = 2$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{2} \rfloor = 0$$$, the array becomes $$$[1, 1, 1, 1, 3]$$$;  choose $$$a_1 = 1$$$ and $$$a_5 = 3$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{3} \rfloor = 0$$$, the array becomes $$$[1, 1, 1]$$$;  choose $$$a_1 = 1$$$ and $$$a_2 = 1$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{1} \rfloor = 1$$$, the array becomes $$$[1]$$$;  add the remaining element $$$1$$$ to the score, so the resulting score is $$$2$$$. In the second test case, no matter which operations you choose, the resulting score is $$$16$$$.In the third test case, one way to obtain a score of $$$0$$$ is the following one:  choose $$$a_1 = 1$$$ and $$$a_2 = 3$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{3} \rfloor = 0$$$, the array becomes $$$[3, 7]$$$;  choose $$$a_1 = 3$$$ and $$$a_2 = 7$$$ for the operation; the score becomes $$$0 + \lfloor \frac{3}{7} \rfloor = 0$$$, the array becomes empty;  the array is empty, so the score doesn't change anymore. In the fourth test case, no operations can be performed, so the score is the sum of the elements of the array: $$$4 + 2 = 6$$$.

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto k = readInt!int;
  auto a = ma(n, readInt!int);
  sort(a);
  auto upper = a[$ - 2 * k .. $];
  auto lower = a[0 .. $ - 2 * k];
  int[int] cnt;
  int mostAps = 0;
  foreach(ai; upper)
    {
      cnt[ai]++;
      if (cnt[ai] > mostAps)
	{
	  mostAps = cnt[ai];
	}
    }
  debug writeln("upper ", upper);
  debug writeln("most aps ", mostAps);
  auto other = cast(int) upper.length - mostAps;
  int rem = max(mostAps - other, 0);
  (lower.sum + rem/2).writeln;
}

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

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

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

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

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, k;
    readf!" %d %d "(n, k);
    auto a = readln.splitter.map!(to!int).array.sort.array;
    long ans;
    foreach (i ; 0 .. n - 2 * k)
      ans += a[i];
    auto b = a[$ - 2 * k .. $];
    if (b.length >= 2) {
      if (b[k] == b[k - 1]) {
        long same = b.count(b[k]);
        long lohi = b.length - same;
        if (same > lohi) {
          ans += (same - lohi) / 2;
        }
      }
    }
    writeln(ans);
  }
}

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

void solve(){
    long n = scan;
    long k = scan;
    auto arr = scanArray;
    arr.sort;
    long summ = 0;
    long[] take;
    for(int i = 0; i < k; ++i){
        take ~= arr.back;
        arr.popBack;
        take ~= arr.back;
        arr.popBack;
    }
    take.sort;
    long maxc = 0;
    long c = 1;
    for(int i = 1; i < 2*k; ++i){
        if(take[i-1] == take[i]){
            ++c;
        }else{
            maxc = max(c, maxc);
            c = 1;
        }
    }
    maxc = max(maxc, c);
    long left = max(2*k - maxc, 0);
    long same = max(maxc - left, 0);
    show(left, same);
    summ = same/2 + arr.sum;
    writeln(summ);
}

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

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


You are given matrix a of size n × m, its elements are integers. We will assume that the rows of the matrix are numbered from top to bottom from 1 to n, the columns are numbered from left to right from 1 to m. We will denote the element on the intersecting of the i-th row and the j-th column as aij.We'll call submatrix i1, j1, i2, j2 (1 ≤ i1 ≤ i2 ≤ n; 1 ≤ j1 ≤ j2 ≤ m) such elements aij of the given matrix that i1 ≤ i ≤ i2 AND j1 ≤ j ≤ j2. We'll call the area of the submatrix number (i2 - i1 + 1)·(j2 - j1 + 1). We'll call a submatrix inhomogeneous, if all its elements are distinct.Find the largest (in area) inhomogenous submatrix of the given matrix.

The first line contains two integers n, m (1 ≤ n, m ≤ 400) — the number of rows and columns of the matrix, correspondingly. Each of the next n lines contains m integers aij (1 ≤ aij ≤ 160000) — the elements of the matrix.

Print a single integer — the area of the optimal inhomogenous submatrix.

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				y[l] = max(y[l], minp[l][d[i][r]]);
				u[l][r] = max(u[l][r], minp[r][d[i][l]]);
				if (r > 0) {
					u[l][r] = max(u[l][r], u[l][r-1]);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
			minp[r][d[i][r]] = i+1;
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160_010;
void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	short[MA][] minp = new short[MA][](MN);
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				y[l] = max(y[l], minp[l][d[i][r]]);
				u[l][r] = max(u[l][r], minp[r][d[i][l]]);
				if (r > 0) {
					u[l][r] = max(u[l][r], u[l][r-1]);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
			minp[r][d[i][r]] = cast(short)(i+1);
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				int p = minp[l][d[i][r]];
				if (p <= i && l < r) {
					y[l] = max(y[l], p+1);
				}
				p = minp[r][d[i][l]];
				if (p < i || (l < r && p == i)) {
					u[l][r] = max(u[l][r], p+1);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(minp[0][2], ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			int p = minp[r][d[i][r]];
			if (p < i) {
				y[r] = u[r][r] = p+1;
			}
			ans = max(ans, (i-u[r][r]+1));
			foreach_reverse (l; 0..r) {
				int pl = minp[l][d[i][r]];
				if (pl <= i) {
					y[l] = max(y[l], pl+1);
				}
				int pr = minp[r][d[i][l]];
				if (pr <= i) {
					u[l][r] = pr+1;
				}
				u[l][r] = max(u[l][r], u[l][r-1], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			int p = minp[r][d[i][r]];
			if (p < i) {
				y[r] = u[r][r] = p+1;
			}
			ans = max(ans, (i-u[r][r]+1));
			foreach_reverse (l; 0..r) {
				int pl = minp[l][d[i][r]];
				if (pl <= i) {
					y[l] = max(y[l], pl+1);
				}
				int pr = minp[r][d[i][l]];
				if (pr <= i) {
					u[l][r] = pr+1;
				}
				u[l][r] = max(u[l][r], u[l][r-1], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
		foreach (r; 0..m) {
			foreach (l; 0..r+1) {
				writeln(i, l, r, u[l][r]);
			}
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				int p = minp[l][d[i][r]];
				if (p <= i && l < r) {
					y[l] = max(y[l], p+1);
				}
				p = minp[r][d[i][l]];
				if (p < i || (l < r && p == i)) {
					u[l][r] = max(u[l][r], p+1);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				int p = minp[l][d[i][r]];
				if (p <= i && l < r) {
					y[l] = max(y[l], p+1);
				}
				p = minp[r][d[i][l]];
				if (p < i || (l < r && p == i)) {
					u[l][r] = max(u[l][r], p+1);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}


A famous sculptor Cicasso goes to a world tour!Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland.Cicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help. There are n cities and m one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities — will be the largest. Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: . Four cities in the order of visiting marked as overlines: [1, 5, 2, 4].Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do.

In the first line there is a pair of integers n and m (4 ≤ n ≤ 3000, 3 ≤ m ≤ 5000) — a number of cities and one-way roads in Berland. Each of the next m lines contains a pair of integers ui, vi (1 ≤ ui, vi ≤ n) — a one-way road from the city ui to the city vi. Note that ui and vi are not required to be distinct. Moreover, it can be several one-way roads between the same pair of cities.

Print four integers — numbers of cities which Cicasso will visit according to optimal choice of the route. Numbers of cities should be printed in the order that Cicasso will visit them. If there are multiple solutions, print any of them.

NoteLet d(x, y) be the shortest distance between cities x and y. Then in the example d(2, 1) = 3, d(1, 8) = 7, d(8, 7) = 3. The total distance equals 13.

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

immutable int INF = int.max / 4;

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

		auto d = new int [] [] (n, n);
		foreach (ref e; d)
		{
			e[] = INF;
		}

		foreach (i; 0..n)
		{
			auto e = d[i];
			int [] q;
			q.reserve (n);

			void add (int v, int c)
			{
				if (e[v] < INF)
				{
					return;
				}
				q.assumeSafeAppend ();
				q ~= v;
				e[v] = c;
			}

			add (i, 0);
			while (!q.empty)
			{
				int v = q.front;
				q.popFront ();
				auto c = e[v];
				c++;
				foreach (u; a[v])
				{
					add (u, c);
				}
			}
		}
		debug {writefln ("%(%(%10s%)\n%)", d);}

		alias Pair = Tuple !(int, q{value}, int, q{num});
		auto x = new Pair [3] [n];
		auto y = new Pair [3] [n];
		foreach (u; 0..n)
		{
			x[u] = [Pair (-1, u), Pair (-1, u), Pair (-1, u)];
			y[u] = [Pair (-1, u), Pair (-1, u), Pair (-1, u)];
			foreach (v; 0..n)
			{
				if (u != v && d[v][u] < INF)
				{
					auto t = Pair (d[v][u], v);
					if (x[u][1] < t)
					{
						if (x[u][0] < t)
						{
							x[u][2] = x[u][1];
							x[u][1] = x[u][0];
							x[u][0] = t;
						}
						else
						{
							x[u][2] = x[u][1];
							x[u][1] = t;
						}
					}
					else
					{
						if (x[u][2] < t)
						{
							x[u][2] = t;
						}
						else
						{
						}
					}
				}
				if (u != v && d[u][v] < INF)
				{
					auto t = Pair (d[u][v], v);
					if (y[u][1] < t)
					{
						if (y[u][0] < t)
						{
							y[u][2] = y[u][1];
							y[u][1] = y[u][0];
							y[u][0] = t;
						}
						else
						{
							y[u][2] = y[u][1];
							y[u][1] = t;
						}
					}
					else
					{
						if (y[u][2] < t)
						{
							y[u][2] = t;
						}
						else
						{
						}
					}
				}
			}
		}

		int [] ans;
		int res = -1;
		foreach (u; 0..n)
		{
			foreach (v; 0..n)
			{
				if (u == v || d[u][v] >= INF)
				{
					continue;
				}
				foreach (p; x[u])
				{
					if (p.num == u || p.num == v)
					{
						continue;
					}
					foreach (q; y[v])
					{
						if (q.num == u || q.num == v ||
						    q.num == p.num)
						{
							continue;
						}
						int cur = d[u][v] +
						    p.value + q.value;
						if (res < cur)
						{
							res = cur;
							ans = [p.num, u, v,
							    q.num];
						}
					}
				}
			}
		}
		debug {writeln (res);}
		writefln ("%(%s %)", ans.map !(q{a + 1}));
	}
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let's call a pair of indices $$$i$$$, $$$j$$$ good if $$$1 \le i < j \le n$$$ and $$$\gcd(a_i, 2a_j) > 1$$$ (where $$$\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$).Find the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$) — the number of elements in the array. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, output a single integer — the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

NoteIn the first example, the array elements can be rearranged as follows: $$$[6, 3, 5, 3]$$$.In the third example, the array elements can be rearranged as follows: $$$[4, 4, 2, 1, 1]$$$.

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

long gcd(long a, long b) {
    return b == 0L ? a : gcd(b, a%b);
}

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

while(t--) {
    int n = readln.chomp.to!int;
    long[] a = readln.split.map!(to!long).array;

    long[] b;
    foreach(item; a) {
        if(item % 2 == 0)
            b = b ~ item;
    }
    foreach(item; a) {
        if(item % 2 == 1)
            b = b ~ item;
    }

    int ans = 0;
    for(int i = 0; i < n; ++i)
        for(int j = i + 1; j < n; ++j)
            if(gcd(b[i],2 * b[j]) > 1)
                ans += 1;
    ans.writeln;
}
}

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    long result = 0;
    foreach (i ; 0 .. a.length) {
      foreach (j ; i + 1 .. a.length) {
        if (gcd(a[i], a[j]) > 1)
          result++;
        else if (a[i] % 2 == 0 || a[j] % 2 == 0)
          result++;
      }
    }
    writeln(result);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto lo = a.filter !(x => (x & 1) == 0).array;
		auto hi = a.filter !(x => (x & 1) == 1).array;
		auto b = lo ~ hi;
		int res = 0;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				if (gcd (b[i], b[j] * 2) > 1)
				{
					res += 1;
				}
			}
		}
		writeln (res);
	}
}

import std.stdio;
import std.ascii;
import std.numeric;
import std.algorithm;
import core.stdc.stdio;

int main()
{
    int t = readInt!int;
    foreach(ti; 0 .. t)
    {
        int n = readInt!int;
        int[] a = new int[](n);
        int[] even;
        int[] odd;
        foreach(ref ai; a)
        {
            ai = readInt!int;
            if (ai & 1) odd ~= ai;
            else even ~= ai;
        }
        long count = 0;
        foreach(i, oi; odd)
        {
            foreach(j; i + 1 .. odd.length)
            {
                if (gcd(oi, odd[j]) > 1)
                {
                    count++;
                }
            }
        }
        count += even.length * (even.length - 1) / 2;
        count += even.length * odd.length;
        count.writeln;
    }
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
    long rep;
    this(long num)
    {
        rep = num;
    }
    Z!m opBinary(string operator)(Z!m rhs)
    {
        static if (operator == "+")
        {
            long result = rhs.rep + this.rep;
            if (result >= m) result -= m;
            return Z!m(result);
        }
        else static if (operator == "-")
        {
            long result = this.rep - rhs.rep;
            if (result < 0) result += m;
            return Z!m(result);
        }
        else static if (operator == "*")
        {
            long result = this.rep * rhs.rep;
            if (result >= m) result %= m;
            return Z!m(result);
        } else static assert(text("Operator ", operator, " not supported"));
    }
    Z!m opBinary(string operator)(long exponent) if (operator == "^^")
    {
        assert(exponent >= 0);
        Z!m base = this;
        Z!m result = 1;
        while (exponent)
        {
            if (exponent & 1)
                result = result * base;
            base = base * base;
            exponent >>= 1;
        }
        return result;
    }
    invariant
    {
        assert(rep >= 0 && rep < m);
    }
}

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

long gcd(long a, long b) {
    return b == 0L ? a : gcd(b, a%b);
}

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

while(t--) {
    int n = readln.chomp.to!int;
    long[] a = readln.split.map!(to!long).array;

    long[] b;
    foreach(item; a) {
        if(item % 2 == 0)
            b = b ~ item;
    }
    foreach(item; a) {
        if(item % 2 == 1)
            b = b ~ item;
    }
    int ans = 0;
    for(int i = 0; i < n; ++i)
        for(int j = i + 1; j < n; ++j)
            if(gcd(i,j) > 1)
                ans += 1;
    ans.writeln;
}
}


After studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly T seconds. The problem is that the star is yet to be discovered by scientists.There are n astronomers numerated from 1 to n trying to detect the star. They try to detect the star by sending requests to record the sky for 1 second. The astronomers send requests in cycle: the i-th astronomer sends a request exactly ai second after the (i - 1)-th (i.e. if the previous request was sent at moment t, then the next request is sent at moment t + ai); the 1-st astronomer sends requests a1 seconds later than the n-th. The first astronomer sends his first request at moment 0.Mister B doesn't know the first moment the star is going to shine, but it's obvious that all moments at which the star will shine are determined by the time of its shine moment in the interval [0, T). Moreover, this interval can be split into T parts of 1 second length each of form [t, t + 1), where t = 0, 1, 2, ..., (T - 1).Mister B wants to know how lucky each astronomer can be in discovering the star first.For each astronomer compute how many segments of form [t, t + 1) (t = 0, 1, 2, ..., (T - 1)) there are in the interval [0, T) so that this astronomer is the first to discover the star if the first shine of the star happens in this time interval.

The first line contains two integers T and n (1 ≤ T ≤ 109, 2 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print n integers: for each astronomer print the number of time segments describer earlier.

NoteIn the first sample test the first astronomer will send requests at moments t1 = 0, 5, 10, ..., the second — at moments t2 = 3, 8, 13, .... That's why interval [0, 1) the first astronomer will discover first at moment t1 = 0, [1, 2) — the first astronomer at moment t1 = 5, [2, 3) — the first astronomer at moment t1 = 10, and [3, 4) — the second astronomer at moment t2 = 3.In the second sample test interval [0, 1) — the first astronomer will discover first, [1, 2) — the second astronomer, [2, 3) — the third astronomer, [3, 4) — the fourth astronomer, [4, 5) — the first astronomer.

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

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

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

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

Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}

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

      auto X = new long[N + 1];
      foreach (i; 0 .. N) {
        X[i + 1] = X[i] + A[(i + 1) % N];
      }
      const M = X[N];
      debug {
        writeln("X = ", X);
      }

      long z0, z1;
      const D = gojo(M, T, z0, z1);

      alias Entry = Tuple!(long, "val", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(X[i] % D, i);
      }
      es.sort;

      auto ans = new long[N];
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].val == es[k].val; ++k) {}
        debug {
          writeln(es[j .. k]);
        }
        const r = es[j].val;
        auto fs = new Entry[k - j];
        foreach (l; 0 .. k - j) {
          const i = es[j + l].i;
          /*
            X[i] == r + M a (mod T)
            X[i] + T b = r + M a
            (M / D) a - (T / D) b = (X[i] - r) / D
            (M / D) z0 + (T / D) z1 = 1
          */
          // long a = (z0 * ((X[i] - r) / D)) % (T / D);
          long a = cast(long)((z0 * BigInt((X[i] - r) / D)) % (T / D));
          if (a < 0) {
            a += T / D;
          }
          fs[l] = Entry(a, i);
        }
        fs.sort!"(a.val != b.val) ? (a.val < b.val) : (a.i > b.i)";
        debug {
          writeln("  fs = ", fs);
        }
        foreach (l; 0 .. k - j - 1) {
          ans[fs[l].i] = fs[l + 1].val - fs[l].val;
        }
        ans[fs[k - j - 1].i] = T / D + fs[0].val - fs[k - j - 1].val;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;

      debug {
        auto app = new bool[cast(int)(T)];
        auto brt = new long[N];
        foreach (h; 0 .. T) {
          foreach (i; 0 .. N) {
            const x = (X[i] + M * h) % T;
            if (!app[cast(int)(x)]) {
              app[cast(int)(x)] = true;
              ++brt[i];
            }
          }
        }
        writeln("brt = ", brt);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}

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

      auto X = new long[N + 1];
      foreach (i; 0 .. N) {
        X[i + 1] = X[i] + A[(i + 1) % N];
      }
      const M = X[N];
      debug {
        writeln("X = ", X);
      }

      long z0, z1;
      const D = gojo(M, T, z0, z1);

      alias Entry = Tuple!(long, "val", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(X[i] % D, i);
      }
      es.sort;

      auto ans = new long[N];
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].val == es[k].val; ++k) {}
        debug {
          writeln(es[j .. k]);
        }
        const r = es[j].val;
        auto fs = new Entry[k - j];
        foreach (l; 0 .. k - j) {
          const i = es[j + l].i;
          /*
            X[i] == r + M a (mod T)
            X[i] + T b = r + M a
            (M / D) a - (T / D) b = (X[i] - r) / D
            (M / D) z0 + (T / D) z1 = 1
          */
          long a = (z0 * (((X[i] - r) / D) % (T / D))) % (T / D);
          if (a < 0) {
            a += T / D;
          }
          fs[l] = Entry(a, i);
        }
        fs.sort!"(a.val != b.val) ? (a.val < b.val) : (a.i > b.i)";
        debug {
          writeln("  fs = ", fs);
        }
        foreach (l; 0 .. k - j - 1) {
          ans[fs[l].i] = fs[l + 1].val - fs[l].val;
        }
        ans[fs[k - j - 1].i] = T / D + fs[0].val - fs[k - j - 1].val;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;

      debug {
        auto app = new bool[cast(int)(T)];
        auto brt = new long[N];
        foreach (h; 0 .. T) {
          foreach (i; 0 .. N) {
            const x = (X[i] + M * h) % T;
            if (!app[cast(int)(x)]) {
              app[cast(int)(x)] = true;
              ++brt[i];
            }
          }
        }
        writeln("brt = ", brt);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}

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

      auto X = new long[N + 1];
      foreach (i; 0 .. N) {
        X[i + 1] = X[i] + A[(i + 1) % N];
      }
      const M = X[N];
      debug {
        writeln("X = ", X);
      }

      long z0, z1;
      const D = gojo(M, T, z0, z1);

      alias Entry = Tuple!(long, "val", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(X[i] % D, i);
      }
      es.sort;

      auto ans = new long[N];
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].val == es[k].val; ++k) {}
        debug {
          writeln(es[j .. k]);
        }
        const r = es[j].val;
        auto fs = new Entry[k - j];
        foreach (l; 0 .. k - j) {
          const i = es[j + l].i;
          /*
            X[i] == r + M a (mod T)
            X[i] + T b = r + M a
            (M / D) a - (T / D) b = (X[i] - r) / D
            (M / D) z0 + (T / D) z1 = 1
          */
          long a = (z0 * ((X[i] - r) / D)) % (T / D);
          if (a < 0) {
            a += T / D;
          }
          fs[l] = Entry(a, i);
        }
        fs.sort!"(a.val != b.val) ? (a.val < b.val) : (a.i > b.i)";
        debug {
          writeln("  fs = ", fs);
        }
        foreach (l; 0 .. k - j - 1) {
          ans[fs[l].i] = fs[l + 1].val - fs[l].val;
        }
        ans[fs[k - j - 1].i] = T / D + fs[0].val - fs[k - j - 1].val;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;

      debug {
        auto app = new bool[cast(int)(T)];
        auto brt = new long[N];
        foreach (h; 0 .. T) {
          foreach (i; 0 .. N) {
            const x = (X[i] + M * h) % T;
            if (!app[cast(int)(x)]) {
              app[cast(int)(x)] = true;
              ++brt[i];
            }
          }
        }
        writeln("brt = ", brt);
      }
    }
  } catch (EOFException e) {
  }
}