You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands "00010010", "1001001", "00010" and "0" are good but garlands "00101001", "1000001" and "01001100" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25~ 000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6; 1 \le k \le n$$$) — the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).

For each test case, print the answer — the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.

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

auto savings (R) (R r)
{
	int balance = 0;
	int res = 0;
	foreach (const ref cur; r)
	{
		balance += cur ? +1 : -1;
		balance = max (balance, 0);
		res = max (res, balance);
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip.map !(q{a == '1'}).array;
		int total = s.sum;
		int res = total;
		foreach (start; 0..k)
		{
			res = min (res, total -
			    savings (s.drop (start).stride (k)));
		}
		writeln (res);
	}
}

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;

void main(string[] args)
{
  auto t = next!int;
 tcl: foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto k = next!int;
      auto s = next!char(n);
      auto totalModuloCount = new int[](k);
      auto rightModuloCount = new int[](k);
      auto no1s = s.count!(c => c == '1');
      foreach(i, c; s) if (c == '1') totalModuloCount[cast(int)i % k]++;
      rightModuloCount[] = totalModuloCount[];
      auto bestEnding = new int[](n);
      auto bestEndingPerClass = new int[](k);
      debug writeln(totalModuloCount);
      bestEndingPerClass[] = 1_000_000_0;
      foreach(i; 0 .. n)
	{
	  auto moduloClass = cast(int) i % k;
	  if (s[i] == '1')
	    {
	      rightModuloCount[moduloClass]--;
	    }
	  if (i - k >= 0)
	    {
	      debug
		{
		  if (i == 3)
		    {
		      writeln("current cost: ", - int(s[i] == '1')  + int(s[i] != '1'));
		      writeln(bestEnding);
		      writeln("comparing ", totalModuloCount[moduloClass] - int(s[i] == '1') + int(s[i] != '1'),
			      " with ", bestEnding[i - k] - int(s[i] == '1') + int(s[i] != '1'));
		    }
		}
	      bestEnding[i] = min(totalModuloCount[moduloClass] - int(s[i] == '1') + int(s[i] != '1'),
				  bestEnding[i - k] - int(s[i] == '1') + int(s[i] != '1'));
	    }
	  else
	    {
	      bestEnding[i] = totalModuloCount[moduloClass] - int(s[i] == '1') + int(s[i] != '1');
	    }
	  bestEndingPerClass[moduloClass] = min(bestEndingPerClass[moduloClass],
						bestEnding[i]);
	}
      debug writeln(bestEnding);
      debug writeln(bestEndingPerClass);
      int bestTotal = cast(int)no1s;
      foreach(cl; 0 .. k)
	{
	  bestTotal = min(bestTotal, bestEndingPerClass[cl] + no1s - totalModuloCount[cl]);
	}
      bestTotal.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've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?

The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≤  ai,  bi  ≤  109).

Print the sought number of operations for each pair on a single line.

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

int solve(int a, int b) {
        if (a == 0 || b == 0) return 0;
        else return max(a, b) / min(a, b) + solve(max(a, b) % min(a, b), min(a, b));
}
void main() {
        IO cin;
        int t = 1;
        t = cin.readInt;
        while (t--) {
                int a = cin.readInt;
                int b = cin.readInt;
                int count = 0;
                writeln(solve(a, b));
        }
}

import std.stdio;

int steps (int a, int b)
{
	if (b == 0)
	{
		return 0;
	}
	return a / b + steps (b, a % b);
}

int main ()
{
        int tests;
        readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		int a, b;
		readf (" %s %s", &a, &b);
		writefln ("%s", steps (a, b));
	}
	return 0;
}


Polycarp wrote on a whiteboard an array $$$p$$$ of length $$$n$$$, which is a permutation of numbers from $$$1$$$ to $$$n$$$. In other words, in $$$p$$$ each number from $$$1$$$ to $$$n$$$ occurs exactly once.He also prepared a resulting array $$$a$$$, which is initially empty (that is, it has a length of $$$0$$$).After that, he did exactly $$$n$$$ steps. Each step looked like this:  Look at the leftmost and rightmost elements of $$$p$$$, and pick the smaller of the two. If you picked the leftmost element of $$$p$$$, append it to the left of $$$a$$$; otherwise, if you picked the rightmost element of $$$p$$$, append it to the right of $$$a$$$. The picked element is erased from $$$p$$$. Note that on the last step, $$$p$$$ has a length of $$$1$$$ and its minimum element is both leftmost and rightmost. In this case, Polycarp can choose what role the minimum element plays. In other words, this element can be added to $$$a$$$ both on the left and on the right (at the discretion of Polycarp).Let's look at an example. Let $$$n=4$$$, $$$p=[3, 1, 4, 2]$$$. Initially $$$a=[]$$$. Then: During the first step, the minimum is on the right (with a value of $$$2$$$), so after this step, $$$p=[3,1,4]$$$ and $$$a=[2]$$$ (he added the value $$$2$$$ to the right).  During the second step, the minimum is on the left (with a value of $$$3$$$), so after this step, $$$p=[1,4]$$$ and $$$a=[3,2]$$$ (he added the value $$$3$$$ to the left).  During the third step, the minimum is on the left (with a value of $$$1$$$), so after this step, $$$p=[4]$$$ and $$$a=[1,3,2]$$$ (he added the value $$$1$$$ to the left).  During the fourth step, the minimum is both left and right (this value is $$$4$$$). Let's say Polycarp chose the right option. After this step, $$$p=[]$$$ and $$$a=[1,3,2,4]$$$ (he added the value $$$4$$$ to the right).Thus, a possible value of $$$a$$$ after $$$n$$$ steps could be $$$a=[1,3,2,4]$$$.You are given the final value of the resulting array $$$a$$$. Find any possible initial value for $$$p$$$ that can result the given $$$a$$$, or determine that there is no solution.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case consists of two lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. All elements of the $$$a$$$ array are distinct numbers. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each of the lines must contain the answer to the corresponding set of input data: numbers $$$p_1, p_2, \dots, p_n$$$  — any of the possible initial values of the array $$$p$$$, which will lead to the given array $$$a$$$. All elements of $$$p$$$ are distinct integers from $$$1$$$ to $$$n$$$. Thus, if there are several solutions, print any. If there is no solution, then print -1 on the line.

NoteThe first test case in the example is clarified in the main section of the problem statement. There may be other correct answers for this test set.In the second test case, $$$n=1$$$. Thus, there is only one permutation that can be the answer: $$$p=[1]$$$. Indeed, this is the answer to this test case.In the third test case of the example, no matter what permutation you take as $$$p$$$, after applying the $$$n$$$ steps, the result will differ from $$$a=[1, 3, 5, 4, 2]$$$.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    auto mx = a.maxElement;
    if (mx != a[0] && mx != a[$ - 1]) {
      writeln(-1);
      continue;
    }
    if (mx == a[0])
      a = a[1 .. $];
    else
      a = a[0 .. $ - 1];
    writefln("%(%s %)", [mx] ~ a.reverse);
  }
}

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.splitter.map !(to !(int)).array;
		if (a.front == n || a.back == n)
		{
			a.retro.writefln !("%(%s %)");
		}
		else
		{
			writeln (-1);
		}
	}
}


You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations:  swap $$$a_k$$$ and $$$a_4$$$;  swap $$$a_2$$$ and $$$a_2$$$;  swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto m = RD!int;
		int ll = x, rr = x;
		foreach (i; 0..m)
		{
			auto l = RD!int;
			auto r = RD!int;
			if (l <= rr && r >= ll)
			{
				ll.chmin(l);
				rr.chmax(r);
			}
		}
		ans[ti] = rr-ll+1;
	}

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


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.

Output the minimum length of the string that may remain after applying the described operations several times.

NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .

import std.stdio;
import core.stdc.stdio;
import std.string;
import std.regex;
import std.math;
import std.algorithm;

string readline()
{
	string l = readln();
	if (l[$-1] == '\n') l.length--;
	return l;
}

int main(string[] argv)
{
	readline();
	string l = readline();
	int[] c; c.length = 1000;
	int idx = 0; c[idx]++;
	char cc = l[0];
	int cidx = 1;
	while (cidx < l.length)
	{
		if (cc == l[cidx])
		{
			c[idx]++;
		} else {
			cc = l[cidx];
			if (idx > 0)
			{
				int min = min(c[idx-1], c[idx]);
				c[idx-1] -= min;
				c[idx]   -= min;
				if (c[idx] == 0)
				{
					idx--;
					c[idx]++;
				} else {
					idx++;
					c[idx]++;
				}
			} else {
				idx++;
				c[idx]++;
			}
		}
		cidx++;
	}
	if (idx > 0)
	{
		int min = min(c[idx-1], c[idx]);
		c[idx-1] -= min;
		c[idx] -= min;
	}
	int gcount = 0;
	foreach (int i; 0..(idx+1))
	{
		gcount += c[i];
	}
	printf("%d", gcount);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.string;
import std.regex;
import std.math;
import std.algorithm;

string readline()
{
	string l = readln();
	if (l[$-1] == '\n') l.length--;
	return l;
}

int main(string[] argv)
{
	readline();
	string l = readline();
	int[] c; c.length = 1000;
	int idx = 0; c[idx]++;
	char cc = l[0];
	int cidx = 1;
	while (cidx < l.length)
	{
		if (cc == l[cidx])
		{
			c[idx]++;
		} else {
			cc = l[cidx];
			if (idx > 0)
			{
				int min = min(c[idx-1], c[idx]);
				c[idx-1] -= min;
				c[idx]   -= min;
			}
			idx++;
			c[idx]++;
		}
		cidx++;
	}
	int min = min(c[idx-1], c[idx]);
	c[idx-1] -= min;
	c[idx] -= min;
	int gcount = 0;
	foreach (int i; 0..(idx+1))
	{
		gcount += c[i];
	}
	printf("%d", gcount);
	return 0;
}

import std.stdio;
import core.stdc.stdio;
import std.string;
import std.regex;
import std.math;
import std.algorithm;

string readline()
{
	string l = readln();
	if (l[$-1] == '\n') l.length--;
	return l;
}

int main(string[] argv)
{
	readline();
	string l = readline();
	int[] c; c.length = 1000;
	int idx = 0; c[idx]++;
	char cc = l[0];
	int cidx = 1;
	while (cidx < l.length)
	{
		if (cc == l[cidx])
		{
			c[idx]++;
		} else {
			cc = l[cidx];
			if (idx > 0)
			{
				int min = min(c[idx-1], c[idx]);
				c[idx-1] -= min;
				c[idx]   -= min;
				if (c[idx] == 0)
				{
					idx--;
				} else {
					idx++;
					c[idx]++;
				}
			} else {
				idx++;
				c[idx]++;
			}
		}
		cidx++;
	}
	int min = min(c[idx-1], c[idx]);
	c[idx-1] -= min;
	c[idx] -= min;
	int gcount = 0;
	foreach (int i; 0..(idx+1))
	{
		gcount += c[i];
	}
	printf("%d", gcount);
	return 0;
}


Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers h1, h2, ..., hn (1  ≤  hi  ≤  105) representing the heights of the pylons.

Print a single number representing the minimum number of dollars paid by Caisa.

NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

unittest{
  assert(solve([3,4,3,2,4]) == 4, "Teste 1");
}

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

  long e = 0;
  long pa = 0;
  long c = 0;
  for(size_t i = 0; i < n; i++){
    long p;
    readf("%s ",&p);
    e += (pa - p);
    pa = p;
    //writeln(e);
    if( e < 0 ){
      c = c - e;
      e = 0;
    }
  }
  writeln(c);
}


We guessed some integer number $$$x$$$. You are given a list of almost all its divisors. Almost all means that there are all divisors except $$$1$$$ and $$$x$$$ in the list.Your task is to find the minimum possible integer $$$x$$$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 300$$$) — the number of divisors in the list. The second line of the query contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$2 \le d_i \le 10^6$$$), where $$$d_i$$$ is the $$$i$$$-th divisor of the guessed number. It is guaranteed that all values $$$d_i$$$ are distinct.

For each query print the answer to it. If the input data in the query is contradictory and it is impossible to find such number $$$x$$$ that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible $$$x$$$.

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

void solve() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    long ans = -1;

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

    long[] F;
    for (long i = 2; i * i <= ans; ++i) {
        if (ans % i == 0) {
            F ~= i;
            if (i * i != ans) {
                F ~= ans / i;
            }
        }
    }
    F.sort();

    writeln(F == A ? ans : -1);
}

void main() {
    auto N = readln.chomp.to!int;
    while (N--) solve;
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int t = read.to!int;

	foreach(q; 0 .. t){

		int n = read.to!int;
		long[] as;
		foreach(i; 0 .. n) as ~= read.to!long;

		as.sort!();

		long x = as[0] * as[$ - 1];
		int flag = 1;

		int k = 0;
		for(long d = 2; d * d <= x; d ++){
			if(x % d == 0){
				if(as[k] == d && as[$ - 1 - k] == x / d){
					k += 1;
					continue;
				}
				else flag = -1;
			}
		}
		if(k <= n - 1 - k) flag = -1;

		if(flag < 0) "-1".writeln;
		else x.writeln;

	}
}

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

alias Tree = RBT!int;

void main() {
    GC.disable();

    int t;
    readf(" %s", t);

    int[][] factors = new int[] [1_000_009];
    bool[] primes = new bool [1_000_009];
    primes[] = true;
    foreach(i; 2 .. 1_000_000) {
      if (primes[i]) {
        factors[i] ~= i;

        for(uint j = 2*i; j <= 1_000_000; j += i) {
          primes[j] = false;
          factors[j] ~= i;
        }
      }
    }

    foreach(q; 0 .. t) {

      uint n;

      readf(" %s", n);

      auto d = new int [n];
      int[int] allprimes;

      foreach(i; 0 .. n) {
        readf(" %s", d[i]);

        foreach(p; factors[ d[i] ]) {
          int pow = 0;
          int t_ = d[i];
          while ( t_ % p == 0) { pow++; t_ /= p; }

          if (p in allprimes) {
            allprimes[p] = max( allprimes[p], pow );
          } else {
            allprimes[p] = pow;
          }
        }
      }

      long num_divisors = 1;
      long x =1 ;
      long sp = -1;
      foreach(k,v; allprimes) {
        // writeln(k, " ", v);
        sp = v;
        num_divisors *= (v+1);
        if (num_divisors > n+2) break;
        x *= pow(k, v);
      }

      long ans = -1;
      if (num_divisors > n+2) { writeln(-1); }
      else if (d.canFind(x)) {
        foreach(k, v; allprimes) {
          auto new_num_divisors = num_divisors / (v+1) * (v+2);
          if (new_num_divisors == n+2) {
            auto newx = x * k;
            if (ans == -1) ans = newx; else ans = min(ans, newx);
          }
        }

        if (ans != -1) writeln(ans); else writeln(-1);
      }
      else if (n==1) {
        if (primes[d[0]]) writeln(d[0]*d[0]); else writeln(-1);
      } else if (allprimes.length == 1) {
        if (num_divisors == n + 1) {
          writeln(x*sp);
        } else {
          writeln(-1);
        }

      } else if (num_divisors != n+2) writeln(-1);
      else {
        writeln(x);
      }

    }
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int t = read.to!int;

	foreach(q; 0 .. t){

		int n = read.to!int;
		int[] as;
		foreach(i; 0 .. n) as ~= read.to!int;

		as.sort!();

		int x = as[0] * as[$ - 1];
		int flag = 1;

		int k = 0;
		for(int d = 2; d * d <= x; d ++){
			if(x % d == 0){
				if(as[k] == d && as[$ - 1 - k] == x / d){
					k += 1;
					continue;
				}
				else flag = -1;
			}
			else{
				if(as[k] != d) continue;
				else flag = -1;
			}
		}
		if(k <= n - 1 - k) flag = -1;

		if(flag < 0) "-1".writeln;
		else x.writeln;

	}
}

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

alias Tree = RBT!int;

void main() {
    GC.disable();

    int t;
    readf(" %s", t);

    int[][] factors = new int[] [1_000_009];
    bool[] primes = new bool [1_000_009];
    primes[] = true;
    foreach(i; 2 .. 1_000_000) {
      if (primes[i]) {
        factors[i] ~= i;

        for(uint j = 2*i; j <= 1_000_000; j += i) {
          primes[j] = false;
          factors[j] ~= i;
        }
      }
    }

    foreach(q; 0 .. t) {

      uint n;

      readf(" %s", n);

      auto d = new int [n];
      int[int] allprimes;

      foreach(i; 0 .. n) {
        readf(" %s", d[i]);

        foreach(p; factors[ d[i] ]) {
          int pow = 0;
          int t_ = d[i];
          while ( t_ % p == 0) { pow++; t_ /= p; }

          if (p in allprimes) {
            allprimes[p] = max( allprimes[p], pow );
          } else {
            allprimes[p] = pow;
          }
        }
      }

      long num_divisors = 1;
      long x =1 ;
      long sp = -1;
      foreach(k,v; allprimes) {
        // writeln(k, " ", v);
        sp = v;
        num_divisors *= (v+1);
        if (num_divisors > n+2) break;
        x *= pow(k, v);
      }

      if (n==1) {
        if (primes[d[0]]) writeln(d[0]*d[0]); else writeln(-1);
      } else if (allprimes.length == 1) {
        if (num_divisors == n + 1) {
          writeln(x*sp);
        } else {
          writeln(-1);
        }

      } else if (num_divisors != n+2) writeln(-1);
      else {
        writeln(x);
      }

    }
}

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

alias Tree = RBT!int;

void main() {
    GC.disable();

    int t;
    readf(" %s", t);

    int[][] factors = new int[] [1_000_009];
    bool[] primes = new bool [1_000_009];
    primes[] = true;
    foreach(i; 2 .. 1_000_000) {
      if (primes[i]) {
        factors[i] ~= i;

        for(uint j = 2*i; j <= 1_000_000; j += i) {
          primes[j] = false;
          factors[j] ~= i;
        }
      }
    }

    foreach(q; 0 .. t) {

      uint n;

      readf(" %s", n);

      auto d = new int [n];
      int[int] allprimes;

      foreach(i; 0 .. n) {
        readf(" %s", d[i]);

        foreach(p; factors[ d[i] ]) {
          int pow = 0;
          int t_ = d[i];
          while ( t_ % p == 0) { pow++; t_ /= p; }

          if (p in allprimes) {
            allprimes[p] = max( allprimes[p], pow );
          } else {
            allprimes[p] = pow;
          }
        }
      }

      long num_divisors = 1;
      long x =1 ;
      foreach(k,v; allprimes) {
        // writeln(k, " ", v);
        num_divisors *= (v+1);
        if (num_divisors > n+2) break;
        x *= pow(k, v);
      }

      if (n==1) {
        if (primes[d[0]]) writeln(d[0]*d[0]);
        else writeln(-1);
      } else
      if (num_divisors != n+2) writeln(-1);
      else {
        writeln(x);
      }

    }
}


The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$ — the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$) — the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.

For each query, print a single integer — the maximum total value of items received for free for one purchase.

NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.

void main() { runSolver(); }

void problem() {
  auto TN = 1;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto QN = scan!int;
      auto P = scan!long(N).sort;
      auto XY = scan!int(2 * QN).chunks(2);

      auto acc = 0 ~ P.cumulativeFold!"a + b".array;
      return XY.map!(xy => {
        auto x = xy[0];
        auto y = xy[1];
        auto r = acc[$ - x - 1..$];
        return r[y] - r[0];
      }());
    }

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

  outputForAtCoder(&solve);
}

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

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

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


Palindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k > 1) if and only if:   Its left half equals to its right half.  Its left and right halfs are non-empty (k - 1)-palindromes. The left half of string t is its prefix of length ⌊|t| / 2⌋, and right half — the suffix of the same length. ⌊|t| / 2⌋ denotes the length of string t divided by 2, rounded down.Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.

The first line contains the string s (1 ≤ |s| ≤ 5000) consisting of lowercase English letters.

Print |s| integers — palindromic characteristics of string s.

NoteIn the first example 1-palindromes are substring «a», «b», «b», «a», «bb», «abba», the substring «bb» is 2-palindrome. There are no 3- and 4-palindromes here.

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

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    auto P_odd = new int[](N);
    auto P_even = new int[](N);

    foreach (i; 0..N) {
        P_odd[i] = 1;
        for (int j = 1; i - j >= 0 && i + j < N && S[i - j] == S[i + j]; ++j) {
            P_odd[i] += 2;
        }
    }

    foreach (i; 0..N-1) {
        for (int j = 0; i - j >= 0 && i + j + 1 < N && S[i - j] == S[i + j + 1]; ++j) {
            P_even[i] += 2;
        }
    }

    auto mem = new int[][](N, N);
    foreach (i; 0..N) fill(mem[i], -1);

    int dfs(int i, int j) {
        if (mem[i][j] >= 0) return mem[i][j];
        if (i > j) return 0;
        if (i == j) return 1;

        int L = j - i + 1;
        int m = (i + j) / 2;
        int ret;

        if (L % 2 == 1) {
            if (P_odd[m] >= L)
                ret = dfs(i, m - 1) + 1;
            else
                ret = 0;
        } else {
            if (P_even[m] >= L)
                ret = dfs(i, m) + 1;
            else
                ret = 0;
        }

        return mem[i][j] = ret;
    }

    auto A = new int[](N + 2);
    foreach (i; 0..N) {
        foreach (j; i..N) {
            int ret = dfs(i, j);
            A[0] += 1;
            A[ret + 1] -= 1;
        }
    }

    foreach (i; 0..N) A[i + 1] += A[i];

    A[1..$-1].map!(a => a.to!string).join(" ").writeln;
}

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

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    auto P_odd = new int[](N);
    auto P_even = new int[](N);

    foreach (i; 0..N) {
        P_odd[i] = 1;
        for (int j = 1; i - j >= 0 && i + j < N && S[i - j] == S[i + j]; ++j) {
            P_odd[i] += 2;
        }
    }

    foreach (i; 0..N-1) {
        for (int j = 0; i - j >= 0 && i + j + 1 < N && S[i - j] == S[i + j + 1]; ++j) {
            P_even[i] += 2;
        }
    }

    auto mem = new int[][](N, N);
    foreach (i; 0..N) fill(mem[i], -1);

    int dfs(int i, int j) {
        if (mem[i][j] >= 0) return mem[i][j];
        if (i > j) return 0;
        if (i == j) return 1;

        int L = j - i + 1;
        int m = (i + j) / 2;
        int ret;

        if (L % 2 == 1) {
            if (P_odd[m] >= L)
                ret = dfs(i, m - 1) + 1;
            else
                ret = 0;
        } else {
            if (P_even[m] >= L)
                ret = dfs(i, m) + 1;
            else
                ret = 0;
        }

        return mem[i][j] = ret;
    }

    auto A = new int[](N + 2);
    foreach (i; 0..N) {
        foreach (j; i..N) {
            int ret = dfs(i, j);
            A[0] += 1;
            A[ret + 1] -= 1;
        }
    }

    foreach (i; 0..N) A[i + 1] += A[i];

    A[1..$].map!(a => a.to!string).join(" ").writeln;
}


Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $$$n$$$ vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $$$1$$$ to $$$n$$$ which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?We remind that cyclic shift of permutation $$$a_1, a_2, \ldots, a_k, \ldots, a_n$$$ for $$$k$$$ elements to the left is the permutation $$$a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$$$.

First line contains an integer number $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — length of the permutation. Second line contains $$$n$$$ integer numbers $$$a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n)$$$, and it is guaranteed that all numbers occur exactly one time.

Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from $$$0$$$ to $$$n - 1$$$. If there are several possible answers, print any of them.

NoteThe following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved.

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

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

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

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

enum E = 18;

int N;
int[] A;

int[] B;
Tuple!(int, int)[][] BMins;

int getMinIndex(int l, int r) {
  const e = bsr(r - l);
  return min(BMins[e][l], BMins[e][r - (1 << e)])[1];
}

int calc(int l, int r) {
  if (r - l == 0) {
    return 0;
  } else {
    const mid = getMinIndex(l, r);
    const resL = calc(l, mid);
    const resR = calc(mid + 1, r);
    return max(resL, resR) + 1;
  }
}

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

      const i0 = A.minIndex;
      B = A[i0 .. N] ~ A[0 .. i0];
      BMins = new Tuple!(int, int)[][](E, N);
      foreach (i; 0 .. N) {
        BMins[0][i] = tuple(B[i], i);
      }
      foreach (e; 0 .. E - 1) {
        foreach (i; 0 .. N) {
          BMins[e + 1][i] = BMins[e][i];
          if (i + (1 << e) < N) {
            chmin(BMins[e + 1][i], BMins[e][i + (1 << e)]);
          }
        }
      }
      debug {
        writeln("B = ", B);
        foreach (i; 0 .. N) foreach (j; i + 1 .. N + 1) {
          int km = i;
          foreach (k; i .. j) {
            if (B[km] > B[k]) {
              km = k;
            }
          }
          assert(km == getMinIndex(i, j));
        }
      }

      int lo = 0, hi = N - 1;
      for (; lo + 1 < hi; ) {
        // (mid) B[0] (N - 1 - mid)
        const mid = (lo + hi) / 2;
        const resL = calc(N - mid, N);
        const resR = calc(1, N - mid);
        (resL < resR) ? (lo = mid) : (hi = mid);
      }

      long ans;
      {
        const resL = calc(N - hi, N);
        const resR = calc(1, N - hi);
        ans = max(resL, resR) + 1;
      }
      int shift = i0;
      shift += N - hi;
      shift %= N;
      writeln(ans, " ", shift);

      debug {
        auto dp = new int[][](2 * N + 1, 2 * N + 1);
        foreach (i; 0 .. 2 * N) {
          dp[i][i + 1] = 1;
        }
        foreach (w; 2 .. 2 * N + 1) {
          foreach (i; 0 .. 2 * N - w + 1) {
            const j = i + w;
            int km = i;
            foreach (k; i .. j) {
              if (A[km % N] > A[k % N]) {
                km = k;
              }
            }
            dp[i][j] = max(dp[i][km], dp[km + 1][j]) + 1;
          }
        }
        /*
        writeln("dp = ");
        foreach (i; 0 .. 2 * N + 1) {
          writeln(dp[i]);
        }
        //*/
        int brt = N + 1;
        foreach (i; 0 .. N) {
          writeln(i, ": ", dp[i][i + N]);
          chmin(brt, dp[i][i + N]);
        }
        assert(brt == ans);
        assert(brt == dp[shift][shift + N]);
      }
    }
  } catch (EOFException e) {
  }
}


You are given a prime number $$$p$$$, $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, and an integer $$$k$$$. Find the number of pairs of indexes $$$(i, j)$$$ ($$$1 \le i < j \le n$$$) for which $$$(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$$$.

The first line contains integers $$$n, p, k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$2 \le p \le 10^9$$$, $$$0 \le k \le p-1$$$). $$$p$$$ is guaranteed to be prime. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le p-1$$$). It is guaranteed that all elements are different.

Output a single integer — answer to the problem.

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

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

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

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

// xorshift
uint xrand() {
  static uint x = 314159265, y = 358979323, z = 846264338, w = 327950288;
  uint t = x ^ x << 11; x = y; y = z; z = w; return w = w ^ w >> 19 ^ t ^ t >> 8;
}

// a^-1 (mod m)
long modInv(long a, long m)
in {
  assert(m > 0, "modInv: m > 0 must hold");
}
do {
  long b = m, x = 1, y = 0, t;
  for (; ; ) {
    t = a / b; a -= t * b;
    if (a == 0) {
      assert(b == 1 || b == -1, "modInv: gcd(a, m) != 1");
      if (b == -1) y = -y;
      return (y < 0) ? (y + m) : y;
    }
    x -= t * y;
    t = b / a; b -= t * a;
    if (b == 0) {
      assert(a == 1 || a == -1, "modInv: gcd(a, m) != 1");
      if (a == -1) x = -x;
      return (x < 0) ? (x + m) : x;
    }
    y -= t * x;
  }
}

// (a / 2) mod m
long div2(long a, long m)
in {
  assert(1 <= m && m < 1L << 62, "div2: 1 <= m < 2^62 must hold");
  assert(m % 2 != 0, "div2: m must not be divisibly by 3");
  assert(0 <= a && a < m, "div2: 0 <= a < m must hold");
}
do {
  return (a + (a % 2) * m) / 2;
}

// (a / 3) mod m
long div3(long a, long m)
in {
  assert(1 <= m && m < 1L << 61, "div3: 1 <= m < 2^61 must hold");
  assert(m % 3 != 0, "div3: m must not be divisibly by 3");
  assert(0 <= a && a < m, "div3: 0 <= a < m must hold");
}
do {
  return (a + (((3 - a % 3) * (m % 3)) % 3) * m) / 3;
}

// Jacobi symbol (a/m)
int jacobi(long a, long m)
in {
  assert(m > 0, "jacobi: m > 0 must hold");
  assert(m & 1, "jacobi: m must be odd");
}
do {
  import core.bitop : bsf;
  import std.algorithm.mutation : swap;
  int s = 1;
  if (a < 0) a = a % m + m;
  for (; m > 1; ) {
    a %= m;
    if (a == 0) return 0;
    const r = bsf(a);
    if ((r & 1) && ((m + 2) & 4)) s = -s;
    a >>= r;
    if (a & m & 2) s = -s;
    swap(a, m);
  }
  return s;
}

// sqrt(a) (mod p)
//   p: be prime
//   (b + sqrt(b^2 - a))^((p+1)/2) in F_p(sqrt(b^2 - a))
long[] modSqrt(long a, long p)
in {
  assert(p < 1L << 31, "modSqrt: p < 2^31 must hold");
  assert(-p * p <= a && a <= p * p, "modSqrt: -p^2 <= a <= p^2 must hold");
}
do {
  if (p == 2) return [a & 1];
  const j = jacobi(a, p);
  if (j == 0) return [0];
  if (j == -1) return [];
  long b, d;
  for (; ; ) {
    b = xrand() % p;
    d = (b * b - a) % p;
    if (d < 0) d += p;
    if (jacobi(d, p) == -1) break;
  }
  long[2] multiply(in long[2] x, in long[2] y) {
    return [(x[0] * y[0] + d * ((x[1] * y[1]) % p)) % p,
            (x[0] * y[1] + x[1] * y[0]) % p];
  }
  long[2] f = [b, 1], g = [1, 0];
  for (long e = (p + 1) >> 1; e; e >>= 1) {
    if (e & 1) g = multiply(g, f);
    f = multiply(f, f);
  }
  assert(g[1] == 0);
  return (g[0] < p - g[0]) ? [g[0], p - g[0]] : [p - g[0], g[0]];
}

// Roots of f0 + f1 T + T^2 in F_p[T] with multiplicity
//   p: prime
long[] modRoots2(long f0, long f1, long p)
in {
  assert(2 <= p && p < 1L << 31, "modRoots2: 2 <= p < 2^31 must hold");
  assert(0 <= f0 && f0 < p, "modRoots2: 0 <= f0 < p must hold");
  assert(0 <= f1 && f1 < p, "modRoots2: 0 <= f1 < p must hold");
}
do {
  import std.algorithm : sort;
  if (p == 2) {
    if (f0 == 0 && f1 == 0) return [0, 0];
    if (f0 == 0 && f1 == 1) return [0, 1];
    if (f0 == 1 && f1 == 0) return [1, 1];
    return [];
  } else {
    const f12 = f1.div2(p);
    auto ts = modSqrt(f12 * f12 - f0, p);
    foreach (ref t; ts) {
      if ((t -= f12) < 0) t += p;
    }
    sort(ts);
    switch (ts.length) {
      case 0: return [];
      case 1: return [ts[0], ts[0]];
      case 2: return ts;
      default: assert(false);
    }
  }
}

// Roots of f0 + f1 T + f2 T^2 + T^3 in F_p[T] with multiplicity
//   p: prime
long[] modRoots3(long f0, long f1, long f2, long p)
in {
  assert(2 <= p && p <= 1_500_000_001,
         "modRoots3: 2 <= p <= 1_500_000_001 must hold");
  assert(0 <= f0 && f0 < p, "modRoots3: 0 <= f0 < p must hold");
  assert(0 <= f1 && f1 < p, "modRoots3: 0 <= f1 < p must hold");
  assert(0 <= f2 && f2 < p, "modRoots3: 0 <= f2 < p must hold");
}
do {
  import std.algorithm : sort;
  if (p == 2) {
    if (f0 == 0 && f1 == 0 && f2 == 0) return [0, 0, 0];
    if (f0 == 0 && f1 == 0 && f2 == 1) return [0, 0, 1];
    if (f0 == 0 && f1 == 1 && f2 == 0) return [0, 1, 1];
    if (f0 == 1 && f1 == 1 && f2 == 1) return [1, 1, 1];
    if (f0 == 0) return [0];
    if ((f0 + f1 + f2 + 1) % 2 == 0) return [1];
    return [];
  } else if (p == 3) {
    if (f0 == 0 && f1 == 0 && f2 == 0) return [0, 0, 0];
    if (f0 == 0 && f1 == 0 && f2 == 2) return [0, 0, 1];
    if (f0 == 0 && f1 == 0 && f2 == 1) return [0, 0, 2];
    if (f0 == 0 && f1 == 1 && f2 == 1) return [0, 1, 1];
    if (f0 == 0 && f1 == 2 && f2 == 0) return [0, 1, 2];
    if (f0 == 0 && f1 == 1 && f2 == 2) return [0, 2, 2];
    if (f0 == 2 && f1 == 0 && f2 == 0) return [1, 1, 1];
    if (f0 == 1 && f1 == 2 && f2 == 2) return [1, 1, 2];
    if (f0 == 2 && f1 == 2 && f2 == 1) return [1, 2, 2];
    if (f0 == 1 && f1 == 0 && f2 == 0) return [2, 2, 2];
    if (f0 == 0) return [0];
    if ((f0 + f1 + f2 + 1) % 3 == 0) return [1];
    if ((f0 - f1 + f2 - 1) % 3 == 0) return [2];
    return [];
  } else {
    // gcd(f0 + f1 T + f2 T^2 + T^3, f1 + 2 f2 T + 3 T^2)
    //   remainder: (f0 - f1 f2 / 9) + (2 f1 / 3 - 2 f2^2 / 9) T
    const f13 = f1.div3(p), f23 = f2.div3(p);
    long a0 = (f0 - f13 * f23) % p, a1 = (2 * f13 - 2 * f23 * f23) % p;
    if (a0 < 0) a0 += p;
    if (a1 < 0) a1 += p;
    if (a1 != 0) {
      if ((f13 * ((a1 * a1) % p) - 2 * f23 * ((a0 * a1) % p) + a0 * a0) % p != 0) {
        // gcd = 1
      } else {
        // gcd = a0 + a1 T
        const t2 = ((p - a0) * a1.modInv(p)) % p;
        long t1 = (-f2 - 2 * t2) % p;
        if (t1 < 0) t1 += p;
        auto ts = [t1, t2, t2];
        sort(ts);
        return ts;
      }
    } else if (a0 != 0) {
      // gcd = 1
    } else {
      // gcd = f1 + 2 f2 T + 3 T^2
      const t = (f23 != 0) ? (p - f23) : 0;
      return [t, t, t];
    }

    long[3] mul(in long[3] a, in long[3] b) {
      long[3] c = [a[0] * b[0], a[0] * b[1] + a[1] * b[0],
                a[0] * b[2] + a[1] * b[1] + a[2] * b[0]];
      long c3 = a[1] * b[2] + a[2] * b[1], c4 = a[2] * b[2];
      c4 %= p;
      c[1] -= f0 * c4; c[2] -= f1 * c4; c3 -= f2 * c4;
      c3 %= p;
      c[0] -= f0 * c3; c[1] -= f1 * c3; c[2] -= f2 * c3;
      if ((c[0] %= p) < 0) c[0] += p;
      if ((c[1] %= p) < 0) c[1] += p;
      if ((c[2] %= p) < 0) c[2] += p;
      return c;
    }

    // f: square-free
    // gcd(f, T^p - T)
    long[3] t2 = [0, 1, 0], tp = [1, 0, 0];
    for (long e = p; e; e >>= 1) {
      if (e & 1) tp = mul(tp, t2);
      t2 = mul(t2, t2);
    }
    if (--tp[1] < 0) tp[1] += p;
    if (tp[2] != 0) {
      const invTp2 = tp[2].modInv(p);
      (tp[0] *= invTp2) %= p;
      (tp[1] *= invTp2) %= p;
      long b0 = (f0 - (f2 - tp[1]) * tp[0]) % p;
      long b1 = (f1 - tp[0] - (f2 - tp[1]) * tp[1]) % p;
      if (b0 < 0) b0 += p;
      if (b1 < 0) b1 += p;
      if (b1 != 0) {
        if ((tp[0] * ((b1 * b1) % p) - tp[1] * ((b0 * b1) % p) + b0 * b0) % p != 0) {
          // gcd = 1
          return [];
        } else {
          // gcd = b0 + b1 T
          return [((p - b0) * b1.modInv(p)) % p];
        }
      } else if (b0 != 0) {
        // gcd = 1
        return [];
      } else {
        // gcd = tp[0] + tp[1] T + T^2
        assert(false);
      }
    } else if (tp[1] != 0) {
      const tp02 = (tp[0] * tp[0]) % p, tp12 = (tp[1] * tp[1]) % p;
      if ((((f0 * tp[1] - f1 * tp[0]) % p) * tp12 +
           ((f2 * tp[1] - tp[0]) % p) * tp02) % p != 0) {
        // gcd = 1
        return [];
      } else {
        // gcd = tp[0] + tp[1] T
        return [((p - tp[0]) * tp[1].modInv(p)) % p];
      }
    } else if (tp[0] != 0) {
      // gcd = 1
      return [];
    } else {
      // gcd = f0 + f1 T + f2 T^2 + T^3
    }

    // f: split
    for (; ; ) {
      // gcd(rand^((p-1)/2) - 1, f)
      long[3] r2 = [xrand() % p, xrand() % p, xrand() % p], rp = [1, 0, 0];
      for (long e = (p - 1) / 2; e; e >>= 1) {
        if (e & 1) rp = mul(rp, r2);
        r2 = mul(r2, r2);
      }
      if (--rp[0] < 0) rp[0] += p;
      if (rp[2] != 0) {
        const invRp2 = rp[2].modInv(p);
        (rp[0] *= invRp2) %= p;
        (rp[1] *= invRp2) %= p;
        long c0 = (f0 - (f2 - rp[1]) * rp[0]) % p;
        long c1 = (f1 - rp[0] - (f2 - rp[1]) * rp[1]) % p;
        if (c0 < 0) c0 += p;
        if (c1 < 0) c1 += p;
        if (c1 != 0) {
          if ((rp[0] * ((c1 * c1) % p) - rp[1] * ((c0 * c1) % p) + c0 * c0) % p != 0) {
            // gcd = 1
          } else {
            // gcd = c0 + c1 T
            const t = ((p - c0) * c1.modInv(p)) % p;
            auto ts = [t] ~ modRoots2((f1 + (f2 + t) * t) % p, (f2 + t) % p, p);
            sort(ts);
            return ts;
          }
        } else if (c0 != 0) {
          // gcd = 1
        } else {
          // gcd = rp[0] + rp[1] T + T^2
          auto ts = modRoots2(rp[0], rp[1], p) ~ [(rp[1] - f2 + p) % p];
          sort(ts);
          return ts;
        }
      } else if (rp[1] != 0) {
        const rp02 = (rp[0] * rp[0]) % p, rp12 = (rp[1] * rp[1]) % p;
        if ((((f0 * rp[1] - f1 * rp[0]) % p) * rp12 +
             ((f2 * rp[1] - rp[0]) % p) * rp02) % p != 0) {
          // gcd = 1
        } else {
          // gcd = rp[0] + rp[1] T
          const t = ((p - rp[0]) * rp[1].modInv(p)) % p;
          auto ts = [t] ~ modRoots2((f1 + (f2 + t) * t) % p, (f2 + t) % p, p);
          sort(ts);
          return ts;
        }
      } else if (rp[0] != 0) {
        // gcd = 1
      } else {
        // gcd = f0 + f1 T + f2 T^2 + T^3
      }
    }
  }
}

int N;
long P, K;
long[] A;

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

      long[long] cnt;
      foreach (a; A) {
        ++cnt[a];
      }

      long ans;
      foreach (a; A) {
        /*
          (A[i] + T) (A[i]^2 + T^2) = k
        */
        const aa = (a * a) % P;
        const res = modRoots3((a * aa - K + P) % P, aa, a, P);
        debug {
          writeln(a, ": ", (a * aa - K + P) % P, " ", aa, " ", a, " ", res);
        }
        foreach (t; res.uniq) {
          if (a < t) {
            if (t in cnt) {
              ans += cnt[t];
            }
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

int N;
long P, K;
long[] A;

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

      auto fs = new long[N];
      foreach (i; 0 .. N) {
        long a2 = (A[i] * A[i]) % P;
        fs[i] = ((a2 * a2 - K * A[i]) % P + P) % P;
      }
      fs.sort;

      long ans;
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && fs[i] == fs[j]; ++j) {}
        ans += (j - i) * (j - i - 1) / 2;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Let us call a point of the plane admissible if its coordinates are positive integers less than or equal to $$$200$$$.There is an invisible rectangle such that:   its vertices are all admissible;  its sides are parallel to the coordinate axes;  its area is strictly positive.  Your task is to guess the perimeter of this rectangle.In order to guess it, you may ask at most $$$4$$$ queries. In each query, you choose a nonempty subset of the admissible points and you are told how many of the chosen points are inside or on the boundary of the invisible rectangle.

NoteThe following is an example of interaction for the first sample intended to show the format of the queries. $$$$$$ \begin{array}{l|l|l} \text{Query (contestant program)} & \text{Answer (interactor)} & \text{Explanation} \\ \hline \mathtt{?\ 4} & & \text{We choose the $4$ vertices of} \\ \mathtt{13\ 5\ 13\ 80\ 123\ 5\ 123\ 80} & \mathtt{4} &\text{the hidden rectangle.}\\ \hline \mathtt{?\ 5} & & \text{We choose $4$ points just outside the hidden}\\ \mathtt{100\ 4\ 100\ 81\ 12\ 40\ 124\ 40\ 50\ 50} & \mathtt{1}& \text{rectangle and also the point $(50,50)$.}\\ \hline \mathtt{?\ 2} & & \text{We choose the points $(1, 1)$} \\ \mathtt{200\ 200\ 1\ 1} & \mathtt{0} & \text{and $(200,200)$.}\\ \hline \mathtt{!\ 370} & & \text{This is the correct perimeter.} \end{array} $$$$$$For the second sample, a possible interaction is the following. $$$$$$ \begin{array}{l|l|l} \text{Query (contestant program)} & \text{Answer (interactor)} & \text{Explanation} \\ \hline \mathtt{?\ 4} & & \text{We choose the points $(3, 2)$, $(4, 1)$,} \\ \mathtt{3\ 2\ 4\ 1\ 5\ 2\ 4\ 3} & 2 & \text{$(5, 2)$ and $(4, 3)$.} \\ \hline \mathtt{?\ 7} & & \text{We choose the points $(1, 4)$, $(2, 4)$,} \\ \mathtt{1\ 4\ 2\ 4\ 1\ 5\ 2\ 5\ 5\ 5\ 5\ 6\ 6\ 5} & 1 & \text{$(1, 5)$, $(2, 5)$, $(5, 5)$, $(5, 6)$ and $(6, 5)$.} \\ \hline \mathtt{!\ 8} & & \text{This is the correct perimeter.} \end{array} $$$$$$ The situation is shown in the following picture:  The green points are the ones belonging to the first query, while the orange points are the ones belonging to the second query. One can see that there are exactly two rectangles consistent with the interactor's answers:   the rectangle of vertices $$$(2, 2)$$$ and $$$(4, 4)$$$, shown in red;  the rectangle of vertices $$$(4, 2)$$$ and $$$(5, 5)$$$, shown in blue.  Since both of these rectangles have perimeter $$$8$$$, this is the final answer.

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

alias Pt = Tuple!(int, "x", int, "y");

debug {
  enum N = 10;
} else {
  enum N = 200;
}

int Ask(Pt[] pts) {
  if (pts.empty) {
    debug {
      writeln("Ask([])");
      stdout.flush;
    }
    return 0;
  }
  const ptsLen = cast(int)(pts.length);
  writeln("? ", ptsLen);
  foreach (i; 0 .. ptsLen) {
    if (i > 0) write(" ");
    write(pts[i].x, " ", pts[i].y);
  }
  writeln;
  stdout.flush;
  const res = readInt();
  return res;
}
void Answer(int p) {
  writeln("! ", p);
  stdout.flush;
}

void main() {
  auto xss = new int[long][N^^2 + 1];
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    auto rss = new int[][3];
    int e;
    foreach_reverse (f; 0 .. 3) {
      const m = 1 << (e | 1 << f);
      foreach (xx; [x / m, (x + m - 1) / m]) {
        rss[f] ~= xx * y;
      }
      rss[f] = rss[f].sort.uniq.array;
      if (x % m == 0) {
        e |= 1 << f;
      }
    }
    foreach (r0; rss[0])
    foreach (r1; rss[1])
    foreach (r2; rss[2])
    {
      const key = cast(long)(r0) | cast(long)(r1) << 16 | cast(long)(r2) << 32;
      if (key in xss[x * y] && xss[x * y][key] != y) {
        writefln("%s %s: %s %s; %s", x, y, e, rss, xss[x * y][key]);
        assert(false);
      }
      xss[x * y][key] = x;
    }
  }

  Pt[] all;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    all ~= Pt(x, y);
  }
  const S = Ask(all);

  auto rs = new int[3];
  int e;
  foreach_reverse (f; 0 .. 3) {
    const m = 1 << (e | 1 << f);
    Pt[] pts;
    foreach (x; 1 .. N + 1) {
      if (x % m == 0) {
        foreach (y; 1 .. N + 1) {
          pts ~= Pt(x, y);
        }
      }
    }
    rs[f] = Ask(pts);
    if (S == m * rs[f]) {
      e |= 1 << f;
    }
  }
  const key = cast(long)(rs[0]) | cast(long)(rs[1]) << 16 | cast(long)(rs[2]) << 32;
  assert(key in xss[S]);

  const ansX = xss[S][key];
  const ansY = S / ansX;
  debug {
    writefln("ansX = %s, ansY = %s", ansX, ansY);
    stdout.flush;
  }
  Answer(2 * ((ansX - 1) + (ansY - 1)));
}

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

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

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

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

alias Pt = Tuple!(int, "x", int, "y");

debug {
  enum N = 10;
} else {
  enum N = 200;
}

int Ask(Pt[] pts) {
  const ptsLen = cast(int)(pts.length);
  writeln("? ", ptsLen);
  foreach (i; 0 .. ptsLen) {
    if (i > 0) write(" ");
    write(pts[i].x, " ", pts[i].y);
  }
  writeln;
  stdout.flush;
  const res = readInt();
  return res;
}
void Answer(int p) {
  writeln("! ", p);
  stdout.flush;
}

void main() {
  Pt[] all;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    all ~= Pt(x, y);
  }
  const S = Ask(all);

  int[] ps, es;
  {
    int s = S;
    for (int p = 2; p^^2 <= s; ++p) {
      if (s % p == 0) {
        int e;
        do {
          ++e;
          s /= p;
        } while (s % p == 0);
        ps ~= p;
        es ~= e;
      }
    }
    if (s > 1) {
      ps ~= s;
      es ~= 1;
    }
  }
  const len = cast(int)(ps.length);
  debug {
    writeln("ps = ", ps);
    writeln("es = ", es);
  }

  auto los = new int[len];
  auto his = new int[len];
  foreach (i; 0 .. len) {
    los[i] = max(es[i] - 7, 0);
    his[i] = es[i] + 1;
  }
  foreach (iter; 0 .. 3) {
    debug {
      writeln("iter = ", iter);
      foreach (i; 0 .. len) {
        writefln("  %s: %s %s", ps[i], ps[i]^^los[i], ps[i]^^(his[i] - 1));
      }
    }
    alias Entry = Tuple!(int, "score", int, "i");
    Entry[] entries;
    foreach (i; 0 .. len) {
      if (los[i] + 1 < his[i]) {
        entries ~= Entry(-bsr(his[i] - los[i]), i);
      }
    }
    entries.sort;
    int mX = 1, mY = 1;
    if (0 < entries.length) {
      const i = entries[0].i;
      const mid = (los[i] + his[i]) / 2;
      mX = ps[i]^^mid;
    }
    if (1 < entries.length) {
      const i = entries[1].i;
      const mid = (los[i] + his[i]) / 2;
      // vX >= mid  <=>  vY < es[i] - mid + 1
      mY = ps[i]^^(es[i] - mid + 1);
    }
    Pt[] pts;
    for (int x = mX; x <= N; x += mX) for (int y = mY; y <= N; y += mY) {
      pts ~= Pt(x, y);
    }
    const res = Ask(pts);
    if (0 < entries.length) {
      const i = entries[0].i;
      const mid = (los[i] + his[i]) / 2;
      ((S == mX * res) ? los[i] : his[i]) = mid;
    }
    if (1 < entries.length) {
      const i = entries[1].i;
      const mid = (los[i] + his[i]) / 2;
      ((S == mY * res) ? his[i] : los[i]) = mid;
    }
  }

  int ansX = 1;
  foreach (i; 0 .. len) {
    assert(los[i] + 1 == his[i]);
    ansX *= ps[i]^^los[i];
  }
  const ansY = S / ansX;
  debug {
    writefln("ansX = %s, ansY = %s", ansX, ansY);
  }
  Answer(2 * ((ansX - 1) + (ansY - 1)));
}

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

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

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

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

alias Pt = Tuple!(int, "x", int, "y");

debug {
  enum N = 10;
} else {
  enum N = 200;
}

int Ask(Pt[] pts) {
  const ptsLen = cast(int)(pts.length);
  writeln("? ", ptsLen);
  foreach (i; 0 .. ptsLen) {
    if (i > 0) write(" ");
    write(pts[i].x, " ", pts[i].y);
  }
  writeln;
  stdout.flush;
  const res = readInt();
  return res;
}
void Answer(int p) {
  writeln("! ", p);
  stdout.flush;
}

void main() {
  Pt[] all;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    all ~= Pt(x, y);
  }
  const S = Ask(all);

  int[] ps, es;
  {
    int s = S;
    for (int p = 2; p^^2 <= s; ++p) {
      if (s % p == 0) {
        int e;
        do {
          ++e;
          s /= p;
        } while (s % p == 0);
        ps ~= p;
        es ~= e;
      }
    }
    if (s > 1) {
      ps ~= s;
      es ~= 1;
    }
  }
  const len = cast(int)(ps.length);
  debug {
    writeln("ps = ", ps);
    writeln("es = ", es);
  }

  auto los = new int[len];
  auto his = new int[len];
  foreach (i; 0 .. len) {
    los[i] = max(es[i] - 7, 0);
    his[i] = es[i] + 1;
  }
  foreach (iter; 0 .. 3) {
    debug {
      writeln("iter = ", iter);
      foreach (i; 0 .. len) {
        writefln("  %s: %s %s", ps[i], ps[i]^^los[i], ps[i]^^(his[i] - 1));
      }
    }
    alias Entry = Tuple!(int, "score", int, "i");
    Entry[] entries;
    foreach (i; 0 .. len) {
      if (los[i] + 1 < his[i]) {
        entries ~= Entry(-bsr(his[i] - los[i]), i);
      }
    }
    entries.sort;
    int mX = 1, mY = 1;
    if (0 < entries.length) {
      const i = entries[0].i;
      const mid = (los[i] + his[i]) / 2;
      mX = ps[i]^^mid;
    }
    if (1 < entries.length) {
      const i = entries[1].i;
      const mid = (los[i] + his[i]) / 2;
      // vX >= mid  <=>  vY < es[i] - mid + 1
      mY = ps[i]^^(es[i] - mid + 1);
    }
    Pt[] pts;
    for (int x = mX; x <= N; x += mX) for (int y = mY; y <= N; y += mY) {
      pts ~= Pt(x, y);
    }
    const res = Ask(pts);
    if (0 < entries.length) {
      const i = entries[0].i;
      const mid = (los[i] + his[i]) / 2;
      ((S == mX * res) ? los[i] : his[i]) = mid;
    }
    if (1 < entries.length) {
      const i = entries[1].i;
      const mid = (los[i] + his[i]) / 2;
      ((S == mY * res) ? his[i] : los[i]) = mid;
    }
  }

  int ansX = 1;
  foreach (i; 0 .. len) {
    assert(los[i] + 1 == his[i]);
    ansX *= ps[i]^^los[i];
  }
  const ansY = S / ansX;
  debug {
    writefln("ansX = %s, ansY = %s", ansX, ansY);
  }
  Answer(2 * (ansX + ansY));
}


PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex.Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.

There are only two numbers in the input: n and k (5 ≤ n ≤ 106, 2 ≤ k ≤ n - 2, gcd(n, k) = 1).

You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.

NoteThe greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines.

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

__gshared:

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

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

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

struct FenwickTree(int n) {
    int[n] t;

    void init() {
        memset(t.ptr, 0x00, t.sizeof);
    }

    void inc(int i) {
        for (; i < n; i |= i + 1)
            t[i]++;
    }

    int get(int right) {
        int result = 0;
        for (; right; right &= right - 1)
            result += t[right - 1];
        return result;
    }
}

FenwickTree!1_000_000 fwt;

void main() {
    int n, k;
    while (read(&n, &k)) {
        k = min(k, n - k);
        version (LocalProject)
            fwt.init();
        long result = 1;
        int cur = 0;
        foreach (i; 0 .. n) {
            int next = cur + k;
            int count;
            if (next <= n)
                count = fwt.get(next) - fwt.get(cur);
            else {
                next -= n;
                count = i - fwt.get(cur) + fwt.get(next);
                result--;
            }
            result += (count << 1) + 1;
            fwt.inc(cur);
            cur = next;
            write(result, ' ');
        }
        writeln();
    }
}

import core.bitop;
import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		k = min (k, n - k);
		int me = 1;
		while (me < n * 2)
		{
			me <<= 1;
		}
		int hi = me << 1;
		auto t = new long [hi];

		void add (int p, long value)
		{
			for (p += me; p > 0; p >>= 1)
			{
				t[p] += value;
			}
		}

		long seg (int lo, int hi)
		{
			long res = 0;
			for (lo += me, hi += me; lo < hi; lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					res += t[lo];
					lo += 1;
				}
				if (hi & 1)
				{
					hi -= 1;
					res += t[hi];
				}
			}
			return res;
		}

		long res = 1;
		int cur = 0;
		foreach (i; 0..n)
		{
			int next = cur + k;
			res += 1 + seg (cur + 1, next);
			write (res, "\n "[i + 1 < n]);

			if (next >= n)
			{
				next -= n;
			}
			add (cur, 1);
			add (next, 1);
			add (cur + n, 1);
			add (next + n, 1);
			cur = next;
		}
		debug {stderr.writeln (res);}
	}
}

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

immutable long MOD = 1_000_000_007;
alias tie = TypeTuple;
alias triplet = Tuple!(int, int, int);

void main(){
    int N, K;
    readVars(N, K);

    K = min(K, N - K);

    int s, t;
    long d = 1;
    long res = 1;

    foreach(i ; 0 .. N){
        t = (s + K) % N;

        if (s < t || t == 0) {
            res += d;
        } else {
            d++;
            res += d;
            d++;
        }

        write(res, i != N - 1 ? ' ' : '\n');

        s = t;
    }
}

class FenwickTree(T){
private:
    T[] data;
    int N;

public:
    this(T[] a){
        data = [cast(T)0] ~ a[];
        N = a.length.to!int;

        foreach (i ; 1 .. N + 1) {
            if (i + (i & (-i)) <= N) {
                data[i + (i & (-i))] += data[i];
            }
        }
    }

    void add(int i, T x) {
        i++;

        while (i <= N) {
            data[i] += x;
            i += i & (-i);
        }
    }

    T getSum(int r) {
        T res;

        while(r > 0){
            res += data[r];
            r -= r & (-r);
        }

        return res;
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

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

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

immutable long MOD = 1_000_000_007;
alias tie = TypeTuple;
alias triplet = Tuple!(int, int, int);

void main(){
    int N, K;
    readVars(N, K);

    K = min(K, N - K);

    int s, t;

    auto a = new long[](N);
    auto ft = new FenwickTree!(long)(a);
    long res = 1;

    foreach(i ; 0 .. N){
        t = (s + K) % N;

        if(s < t){
            res += ft.getSum(t) - ft.getSum(s + 1) + 1;
        } else {
            res += ft.getSum(N) - ft.getSum(s + 1);
            res += ft.getSum(t) + 1;
        }

        write(res, i == N - 1 ? '\n' : ' ');

        ft.add(s, 1);
        ft.add(t, 1);

        s = t;
    }

}

class FenwickTree(T){
private:
    T[] data;
    int N;

public:
    this(T[] a){
        data = [cast(T)0] ~ a[];
        N = a.length.to!int;

        foreach (i ; 1 .. N + 1) {
            if (i + (i & (-i)) <= N) {
                data[i + (i & (-i))] += data[i];
            }
        }
    }

    void add(int i, T x) {
        i++;

        while (i <= N) {
            data[i] += x;
            i += i & (-i);
        }
    }

    T getSum(int r) {
        T res;

        while(r > 0){
            res += data[r];
            r -= r & (-r);
        }

        return res;
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

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

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

immutable long MOD = 1_000_000_007;
alias tie = TypeTuple;
alias triplet = Tuple!(int, int, int);

void main(){
    int N, K;
    readVars(N, K);

    K = min(K, N - K);

    int s, t;
    long d = 1;
    long res = 1;
    //auto ans = new long[](N);

    foreach(i ; 0 .. N){
        t = (s + K) % N;

        if (s < t || t == 0) {
            res += d;
        } else {
            d++;
            res += d;
            d++;
        }

        //ans[i] = res;
        write(res, ' ');

        s = t;
    }
    writeln();

    //writefln("%(%s %)", ans);
}

class FenwickTree(T){
private:
    T[] data;
    int N;

public:
    this(T[] a){
        data = [cast(T)0] ~ a[];
        N = a.length.to!int;

        foreach (i ; 1 .. N + 1) {
            if (i + (i & (-i)) <= N) {
                data[i + (i & (-i))] += data[i];
            }
        }
    }

    void add(int i, T x) {
        i++;

        while (i <= N) {
            data[i] += x;
            i += i & (-i);
        }
    }

    T getSum(int r) {
        T res;

        while(r > 0){
            res += data[r];
            r -= r & (-r);
        }

        return res;
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

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

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

immutable long MOD = 1_000_000_007;
alias tie = TypeTuple;
alias triplet = Tuple!(int, int, int);

void main(){
    int N, K;
    readVars(N, K);

    K = min(K, N - K);

    int s, t;
    long d = 1;
    long res = 1;
    auto ans = new long[](N);

    foreach(i ; 0 .. N){
        t = (s + K) % N;

        if (s < t || t == 0) {
            res += d;
        } else {
            d++;
            res += d;
            d++;
        }

        ans[i] = res;

        s = t;
    }

    writefln("%(%s %)", ans);
}

class FenwickTree(T){
private:
    T[] data;
    int N;

public:
    this(T[] a){
        data = [cast(T)0] ~ a[];
        N = a.length.to!int;

        foreach (i ; 1 .. N + 1) {
            if (i + (i & (-i)) <= N) {
                data[i + (i & (-i))] += data[i];
            }
        }
    }

    void add(int i, T x) {
        i++;

        while (i <= N) {
            data[i] += x;
            i += i & (-i);
        }
    }

    T getSum(int r) {
        T res;

        while(r > 0){
            res += data[r];
            r -= r & (-r);
        }

        return res;
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

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

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

immutable long MOD = 1_000_000_007;
alias tie = TypeTuple;
alias triplet = Tuple!(int, int, int);

void main(){
    int N, K;
    readVars(N, K);

    K = min(K, N - K);

    int s, t;

    auto a = new long[](N);
    auto ft = new FenwickTree!(long)(a);
    auto ans = new long[](N);
    long res = 1;

    foreach(i ; 0 .. N){
        t = (s + K) % N;

        if(s < t){
            res += ft.getSum(t) - ft.getSum(s + 1) + 1;
            ans[i] = res;
        } else {
            res += ft.getSum(N) - ft.getSum(s + 1);
            res += ft.getSum(t) + 1;
            ans[i] = res;
        }

        ft.add(s, 1);
        ft.add(t, 1);

        s = t;
    }

    writefln("%(%s %)", ans);
}

class FenwickTree(T){
private:
    T[] data;
    int N;

public:
    this(T[] a){
        data = [cast(T)0] ~ a[];
        N = a.length.to!int;

        foreach (i ; 1 .. N + 1) {
            if (i + (i & (-i)) <= N) {
                data[i + (i & (-i))] += data[i];
            }
        }
    }

    void add(int i, T x) {
        i++;

        while (i <= N) {
            data[i] += x;
            i += i & (-i);
        }
    }

    T getSum(int r) {
        T res;

        while(r > 0){
            res += data[r];
            r -= r & (-r);
        }

        return res;
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

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

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

__gshared:

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

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

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

struct FenwickTree(int n) {
    int[n] t;

    void init() {
        memset(t.ptr, 0x00, t.sizeof);
    }

    void inc(int i) {
        for (; i < n; i |= i + 1)
            t[i]++;
    }

    int get(int right) {
        int result = 0;
        for (; right; right &= right - 1)
            result += t[right - 1];
        return result;
    }
}

FenwickTree!1_000_000 fwt;

void main() {
    int n, k;
    while (read(&n, &k)) {
        version (LocalProject)
            fwt.init();
        long result = 1;
        int cur = 0;
        foreach (i; 0 .. n) {
            int next = cur + k;
            int count;
            if (next <= n)
                count = fwt.get(next) - fwt.get(cur);
            else {
                next -= n;
                count = i - fwt.get(cur) + fwt.get(next);
                result--;
            }
            result += (count << 1) + 1;
            fwt.inc(cur);
            cur = next;
            write(result, ' ');
        }
        writeln();
    }
}

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

immutable long MOD = 1_000_000_007;
alias tie = TypeTuple;
alias triplet = Tuple!(int, int, int);

void main(){
    int N, K;
    readVars(N, K);

    K = min(K, N - K);

    int s, t;

    auto a = new int[](N);
    auto ft = new FenwickTree!(int)(a);
    auto ans = new int[](N);
    int res = 1;

    foreach(i ; 0 .. N){
        t = (s + K) % N;

        if(s < t){
            res += ft.getSum(t) - ft.getSum(s + 1) + 1;
            ans[i] = res;
        } else {
            res += ft.getSum(N) - ft.getSum(s + 1);
            res += ft.getSum(t) + 1;
            ans[i] = res;
        }

        ft.add(s, 1);
        ft.add(t, 1);

        s = t;
    }

    writefln("%(%s %)", ans);
}

class FenwickTree(T){
private:
    T[] data;
    int N;

public:
    this(T[] a){
        data = [0] ~ a[];
        N = a.length.to!int;

        foreach (i ; 1 .. N + 1) {
            if (i + (i & (-i)) <= N) {
                data[i + (i & (-i))] += data[i];
            }
        }
    }

    void add(int i, T x) {
        i++;

        while (i <= N) {
            data[i] += x;
            i += i & (-i);
        }
    }

    T getSum(int r) {
        T res;

        while(r > 0){
            res += data[r];
            r -= r & (-r);
        }

        return res;
    }

    void print(){
        stderr.writefln("%(%s %)", data);
    }
}

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


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.

import std.stdio;

void main()
{
	int n, a, b;

	readf("%d %d %d", &n, &a, &b);

	int oddSeats = (a * b + 1) / 2;
	int evenSeats = a * b - oddSeats;

	int oddMembers = (n + 1) / 2;
	int evenMembers = n - oddMembers;

	if (oddMembers > oddSeats || evenMembers > evenSeats) {
		writef("-1\n");
	}
	else {
		int id = 1;
		int[][] result = new int[][](a, b);

		for (int i = 0; i < a; i++) {
			int from = 0;
			int delta = 1;
			if (i > 0 && result[i - 1][0] % 2 == id % 2) {
				from = b - 1;
				delta = -1;
			}
			for (int j = from; j != b && j != -1; j += delta) {
				if (id % 2 == 1 && oddMembers > 0) {
					result[i][j] = id;
					oddMembers--;
					id++;
				}
				else if (id % 2 == 0 && evenMembers > 0) {
					result[i][j] = id;
					evenMembers--;
					id++;
				}
			}
		}

		writef("%(%(%d %)\n%)\n", result);
	}
}

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

void main ()
{
	int n, a, b;
	while (readf (" %s %s %s", &n, &a, &b) > 0)
	{
		if (n <= a * b)
		{
			auto s = iota (1, n + 1).array;
			s.length = a * b;
			auto t = s.chunks (b).array;
			if (b % 2 == 0)
			{
				foreach (i, ref r; t)
				{
					if (i % 2 == 1)
					{
						reverse (r);
					}
				}
			}
			writefln ("%(%(%s %)\n%)", s.chunks (b));
		}
		else
		{
			writeln (-1);
		}
	}
}

import std.stdio;

void main()
{
	int n, a, b;

	readf("%d %d %d", &n, &a, &b);

	int oddSeats = (a * b + 1) / 2;
	int evenSeats = a * b - oddSeats;

	int oddMembers = (n + 1) / 2;
	int evenMembers = n - oddMembers;

	if (oddMembers > oddSeats || evenMembers > evenSeats) {
		writef("-1\n");
	}
	else {
		int id = 1;
		for (int i = 0; i < a; i++) {
			for (int j = 0; j < b; j++) {
				if (id % 2 == 1 && oddMembers > 0) {
					writef("%d", id);
					oddMembers--;
					id++;
				}
				else if (id % 2 == 0 && evenMembers > 0) {
					writef("%d", id);
					evenMembers--;
					id++;
				}
				else {
					writef("0");
				}

				if (j < b - 1)
					writef(" ");
				else
					writef("\n");
			}
		}
	}
}

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

void main ()
{
	int n, a, b;
	while (readf (" %s %s %s", &n, &a, &b) > 0)
	{
		if (n <= a * b)
		{
			auto s = iota (1, n + 1).array;
			s.length = a * b;
			writefln ("%(%(%s %)\n%)", s.chunks (b));
		}
		else
		{
			writeln (-1);
		}
	}
}