Vanya plays a game of balloons on the field of size n × n, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:**o****o**ooooo**o****o**oro***o*o*o***o***o*o*o***oFormally, the cross is given by three integers r, c and d, such that d ≤ r, c ≤ n - d + 1. The normal cross consists of balloons located in cells (x, y) (where x stay for the number of the row and y for the number of the column), such that |x - r|·|y - c| = 0 and |x - r| + |y - c| < d. Rotated cross consists of balloons located in cells (x, y), such that |x - r| = |y - c| and |x - r| < d.Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows and columns in the table with balloons. The each of the following n lines contains n characters '0', '1', '2' or '3' — the description of the values in balloons.

Print the maximum possible product modulo 109 + 7. Note, that you are not asked to maximize the remainder modulo 109 + 7, but to find the maximum value and print it this modulo.

NoteIn the first sample, the maximum product is achieved for a rotated cross with a center in the cell (3, 3) and radius 1: 2·2·3·3·3 = 108.

import std.stdio;

immutable int MOD = 1_000_000_007;
immutable int MAX_N = 1003;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = new byte [MAX_N * MAX_N];
		foreach (i; 0..n)
		{
			auto t = readln;
			foreach (j; 0..n)
			{
				a[(i + 1) * MAX_N + (j + 1)] =
				    cast (byte) (t[j] - '0');
			}
		}
		real resR = 0;
		long res = 0;
		foreach (i; 1..n + 1)
		{
			foreach (j; 1..n + 1)
			{
				void fun (int d1, int d2, int d3, int d4) ()
				{
					auto p1 = &a[i * MAX_N + j];
					auto p2 = &a[i * MAX_N + j];
					auto p3 = &a[i * MAX_N + j];
					auto p4 = &a[i * MAX_N + j];
					real curR = *p1;
					long cur = *p1;

					if (curR)
					{
						for (int step = 0; ; step++)
						{
							p1 += d1;
							p2 += d2;
							p3 += d3;
							p4 += d4;
							int m = *p1 * *p2 *
							    *p3 * *p4;
							if (!m)
							{
								break;
							}
							curR *= m;
							cur *= m;
							if (!(step & 3))
							{
								cur %= MOD;
							}
						}
					}
					if (resR < curR)
					{
						resR = curR;
						res = cur;
					}
				}

				fun !(-MAX_N - 1, -MAX_N + 1,
				    +MAX_N - 1, +MAX_N + 1) ();
				fun !(-MAX_N, -1, +1, +MAX_N) ();
			}
		}
		writeln (res % MOD);
	}
}

import std.stdio;
immutable int MOD = 10 ^^ 9 + 7, MAX_N = 1002;
void main () {
	int n;
	while (readf (" %s ", &n) > 0) {
		auto a = new byte [MAX_N * MAX_N];
		foreach (i; 1..n + 1) {
			auto t = readln;
			foreach (j; 1..n + 1) a[i * MAX_N + j] = cast (byte) (t[j - 1] - '0');
		}
		real resR = 0; long res = 0;
		void fun (int d1, int d2, int d3, int d4) (int i, int j) {
			auto p1 = &a[i * MAX_N + j], p2 = p1, p3 = p1, p4 = p1;
			real curR = *p1; long cur = *p1;
			if (curR) for (int step = 0; ; step++) {
				p1 += d1; p2 += d2; p3 += d3; p4 += d4;
				int m = *p1 * *p2 * *p3 * *p4;
				if (!m) break;
				curR *= m; cur *= m;
				if (!(step & 3)) cur %= MOD;
			}
			if (resR < curR) {resR = curR; res = cur;}
		}
		foreach (i; 1..n + 1)
			foreach (j; 1..n + 1) {
				fun !(-MAX_N - 1, -MAX_N + 1, +MAX_N - 1, +MAX_N + 1) (i, j);
				fun !(-MAX_N, -1, +1, +MAX_N) (i, j);
			}
		writeln (res % MOD);
	}
}

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

immutable int MOD = 1_000_000_007;
immutable int MAX_N = 1003;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = new byte [MAX_N * MAX_N];
		foreach (i; 0..n)
		{
			auto t = readln;
			foreach (j; 0..n)
			{
				a[(i + 1) * MAX_N + (j + 1)] =
				    cast (byte) (t[j] - '0');
			}
		}
		debug {writeln (a.chunks (MAX_N));}
		real resR = 0;
		long res = 0;
		foreach (i; 1..n + 1)
		{
			foreach (j; 1..n + 1)
			{
				void fun (int d1, int d2, int d3, int d4) ()
				{
					auto p1 = &a[i * MAX_N + j];
					auto p2 = &a[i * MAX_N + j];
					auto p3 = &a[i * MAX_N + j];
					auto p4 = &a[i * MAX_N + j];
					real curR = *p1;
					long cur = *p1;

					if (curR)
					{
						for (int step = 0; ; step++)
						{
							p1 += d1;
							p2 += d2;
							p3 += d3;
							p4 += d4;
							int m = *p1 * *p2 *
							    *p3 * *p4;
							if (!m)
							{
								break;
							}
							curR *= m;
							cur *= m;
							if (!(step & 3))
							{
								cur %= MOD;
							}
						}
					}
					if (resR < curR)
					{
						resR = curR;
						res = cur;
					}
				}

				fun !(-MAX_N - 1, -MAX_N + 1,
				    +MAX_N - 1, +MAX_N + 1) ();
				fun !(-MAX_N, -1, +1, +MAX_N) ();
			}
		}

		debug {writeln (resR);}
		writeln (res % MOD);
	}
}


This is an interactive problem.We hid from you a permutation $$$p$$$ of length $$$n$$$, consisting of the elements from $$$1$$$ to $$$n$$$. You want to guess it. To do that, you can give us 2 different indices $$$i$$$ and $$$j$$$, and we will reply with $$$p_{i} \bmod p_{j}$$$ (remainder of division $$$p_{i}$$$ by $$$p_{j}$$$).We have enough patience to answer at most $$$2 \cdot n$$$ queries, so you should fit in this constraint. Can you do it?As a reminder, a permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 10^4$$$) — length of the permutation.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] token;
T rd(T = long)() { while(!token.length) token = readln.chomp.split; string res = token[0]; token.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

int ask(ll x, ll y){
    writeln("? ", x, " ", y);
    stdout.flush();
    int res = rd!int;
    return res;
}

void play(){
    int n;
    n = rd!int;
    auto nums = rbt!(int);
    auto seen = rbt!(int);
    bool[int] vis;
    foreach(i; 1.. (n+1)){
        nums.insert(i);
        seen.insert(i);
        vis[i] = 0;
    }
    int[int] fin;
    int cur = 1;
    while(nums.length > 1){
        cur = nums.front;
        nums.removeKey(cur);
        int checknum = nums.front;
        int res = ask(cur, checknum);
        int res2 = ask(checknum, cur);
        if(res > res2){
            vis[cur] = 1;
            fin[cur] = res;
            seen.removeKey(res);
        }else{
            vis[checknum] = 1;
            fin[checknum] = res2;
            seen.removeKey(res2);
            nums.removeKey(checknum);
            nums.insert(cur);
        }
    }
    foreach(i; 1..n+1){
        if(!(i in fin)){
            fin[i] = seen.front;
        }
    }
    write("! ");
    foreach(i; 1..n+1){
        write(fin[i], " ");
    }
    writeln;
    stdout.flush;
}

int main(){
    ll t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}


Recently, the bear started studying data structures and faced the following problem.You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li, ri is the sum: , where S(li, ri) is a set of prime numbers from segment [li, ri] (both borders are included in the segment).Help the bear cope with the problem.

The first line contains integer n (1 ≤ n ≤ 106). The second line contains n integers x1, x2, ..., xn (2 ≤ xi ≤ 107). The numbers are not necessarily distinct. The third line contains integer m (1 ≤ m ≤ 50000). Each of the following m lines contains a pair of space-separated integers, li and ri (2 ≤ li ≤ ri ≤ 2·109) — the numbers that characterize the current query.

Print m integers — the answers to the queries on the order the queries appear in the input.

NoteConsider the first sample. Overall, the first sample has 3 queries.  The first query l = 2, r = 11 comes. You need to count f(2) + f(3) + f(5) + f(7) + f(11) = 2 + 1 + 4 + 2 + 0 = 9.  The second query comes l = 3, r = 12. You need to count f(3) + f(5) + f(7) + f(11) = 1 + 4 + 2 + 0 = 7.  The third query comes l = 4, r = 4. As this interval has no prime numbers, then the sum equals 0.

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

struct XD
{
    long[] res;
    int max;
    this(long[] res, int max)
    {
        this.res = res;
        this.max = max;
    }
};

struct Q
{
    int left;
    int right;
};

XD calc(int[] x)
{
    int m = 0;
    foreach (i; 0 .. x.length) if (x[i] > m) m = x[i];
    auto count = new int[m + 1];
    foreach (i; 0 .. x.length) ++ count[x[i]];
    auto notPrime = new bool[m + 1];
    auto res = new long[m + 1];
    foreach (i; 2 .. m + 1)
    {
        res[i] = res[i - 1];
        if (!notPrime[i])
        {
            long cnt = 0;
            for (int j = i; j <= m; j += i)
            {
                cnt += count[j];
                if (j > i) notPrime[j] = true;
            }
            res[i] += cnt;
        }
    }
    return XD(res, m);
}

void solve(int[] x, Q[] qs)
{
    XD xd = calc(x);
    foreach (i; 0 .. qs.length)
    {
        if (qs[i].left > xd.max)
        {
            writeln(0);
            continue;
        }
        if (qs[i].left > xd.max) qs[i].left = xd.max;
        if (qs[i].right > xd.max) qs[i].right = xd.max;
        writeln(xd.res[qs[i].right] - xd.res[qs[i].left - 1]);
    }
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
        //n = 1000000;
        auto x = new int[n];
        //Random gen;
        //foreach (i; 0 .. n) x[i] = uniform(2, 10000000, gen);
        foreach (i; 0 .. n) scanf("%d", &x[i]);
        //foreach (i; 0 .. n) writeln(x[i], " ");
        //writeln();
        scanf("%d", &m);
        //m = 50000;
        auto qs = new Q[m];
        foreach (i; 0 .. m) scanf("%d%d", &qs[i].left, &qs[i].right);
        //{
            //qs[i].left = uniform(2, 2000000000, gen);
            //qs[i].right = uniform(qs[i].left, 2000000000, gen);
            //write(qs[i].left, " ", qs[i].right);
        //}
        //writeln();
        solve(x, qs);
    }
}

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

struct XD
{
    long[] res;
    int max;
    this(long[] res, int max)
    {
        this.res = res;
        this.max = max;
    }
};

struct Q
{
    int left;
    int right;
};

XD calc(int[] x)
{
    int m = 0;
    foreach (i; 0 .. x.length) if (x[i] > m) m = x[i];
    auto count = new int[m + 1];
    foreach (i; 0 .. x.length) ++ count[x[i]];
    int[] primes;
    auto notPrime = new bool[m + 1];
    auto res = new long[2];
    foreach (i; 2 .. m + 1)
    {
        if (!notPrime[i])
        {
            primes ~= i;
            int cnt = 0;
            for (int j = i; j <= m; j += i)
            {
                cnt += count[j];
                if (j > i) notPrime[j] = true;
            }
            res ~= res[$ - 1] + cnt;
        }
        else
        {
            res ~= res[$ - 1];
        }
    }
    return XD(res, m);
}

void solve(int[] x, Q[] qs)
{
    XD xd = calc(x);
    foreach (i; 0 .. qs.length)
    {
        if (qs[i].left > xd.max) qs[i].left = xd.max;
        if (qs[i].right > xd.max) qs[i].right = xd.max;
        writeln(xd.res[qs[i].right] - xd.res[qs[i].left - 1]);
    }
}

void main(string[] args)
{
    int n, m;
    while (scanf("%d", &n) == 1)
    {
        //n = 1000000;
        auto x = new int[n];
        //Random gen;
        //foreach (i; 0 .. n) x[i] = uniform(2, 10000000, gen);
        foreach (i; 0 .. n) scanf("%d", &x[i]);
        //foreach (i; 0 .. n) writeln(x[i], " ");
        //writeln();
        scanf("%d", &m);
        //m = 50000;
        auto qs = new Q[m];
        foreach (i; 0 .. m) scanf("%d%d", &qs[i].left, &qs[i].right);
        //{
            //qs[i].left = uniform(2, 2000000000, gen);
            //qs[i].right = uniform(qs[i].left, 2000000000, gen);
            //write(qs[i].left, " ", qs[i].right);
        //}
        //writeln();
        solve(x, qs);
    }
}


We guessed a permutation $$$p$$$ consisting of $$$n$$$ integers. The permutation of length $$$n$$$ is the array of length $$$n$$$ where each element from $$$1$$$ to $$$n$$$ appears exactly once. This permutation is a secret for you.For each position $$$r$$$ from $$$2$$$ to $$$n$$$ we chose some other index $$$l$$$ ($$$l < r$$$) and gave you the segment $$$p_l, p_{l + 1}, \dots, p_r$$$ in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $$$n-1$$$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.For example, if the secret permutation is $$$p=[3, 1, 4, 6, 2, 5]$$$ then the possible given set of segments can be:  $$$[2, 5, 6]$$$  $$$[4, 6]$$$  $$$[1, 3, 4]$$$  $$$[1, 3]$$$  $$$[1, 2, 4, 6]$$$ Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the length of the permutation. The next $$$n-1$$$ lines describe given segments. The $$$i$$$-th line contains the description of the $$$i$$$-th segment. The line starts with the integer $$$k_i$$$ ($$$2 \le k_i \le n$$$) — the length of the $$$i$$$-th segment. Then $$$k_i$$$ integers follow. All integers in a line are distinct, sorted in ascending order, between $$$1$$$ and $$$n$$$, inclusive. It is guaranteed that the required $$$p$$$ exists for each test case. It is also guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$200$$$ ($$$\sum n \le 200$$$).

For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input).

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

void main ()
{
	readln;
	int n;
multitest_loop:
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = new int [] [n - 1];
		auto d0 = new int [n];
		auto hasElement = new bool [] [] (n - 1, n);
		foreach (i, ref q; p)
		{
			q = readln.splitter.drop (1).map !(to !(int)).array;
			q[] -= 1;
			foreach (ref v; q)
			{
				d0[v] += 1;
				hasElement[i][v] = true;
			}
		}

		int [] solve (int v, int first)
		{
			auto d = d0.dup;
			auto pos = new int [n - 1];
			pos[] = 1;
			auto res = new int [n];
			auto total = n.iota.sum;
			foreach_reverse (i; 2..n)
			{
				res[i] = v;
				debug {writeln ("i = ", i, ", v = ", v);}
				int j = 0;
				while (pos[j] != 1 || !hasElement[j][v])
				{
					j += 1;
				}
				pos[j] = i;

				v = int.max;
				foreach (const ref u; p[j])
				{
					d[u] -= 1;
					if (d[u] == 1 && u != first)
					{
						v = u;
					}
				}
				if (v == int.max)
				{
					return null;
				}
			}
			res[1] = total - res.sum - first;
			res[0] = first;
			debug {writeln ("pos = ", pos);}
			debug {writeln ("res = ", res);}

			foreach (j, i; pos)
			{
				auto len = p[j].length;
				debug {writeln (res[i - len + 1..i + 1]);}
				foreach (k; i - len + 1..i + 1)
				{
					if (!hasElement[j][res[k]])
					{
						return null;
					}
				}
			}
			return res;
		}

		foreach (first; 0..n)
		{
			foreach (v; 0..n)
			{
				if (v != first && d0[v] == 1)
				{
					auto answer = solve (v, first);
					if (answer !is null)
					{
						answer[] += 1;
						writefln !("%(%s %)") (answer);
						continue multitest_loop;
					}
				}
			}
		}
		assert (false);
	}
}


Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:You have an array $$$a$$$ consisting of $$$n$$$ positive integers. An operation consists of choosing an element and either adding $$$1$$$ to it or subtracting $$$1$$$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $$$1$$$. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!

The first line contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)  — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^{12}$$$)  — the elements of the array.

Print a single integer  — the minimum number of operations required to make the array good.

NoteIn the first example, the first array is already good, since the greatest common divisor of all the elements is $$$2$$$.In the second example, we may apply the following operations:  Add $$$1$$$ to the second element, making it equal to $$$9$$$.  Subtract $$$1$$$ from the third element, making it equal to $$$6$$$.  Add $$$1$$$ to the fifth element, making it equal to $$$2$$$.  Add $$$1$$$ to the fifth element again, making it equal to $$$3$$$. The greatest common divisor of all elements will then be equal to $$$3$$$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
import std.functional;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[N] factorize(Z n)
{
  N[N] res;
  for(N d = 2; d * d <= n; d++)
    while (n % d == 0)
      res[d]++, n /= d;
  if (n != 1)
    res[n]++;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;
  N minOps(N m)
  {
    if (m == 0)
      return N.max;
    N minOpsPrime(N p)
    {
      N ops = 0;
      foreach(e; a)
	ops += min((e > pmod(e, p))? pmod(e, p) : N.max, pmod(-e, p));
      return ops;
    }
    auto factorization = m.factorize;
    N ops = n;
    foreach(prime, order; factorization)
	ops = min(ops, memoize!minOpsPrime(prime));
    return ops;
  }
  foreach(e; a[0 .. min(18, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 1])
      minops = min(minops, memoize!minOps(t));
  ans(minops);
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
import std.functional;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    while (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[] factorize(Z n)
{
  N[] res;
  for(N d = 2; d * d <= n; d++)
    if (n % d == 0)
      {
	res ~= d;
	n /= d;
	while (n % d == 0)
	  n /= d;
      }
  if (n != 1)
    res ~= n;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minOpsPrime(N p)
  {
    return a.map!(e => min((e > pmod(e, p))? pmod(e, p) : N.max, pmod(-e, p))).sum;
  }
  N minOps(N m)
  {
    return m == 0? N.max : m.factorize.map!(memoize!minOpsPrime).fold!min(N.max);
  }
  ans(a[0..min(18, cast(size_t)(n))]
      .map!(e => [e - 1, e, e + 1]
	    .map!(memoize!minOps)
	    .fold!min(N.max))
      .fold!min(N.max));
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
import std.functional;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[] factorize(Z n)
{
  N[] res;
  for(N d = 2; d * d <= n; d++)
    if(n % d == 0)
      {
	res ~= d;
	while (n % d == 0)
	  n /= d;
      }
  if (n != 1)
    res ~= n;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;
  N minOps(N m)
  {
    if (m == 0)
      return N.max;
    N minOpsPrime(N p)
    {
      N ops = 0;
      foreach(e; a)
	ops += min((e > pmod(e, p))? pmod(e, p) : N.max, pmod(-e, p));
      return ops;
    }
    auto factorization = m.factorize;
    N ops = n;
    foreach(prime; factorization)
	ops = min(ops, memoize!minOpsPrime(prime));
    return ops;
  }
  foreach(e; a[0 .. min(18, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 1])
      minops = min(minops, memoize!minOps(t));
  ans(minops);
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
import std.functional;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[] factorize(Z n)
{
  N[] res;
  for(N d = 2; d * d <= n; d++)
    if (n % d == 0)
      {
	res ~= d;
	n /= d;
	while (n % d == 0)
	  n /= d;
      }
  if (n != 1)
    res ~= n;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;

  N minOpsElem(N e, N p)
  {
    return min((e > pmod(e, p))? pmod(e, p) : N.max, pmod(-e, p));
  }
  N minOpsPrime(N p)
  {
    return a.map!(e => minOpsElem(e, p)).sum;
  }
  N minOps(N m)
  {
    return m == 0? N.max : m.factorize.map!(memoize!minOpsPrime).fold!min(N.max);
  }
  foreach(e; a[0 .. min(18, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 1])
      minops = min(minops, memoize!minOps(t));
  ans(minops);
}

import std.algorithm, std.conv, std.random, std.range, std.stdio, std.string, std.typecons;
void main () {
	auto n = readln.strip.to !(int), a = readln.splitter.map !(to !(long)).array;
	int [long] d;
	foreach (s; 0..30) {
		auto y = a[uniform (0, n)];
		foreach (z; [y - 1, y, y + 1]) {
			for (long c = 2; c * c <= z; c++) if (z % c == 0) {
				d[c] = 1;
				while (z % c == 0) z /= c;
			}
			if (z > 1) d[z] = 1;
		}
	}
	long r = n;
	foreach (k; d.byKey) r = min (r, a.map !(z => z < k ? k - z : min (z % k, k - z % k)).sum);
	r.writeln;
}

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

immutable int limit = 10 ^^ 6;
immutable int steps = 10 ^^ 3;
immutable int divs  = 10 ^^ 3 * 2;
immutable int first = 10 ^^ 2 * 2;

int [] p;

void prepare ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	p = [];
	p.reserve (limit / 12);
	for (int v = 2; v < limit; v++)
	{
		if (s[v])
		{
			p ~= v;
			if (v * 1L * v < limit)
			{
				for (int u = v * v; u < limit; u += v)
				{
					s[u] = false;
				}
			}
		}
	}
}

void main ()
{
	rndGen.seed (236426);
	prepare ();

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		sort (a);
		bool [long] d;
		foreach (x; p[0..first])
		{
			d[x] = true;
		}
		for (int step = 0; step < steps && d.length < divs; step++)
		{
			auto z0 = a[uniform (0, n)];
			foreach (z; [z0 - 1, z0, z0 + 1])
			{
				foreach (const c; p)
				{
					if (c * 1L * c > z)
					{
						break;
					}
					if (z % c == 0)
					{
						d[c] = true;
						do
						{
							z /= c;
						}
						while (z % c == 0);
					}
				}
				if (z > 1)
				{
					d[z] = true;
				}
			}
		}

		long res = n;
		auto e = d.byKey.array;
		sort (e);
		debug {writeln (e);}
		foreach (const k; e)
		{
			long cur = 0;
			foreach (const z; a)
			{
				if (z < k)
				{
					cur += k - z;
				}
				else
				{
					long rem = z % k;
					cur += min (rem, k - rem);
				}
				if (cur >= res)
				{
					break;
				}
			}
			debug {writeln (k, ": ", cur);}
			res = min (res, cur);
		}
		writeln (res);
	}
}

// Code By H~$~C

module main;

import core.stdc.stdio, core.stdc.stdlib, core.stdc.string;
import std.stdio, std.array, std.string, std.math;
import std.algorithm, std.range, std.random;
import std.conv, std.typecons;
alias to!(string) to_string;
alias to!(int) to_int;
alias to!(long) to_long;
alias to!(double) to_double;
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;

int n;
long[] arr;

void main() {
  n = readln.strip.to_int;
  arr = randomShuffle(readln.splitter.map!(to_long).array, rndGen);
  int[long] mp;
  foreach(i; 0 .. min(30, to_int(arr.length))) {
    foreach(x; [arr[i] - 1, arr[i], arr[i] + 1]) {
      for(long p = 2; p * p <= x; p++) {
        if (x % p == 0) {
          mp[p] = 1;
          while (x % p == 0) x /= p;
        }
      }
      if (x > 1) mp[x] = 1;
    }
  }
  long ans = n;
  foreach(k; mp.byKey) {
    ans = min(ans, arr.map!(x => x < k ? k - x : min(x % k, k - x % k)).sum);
  }
  ans.writeln;
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[N] factorize(Z n)
{
  N[N] res;
  for(N d = 2; d * d <= n; d++)
    while (n % d == 0)
      res[d]++, n /= d;
  if (n != 1)
    res[n]++;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;
  N minOps(N m)
  {
    if (m == 0)
      return N.max;
    N minOpsPrime(N p)
    {
      bool shallPrint = p == 3;
      N ops = 0;
      foreach(e; a)
	  ops += min(pmod(e, p) > e? pmod(e, p) : N.max, pmod(-e, p));
      return ops;
    }
    auto factorization = m.factorize;
    N ops = n;
    foreach(prime, order; factorization)
	ops = min(ops, minOpsPrime(prime));
    return ops;
  }
  foreach(e; a[0 .. min(40, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 2])
      minops = min(minops, minOps(e));
  ans(minops);
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[N] factorize(Z n)
{
  N[N] res;
  for(N d = 2; d * d <= n; d++)
    while (n % d == 0)
      res[d]++, n /= d;
  if (n != 1)
    res[n]++;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;
  N minOps(N m)
  {
    if (m == 0)
      return N.max;
    N minOpsPrime(N p)
    {
      bool shallPrint = p == 3;
      N ops = 0;
      foreach(e; a)
	  ops += min(pmod(e, p) > e? pmod(e, p) : N.max, pmod(-e, p));
      return ops;
    }
    auto factorization = m.factorize;
    N ops = n;
    foreach(prime, order; factorization)
	ops = min(ops, minOpsPrime(prime));
    return ops;
  }
  foreach(e; a[0 .. min(40, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 1])
      minops = min(minops, minOps(e));
  ans(minops);
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[N] factorize(Z n)
{
  N[N] res;
  for(N d = 2; d * d <= n; d++)
    while (n % d == 0)
      res[d]++, n /= d;
  if (n != 1)
    res[n]++;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;
  N minOps(N m)
  {
    if (m == 0)
      return N.max;
    N minOpsPrime(N p)
    {
      bool shallPrint = p == 3;
      N ops = 0;
      foreach(e; a)
	  ops += min(pmod(e, p) > e? pmod(e, p) : N.max, pmod(-e, p));
      return ops;
    }
    auto factorization = m.factorize;
    N ops = n;
    foreach(prime, order; factorization)
	ops = min(ops, minOpsPrime(prime));
    return ops;
  }
  foreach(e; a[0 .. min(40, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 1])
      minops = min(minops, minOps(t));
  ans(minops);
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
import std.random;
import std.functional;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}

alias Z = long;
alias N = long;

N[] factorize(Z n)
{
  N[] res;
  for(N d = 2; d * d <= n; d++)
    if (n % d)
      {
	res ~= d;
	n /= d;
	while (n % d == 0)
	  n /= d;
      }
  if (n != 1)
    res ~= n;
  return res;
}

N pmod(N x, N m)
{
  return (x%m+m)%m;
}

void main()
{
  N n; get(n);
  auto a = new N[cast(size_t)(n)]; get(a);
  a = a.randomShuffle;
  N minops = n;

  N minOpsElem(N e, N p)
  {
    return min((e > pmod(e, p))? pmod(e, p) : N.max, pmod(-e, p));
  }
  N minOpsPrime(N p)
  {
    return a.map!(e => minOpsElem(e, p)).sum;
  }
  N minOps(N m)
  {
    return m == 0? N.max : m.factorize.map!(memoize!minOpsPrime).fold!min(N.max);
  }
  foreach(e; a[0 .. min(18, cast(size_t)(n))])
    foreach(t; [e - 1, e, e + 1])
      minops = min(minops, memoize!minOps(t));
  ans(minops);
}

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

immutable int limit = 10 ^^ 6;
immutable int steps = 10 ^^ 3 * 2;
immutable int divs  = 10 ^^ 3 * 4;
immutable int first = 10 ^^ 2 * 4;

int [] p;

void prepare ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	p = [];
	p.reserve (limit / 12);
	for (int v = 2; v < limit; v++)
	{
		if (s[v])
		{
			p ~= v;
			if (v * 1L * v < limit)
			{
				for (int u = v * v; u < limit; u += v)
				{
					s[u] = false;
				}
			}
		}
	}
}

void main ()
{
	rndGen.seed (236426);
	prepare ();

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		randomShuffle (a);
//		sort (a);
		bool [long] d;
		foreach (x; p[0..first])
		{
			d[x] = true;
		}
		for (int step = 0; step < steps && d.length < divs; step++)
		{
			auto z = a[uniform (0, n)];
			foreach (const c; p)
			{
				if (c * 1L * c > z)
				{
					break;
				}
				if (z % c == 0)
				{
					d[c] = true;
					do
					{
						z /= c;
					}
					while (z % c == 0);
				}
			}
			if (z > 1)
			{
				d[z] = true;
			}
		}

		long res = n;
		auto e = d.byKey.array;
		sort (e);
		debug {writeln (e);}
		foreach (const k; e)
		{
			long cur = 0;
			foreach (const z; a)
			{
				if (z < k)
				{
					cur += k - z;
				}
				else
				{
					long rem = z % k;
					cur += min (rem, k - rem);
				}
				if (cur >= res)
				{
					break;
				}
			}
			debug {writeln (k, ": ", cur);}
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

immutable int limit = 10 ^^ 6;
immutable int steps = 10 ^^ 3;
immutable int divs  = 10 ^^ 3 * 2;
immutable int first = 10 ^^ 2 * 2;

int [] p;

void prepare ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	p = [];
	p.reserve (limit / 12);
	for (int v = 2; v < limit; v++)
	{
		if (s[v])
		{
			p ~= v;
			if (v * 1L * v < limit)
			{
				for (int u = v * v; u < limit; u += v)
				{
					s[u] = false;
				}
			}
		}
	}
}

void main ()
{
	rndGen.seed (236426);
	prepare ();

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		sort (a);
		bool [long] d;
		foreach (x; p[0..first])
		{
			d[x] = true;
		}
		for (int step = 0; step < steps && d.length < divs; step++)
		{
			auto z = a[uniform (0, n)];
			foreach (const c; p)
			{
				if (c * 1L * c > z)
				{
					break;
				}
				if (z % c == 0)
				{
					d[c] = true;
					do
					{
						z /= c;
					}
					while (z % c == 0);
				}
			}
			if (z > 1)
			{
				d[z] = true;
			}
		}

		long res = n;
		auto e = d.byKey.array;
		sort (e);
		debug {writeln (e);}
		foreach (const k; e)
		{
			long cur = 0;
			foreach (const z; a)
			{
				if (z < k)
				{
					cur += k - z;
				}
				else
				{
					long rem = z % k;
					cur += min (rem, k - rem);
				}
				if (cur >= res)
				{
					break;
				}
			}
			debug {writeln (k, ": ", cur);}
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

immutable int limit = 10 ^^ 6;
immutable int steps = 10 ^^ 3 * 2;
immutable int divs  = 10 ^^ 3 * 6;
immutable int first = 10 ^^ 2 * 9;

int [] p;

void prepare ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	p = [];
	p.reserve (limit / 12);
	for (int v = 2; v < limit; v++)
	{
		if (s[v])
		{
			p ~= v;
			if (v * 1L * v < limit)
			{
				for (int u = v * v; u < limit; u += v)
				{
					s[u] = false;
				}
			}
		}
	}
}

void main ()
{
	rndGen.seed (236426);
	prepare ();

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
//		randomShuffle (a);
		sort (a);
		bool [long] d;
		foreach (x; p[0..first])
		{
			d[x] = true;
		}
		for (int step = 0; step < steps && d.length < divs; step++)
		{
			auto z = a[uniform (0, n)];
			foreach (const c; p)
			{
				if (c * 1L * c > z)
				{
					break;
				}
				if (z % c == 0)
				{
					d[c] = true;
					do
					{
						z /= c;
					}
					while (z % c == 0);
				}
			}
			if (z > 1)
			{
				d[z] = true;
			}
		}

		long res = n;
		auto e = d.byKey.array;
		sort (e);
		debug {writeln (e);}
		foreach (const k; e)
		{
			long cur = 0;
			foreach (const z; a)
			{
				if (z < k)
				{
					cur += k - z;
				}
				else
				{
					long rem = z % k;
					cur += min (rem, k - rem);
				}
				if (cur >= res)
				{
					break;
				}
			}
			debug {writeln (k, ": ", cur);}
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

immutable int limit = 10 ^^ 6;
immutable int steps = 10 ^^ 3 * 2;
immutable int divs  = 10 ^^ 3 * 5;
immutable int first = 10 ^^ 2 * 8;

int [] p;

void prepare ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	p = [];
	p.reserve (limit / 12);
	for (int v = 2; v < limit; v++)
	{
		if (s[v])
		{
			p ~= v;
			if (v * 1L * v < limit)
			{
				for (int u = v * v; u < limit; u += v)
				{
					s[u] = false;
				}
			}
		}
	}
}

void main ()
{
	rndGen.seed (1236426);
	prepare ();

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
//		randomShuffle (a);
		sort (a);
		bool [long] d;
		foreach (x; p[0..first])
		{
			d[x] = true;
		}
		for (int step = 0; step < steps && d.length < divs; step++)
		{
			auto z = a[uniform (0, n)];
			foreach (const c; p)
			{
				if (c * 1L * c > z)
				{
					break;
				}
				if (z % c == 0)
				{
					d[c] = true;
					do
					{
						z /= c;
					}
					while (z % c == 0);
				}
			}
			if (z > 1)
			{
				d[z] = true;
			}
		}

		long res = n;
		auto e = d.byKey.array;
		sort (e);
		debug {writeln (e);}
		foreach (const k; e)
		{
			long cur = 0;
			foreach (const z; a)
			{
				if (z < k)
				{
					cur += k - z;
				}
				else
				{
					long rem = z % k;
					cur += min (rem, k - rem);
				}
				if (cur >= res)
				{
					break;
				}
			}
			debug {writeln (k, ": ", cur);}
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

immutable int limit = 10 ^^ 6;
immutable int steps = 10 ^^ 3 * 2;
immutable int divs  = 10 ^^ 3 * 4;
immutable int first = 10 ^^ 2 * 4;

int [] p;

void prepare ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	p = [];
	p.reserve (limit / 12);
	for (int v = 2; v < limit; v++)
	{
		if (s[v])
		{
			p ~= v;
			if (v * 1L * v < limit)
			{
				for (int u = v * v; u < limit; u += v)
				{
					s[u] = false;
				}
			}
		}
	}
}

void main ()
{
	rndGen.seed (236426);
	prepare ();

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		sort (a);
		bool [long] d;
		foreach (x; p[0..first])
		{
			d[x] = true;
		}
		for (int step = 0; step < steps && d.length < divs; step++)
		{
			auto z = a[uniform (0, n)];
			foreach (const c; p)
			{
				if (c * 1L * c > z)
				{
					break;
				}
				if (z % c == 0)
				{
					d[c] = true;
					do
					{
						z /= c;
					}
					while (z % c == 0);
				}
			}
			if (z > 1)
			{
				d[z] = true;
			}
		}

		long res = n;
		auto e = d.byKey.array;
		sort (e);
		debug {writeln (e);}
		foreach (const k; e)
		{
			long cur = 0;
			foreach (const z; a)
			{
				if (z < k)
				{
					cur += k - z;
				}
				else
				{
					long rem = z % k;
					cur += min (rem, k - rem);
				}
				if (cur >= res)
				{
					break;
				}
			}
			debug {writeln (k, ": ", cur);}
			res = min (res, cur);
		}
		writeln (res);
	}
}


Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y.  Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.

The first line contains integers n, m and w (1  ≤  n  ≤  1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.

Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.

NoteIn the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.

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

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

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

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

    auto grpid = n.iota.array;

    foreach (_; 0 .. m) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;
        --a, --b;

        int old = grpid[b];
        foreach (ref e; grpid) if (e == old) e = grpid[a];
    }

    auto vis = (false).repeat(n).array;
    auto idsForGrp = new int[][] (grpid.dup.sort.uniq.array.length);

    debug { grpid.writeln; }

    Tuple!(int, int)[] grpsVals;
    foreach (i, e; grpid) {
        if (vis[i]) continue;

        int wsm = 0, bsm = 0;
        foreach (j, f; grpid) {
            if (e != f) continue;

            idsForGrp[grpsVals.length] ~= j.to!int;
            vis[j] = true;
            wsm += ws[j];
            bsm += bs[j];
        }

        grpsVals ~= tuple(wsm, bsm);
    }

    debug { grpsVals.writeln; }
    debug { idsForGrp.writeln; }

    auto dp = new int[][] (grpsVals.length, w+1);
    foreach (i, t; grpsVals) {
        int grw = t[0], grb = t[1];

        if (i > 0) dp[i][] = dp[i-1][];

        for (int cw = w; cw - grw >= 0; --cw) {
            int prevVal = i > 0 ? dp[i-1][cw - grw] : 0;
            dp[i][cw] = max(dp[i][cw], prevVal + grb);
        }

        foreach (e; idsForGrp[i]) {
            for (int cw = w; cw - ws[e] >= 0; --cw) {
                int prevVal = i > 0 ? dp[i-1][cw - ws[e]] : 0;
                dp[i][cw] = max(dp[i][cw], prevVal + bs[e]);
            }
        }
    }

    debug { dp.writeln; }

    int ans = dp[$-1].maxElement;

    ans.writeln;
}

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, m, tw;
	while (readf (" %s %s %s", &n, &m, &tw) > 0)
	{
		readln;
		auto w = readln.split.map !(to !(int)).array;
		auto b = readln.split.map !(to !(int)).array;
		auto a = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto d = new bool [n];
		int [] component;

		void recur (int v)
		{
			if (d[v])
			{
				return;
			}
			d[v] = true;
			component ~= v;
			foreach (u; a[v])
			{
				recur (u);
			}
		}

		int [] [] c;

		foreach (u; 0..n)
		{
			if (!d[u])
			{
				component.length = 0;
				component.assumeSafeAppend ();
				recur (u);
				c ~= component.dup;
			}
		}
		debug {writeln (c);}

		int [] [2] f;
		foreach (ref g; f)
		{
			g = new int [tw + 1];
		}
		int e = 0;
		f[e][] = 0;
		foreach (cur; c)
		{
			e ^= 1;
			f[e][] = f[!e][];
			int sw = 0;
			int sb = 0;

			foreach (k; cur)
			{
				foreach (i; w[k]..tw + 1)
				{
					f[e][i] = max (f[e][i],
					    f[!e][i - w[k]] + b[k]);
				}
				sw += w[k];
				sb += b[k];
			}

			foreach (i; sw..tw + 1)
			{
				f[e][i] = max (f[e][i],
				    f[!e][i - sw] + sb);
			}
		}

		writeln (f[e][].reduce !(max));
	}
}

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

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

struct Dsu(size_t n) {
    int[n] p;

    int get(int x) {
        return x == p[x]? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        p[get(x)] = get(y);
    }
}

alias Girl = Tuple!(int, `weight`, int, `beauty`);

struct Group {
    int id;
    Girl[ ] girls;
    Girl sum;
    Group* next;
}

int n;
Girl[1000] _girls;
Girl[ ] girls;
Dsu!1000 dsu;
Group[1000] groups;
int[1001][1000] dp;

int dyn(int gid, int wcap) {
    assert(gid < n);
    assert(wcap >= 0);
    if (~dp[gid][wcap])
        return dp[gid][wcap];
    const grp = &groups[gid];
    assert(!grp.girls.empty);
    int result = 0;
    if (grp.next is null) {
        if (wcap >= grp.sum.weight)
            result = grp.sum.beauty;
        else
            foreach (g; grp.girls)
                if (wcap >= g.weight)
                    result = max(result, g.beauty);
    } else {
        assert(grp.next == &groups[grp.next.id]);
        result = dyn(grp.next.id, wcap);
        if (wcap >= grp.sum.weight)
            result = max(result, dyn(grp.next.id, wcap - grp.sum.weight) + grp.sum.beauty);
        foreach (g; grp.girls)
            if (wcap >= g.weight)
                result = max(result, dyn(grp.next.id, wcap - g.weight) + g.beauty);
    }
    return (dp[gid][wcap] = result);
}

void main() {
    int m, wl;
    while (read(&n, &m, &wl)) {
        girls = _girls[0 .. n];
        foreach (int i, ref grp; groups) {
            grp.id = i;
            grp.girls = null;
            grp.sum = Girl(0, 0);
        }
        iota(0, n).copy(dsu.p[ ]);
        foreach (ref g; girls)
            read(&g.weight);
        foreach (ref g; girls)
            read(&g.beauty);
        while (m--) {
            int a, b;
            read(&a, &b);
            a--;
            b--;
            dsu.merge(a, b);
        }
        foreach (int i, g; girls) {
            auto grp = &groups[dsu.get(i)];
            grp.girls ~= g;
            grp.sum.weight += g.weight;
            grp.sum.beauty += g.beauty;
        }
        Group* last = null, first = null;
        foreach (ref grp; groups[0 .. n].filter!`!a.girls.empty`) {
            if (first is null)
                first = &grp;
            else
                last.next = &grp;
            last = &grp;
        }
        assert(last !is null);
        last.next = null;
        memset(dp.ptr, 0xFF, dp.sizeof);
        writeln(dyn(first.id, wl));
    }
}

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

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

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

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

    auto grpid = n.iota.array;

    foreach (_; 0 .. m) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;
        --a, --b;

        foreach (ref e; grpid) if (e == grpid[b]) e = grpid[a];
    }

    auto vis = (false).repeat(n).array;
    auto idsForGrp = new int[][] (grpid.dup.sort.uniq.array.length);

    debug { grpid.writeln; }

    Tuple!(int, int)[] grpsVals;
    foreach (i, e; grpid) {
        if (vis[i]) continue;

        int wsm = 0, bsm = 0;
        foreach (j, f; grpid) {
            if (e != f) continue;

            idsForGrp[grpsVals.length] ~= j.to!int;
            vis[j] = true;
            wsm += ws[j];
            bsm += bs[j];
        }

        grpsVals ~= tuple(wsm, bsm);
    }

    debug { grpsVals.writeln; }
    debug { idsForGrp.writeln; }

    auto dp = new int[][] (grpsVals.length, w+1);
    foreach (i, t; grpsVals) {
        int grw = t[0], grb = t[1];

        if (i > 0) dp[i][] = dp[i-1][];

        for (int cw = w; cw - grw >= 0; --cw) {
            int prevVal = i > 0 ? dp[i-1][cw - grw] : 0;
            dp[i][cw] = max(dp[i][cw], prevVal + grb);
        }

        foreach (e; idsForGrp[i]) {
            for (int cw = w; cw - ws[e] >= 0; --cw) {
                int prevVal = i > 0 ? dp[i-1][cw - ws[e]] : 0;
                dp[i][cw] = max(dp[i][cw], prevVal + bs[e]);
            }
        }
    }

    debug { dp.writeln; }

    int ans = dp[$-1].maxElement;

    ans.writeln;
}

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

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

struct Dsu(size_t n) {
    int[n] p;

    int get(int x) {
        return x == p[x]? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        p[get(x)] = get(y);
    }
}

alias Girl = Tuple!(int, `weight`, int, `beauty`);

struct Group {
    int id;
    Girl[ ] girls;
    Girl sum;
    Group* next;
}

int n, m, wl;
Girl[1000] _girls;
Girl[ ] girls;
Dsu!1000 dsu;
Group[1000] groups;
int[1001][1000] dp;

int dyn(int gid, int curWeight) {
    assert(gid < n);
    if (~dp[gid][curWeight])
        return dp[gid][curWeight];
    const grp = &groups[gid];
    assert (!grp.girls.empty);
    if (grp.next is null) {
        if (curWeight + grp.sum.weight <= wl)
            return (dp[gid][curWeight] = grp.sum.beauty);
        int b = 0;
        foreach (g; grp.girls)
            if (curWeight + g.weight <= wl)
                b = max(b, g.beauty);
        return (dp[gid][curWeight] = b);
    } else {
        int result = 0;
        if (curWeight + grp.sum.weight <= wl)
            result = dyn(grp.next.id, curWeight + grp.sum.weight) + grp.sum.beauty;
        foreach (g; grp.girls)
            if (curWeight + g.weight <= wl)
                result = max(result, dyn(grp.next.id, curWeight + g.weight) + g.beauty);
        return (dp[gid][curWeight] = result);
    }
}

void main() {
    while (read(&n, &m, &wl)) {
        girls = _girls[0 .. n];
        foreach (int i, ref grp; groups) {
            grp.id = i;
            grp.girls = null;
            grp.sum = Girl(0, 0);
        }
        iota(0, n).copy(dsu.p[ ]);
        foreach (ref g; girls)
            read(&g.weight);
        foreach (ref g; girls)
            read(&g.beauty);
        while (m--) {
            int a, b;
            read(&a, &b);
            a--;
            b--;
            dsu.merge(a, b);
        }
        foreach (int i, g; girls) {
            auto grp = &groups[dsu.get(i)];
            grp.girls ~= g;
            grp.sum.weight += g.weight;
            grp.sum.beauty += g.beauty;
        }
        Group* last = null, first = null;
        foreach (ref grp; groups[0 .. n].filter!`!a.girls.empty`) {
            if (last is null)
                first = &grp;
            else
                last.next = &grp;
            last = &grp;
        }
        assert(last !is null);
        last.next = null;
        memset(dp.ptr, 0xFF, dp.sizeof);
        writeln(dyn(first.id, 0));
    }
}


Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):  Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.

The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.

Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.

NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled:   In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher:   In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:

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

void main ()
{
	string s;
	while ((s = readln ()).length > 0)
	{
		s = '<' ~ s.strip () ~ '>';
		int n = s.length;
		auto id = iota (n).array;
		auto next = id.dup;
		next[] += 1;
		auto prev = id.dup;
		prev[] -= 1;
		int i = 1;
		while (next[i] < n)
		{
			debug {writeln (i, ' ', next[i]);}
			if (s[i] == s[next[i]])
			{
				debug {writeln (s[i], ' ', s[next[i]]);}
				prev[next[i]] = prev[i];
				next[prev[i]] = next[i];
				i = next[i];
				prev[next[i]] = prev[i];
				next[prev[i]] = next[i];
				i = prev[i];
			}
			else
			{
				i = next[i];
			}
		}
		writeln ((i == n - 1 && prev[i] == 0) ? "Yes" : "No");
	}
}


There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows:   $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains four integers $$$n, m, k$$$ and $$$q$$$ ($$$1 \le n, m, k, q \le 2 \cdot 10^5$$$) — the size of the sheet, the number of non-white colors and the number of operations. The $$$i$$$-th of the following $$$q$$$ lines contains a description of the $$$i$$$-th operation — two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n$$$; $$$1 \le y_i \le m$$$) — the row and the column the operation is applied to. The sum of $$$q$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the number of different colorings modulo $$$998\,244\,353$$$.

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

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

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}

alias MInt = ModInt!998244353L;

void solve() {
    int N, M, K, Q; readf("%d %d %d %d\n", &N, &M,&K, &Q);
    auto Y = new int[Q], X = new int[Q];
    foreach (i; 0 .. Q) {
        readf("%d %d\n", &Y[i], &X[i]);
    }
    bool[int] usedY, usedX;
    int nY, nX;
    MInt ans = 1;
    for (int i = Q - 1; i >= 0; i--) {
        int y = Y[i], x = X[i];
        if ( (y in usedY && x in usedX) || nY == N || nX == M ) continue;
        //if ( (y in usedY || nY == N) && (x in usedX || nX == M) ) continue;
        ans *= K;
        if (y !in usedY) {
            usedY[y] = true;
            nY++;
        }
        if (x !in usedX) {
            usedX[x] = true;
            nX++;
        }
    }
    writeln(ans);

}

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

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

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

struct ModInt(long mod) {
    invariant() {
        assert(0 <= val && val < mod);
    }
    long val;
    this(long v) { this.val = (mod * mod + v) % mod; }
    ModInt opBinary(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(int y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(int y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinary(string op : "-")(long y) const { return ModInt(this.val - y); }
    ModInt opBinary(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinary(string op : "/")(long y) const { return ModInt(this.val * inv(y)); }
    ModInt opBinary(string op : "+")(ModInt y) const { return ModInt(this.val + y.val); }
    ModInt opBinary(string op : "-")(ModInt y) const { return ModInt(this.val - y.val); }
    ModInt opBinary(string op : "*")(ModInt y) const { return ModInt(this.val * y.val); }
    ModInt opBinary(string op : "/")(ModInt y) const { return ModInt(this.val * inv(y.val)); }
    ModInt opBinaryRight(string op : "+")(int y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(int y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(int y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(int y) const { return ModInt(inv(this.val) * y); }
    ModInt opBinaryRight(string op : "+")(long y) const { return ModInt(this.val + y); }
    ModInt opBinaryRight(string op : "-")(long y) const { return ModInt(y - this.val); }
    ModInt opBinaryRight(string op : "*")(long y) const { return ModInt(this.val * y); }
    ModInt opBinaryRight(string op : "/")(long y) const { return ModInt(inv(this.val) * y); }
    void opAssign(int y) { this.val = y; }
    void opAssign(long y) { this.val = y; }
    void opOpAssign(string op : "+")(int y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(int y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(int y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(int y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(long y) { this.val = (this.val + mod * mod + y) % mod; }
    void opOpAssign(string op : "-")(long y) { this.val = (this.val + mod * mod - y) % mod; }
    void opOpAssign(string op : "*")(long y) { this.val = (this.val * y) % mod; }
    void opOpAssign(string op : "/")(long y) { this.val = (this.val * inv(y)) % mod; }
    void opOpAssign(string op : "+")(ModInt y) { this.val = (this.val + mod * mod + y.val) % mod; }
    void opOpAssign(string op : "-")(ModInt y) { this.val = (this.val + mod * mod - y.val) % mod; }
    void opOpAssign(string op : "*")(ModInt y) { this.val = (this.val * y.val) % mod; }
    void opOpAssign(string op : "/")(ModInt y) { this.val = (this.val * inv(y.val)) % mod; }
    ModInt opUnary(string op : "-")() const { return ModInt(mod - this.val); }
    string toString() const { return val.to!string; }
    static long extgcd(long a, long b, ref long x, ref long y) {
        if (b == 0) {
            x = 1;
            y = 0;
            return a;
        }
        long d = extgcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
    }
    static long inv(long a) {
        long x, y;
        extgcd(a, mod, x, y);
        return (x % mod + mod) % mod;
    }
}

alias MInt = ModInt!998244353L;

void solve() {
    int N, M, K, Q; readf("%d %d %d %d\n", &N, &M,&K, &Q);
    auto Y = new int[Q], X = new int[Q];
    foreach (i; 0 .. Q) {
        readf("%d %d\n", &Y[i], &X[i]);
    }
    bool[int] usedY, usedX;
    int nY, nX;
    MInt ans = 1;
    for (int i = Q - 1; i >= 0; i--) {
        int y = Y[i], x = X[i];
        if ( (y in usedY || nY == N) && (x in usedX || nX == M) ) continue;
        ans *= K;
        if (y !in usedY) {
            usedY[y] = true;
            nY++;
        }
        if (x !in usedX) {
            usedX[x] = true;
            nX++;
        }
    }
    writeln(ans);

}

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


For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:  Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.

The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).

If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.

NoteIn the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5 In the second example, g(1) = g(2) = g(3) = 1

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

string solve (int n, int a, int b)
{
	int k = n;
	int [] p;

	void addCycle (int len)
	{
		int cur = p.length.to !(int) + 1;
		foreach (i; 1..len)
		{
			p ~= p.length.to !(int) + 2;
		}
		p ~= cur;
	}

	while (k % b != 0)
	{
		if (k < a)
		{
			return "-1";
		}
		k -= a;
		addCycle (a);
	}
	while (k > 0)
	{
		addCycle (b);
		k -= b;
	}
	assert (k == 0);
	return format ("%(%s %)", p);
}

void main ()
{
	int n, a, b;
	while (readf (" %s %s %s", &n, &a, &b) > 0)
	{
		writeln (solve (n, a, b));
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const A = readInt();
      const B = readInt();

      for (int x = 0; A * x <= N; ++x) {
        if ((N - A * x) % B == 0) {
          const y = (N - A * x) / B;
          int[] ans;
          int pos;
          foreach (i; 0 .. x) {
            foreach (j; 0 .. A) {
              ans ~= pos + (j + 1) % A;
            }
            pos += A;
          }
          foreach (i; 0 .. y) {
            foreach (j; 0 .. B) {
              ans ~= pos + (j + 1) % B;
            }
            pos += B;
          }
          foreach (i; 0 .. N) {
            if (i > 0) write(" ");
            write(ans[i] + 1);
          }
          writeln();
          goto found;
        }
      }
      writeln(-1);
     found:
    }
  } catch (EOFException e) {
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ ($$$n \ge 3$$$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $$$[4, 11, 4, 4]$$$ all numbers except one are equal to $$$4$$$).Print the index of the element that does not equal others. The numbers in the array are numbered from one.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$). It is guaranteed that all the numbers except one in the $$$a$$$ array are the same.

For each test case, output a single integer — the index of the element that is not equal to others.

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int[] a = readln.split.map!(to!int).array, b = a.dup;
        b.sort();
        foreach (i; 0 .. n)
            if (a[i] != b[1])
                writeln(i + 1);
    }
}

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int[] a = readln.split.map!(to!int).array;
        if (a[0] == a[1])
        {
            foreach (j; 0 .. n)
                if (a[j] != a[0])
                    writeln(j + 1);
        }
        else
        {
            if (a[0] == a[2])
                writeln(2);
            else
                writeln(1);
        }
    }
}

import std;

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

    foreach (_; 0 .. t) {
        int n;
        readf("%d\n", n);

        auto a = readln.chomp.split.to!(int[]);

        if (a[0] == a[1] && a[1] == a[2]) {
            foreach (i; 3 .. n) {
                if (a[i] != a[0]) {
                    writeln(i+1);
                }
            }
        }
        else {
            if (a[0] == a[1]) writeln(3);
            if (a[0] == a[2]) writeln(2);
            if (a[1] == a[2]) writeln(1);
        }
    }
}

// Vicfred
// https://codeforces.com/contest/1512/problem/A
// simulation, implementation
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

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

    int[] counter = new int[101];

    foreach(item; a) {
        counter[item] += 1;
    }

    for(int i = 0; i < n; ++i) {
        if(counter[a[i]] == 1) {
            (i + 1).writeln;
            break;
        }
    }
}
}

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int[] a = readln.split.map!(to!int).array, b = a.dup;
        b.sort();
        foreach (i; 0 .. n)
            if (b[i] != a[1])
                writeln(i + 1);
    }
}


We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109 + 7).

Input contains several test cases. The first line contains two integers t and k (1 ≤ t, k ≤ 105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1 ≤ ai ≤ bi ≤ 105), describing the i-th test.

Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109 + 7).

Note  For K = 2 and length 1 Marmot can eat (R).  For K = 2 and length 2 Marmot can eat (RR) and (WW).  For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR).  For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).

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

void main() {
    immutable int MAX = 10^^5+1;
    immutable int MOD = 10^^9+7;

    int T, K;
    scanf("%d %d", &T, &K);

    auto dp = new int[](MAX);
    foreach (i; 1..MAX) {
        dp[i] = (dp[i-1] + 1) % MOD;
        if (i - K >= 0)
            dp[i] = ((dp[i] + dp[i-K]) % MOD + 1) % MOD;
    }

    int a, b;
    foreach (_; 0..T) {
        scanf("%d %d", &a, &b);
        writeln(((dp[b] - dp[a-1]) % MOD + MOD) % MOD);
    }
}

module main;

import std.stdio, std.string;

static auto mod = 1000000007;

void init(int[] dp, int[] s, int k)
{
    foreach (i; 0 .. k)
    {
        dp[i] = 1;
    }
    foreach (i; k .. dp.length)
    {
        dp[i] = (dp[i - 1] + dp[i - k]) % mod;
    }
    s[0] = 0;
    foreach (i; 1 .. s.length)
    {
        s[i] = (s[i - 1] + dp[i]) % mod;
    }
}

int main(string[] args)
{
    int k, t;
    while (scanf("%d%d", &t, &k) == 2)
    {
        auto dp = new int[100001];
        auto s = new int[100001];
        init(dp, s, k);
        foreach (i; 0 .. t)
        {
            int a, b;
            scanf("%d%d", &a, &b);
            auto ans = s[b] - s[a - 1];
            if (ans < 0)
            {
                ans += mod;
            }
            writefln("%d", ans);
        }
    }
    return 0;
}

import std.stdio;
import std.exception;

void main() {
	size_t t, k;
	enforce(readf(" %s %s", &t, &k));

	enum MOD = cast(int)(1e9 + 7);
	enum N = 100500;
	int[N] z;
	z[0] = 1;
	foreach (cur; 1..N) {
		z[cur] = z[cur - 1];
		if (cur >= k)
			z[cur] += z[cur - k];
		z[cur] %= MOD;
	}
	foreach (cur; 1..N) {
		z[cur] += z[cur - 1];
		z[cur] %= MOD;
	}

	foreach (test; 0..t) {
		size_t a, b;
		enforce(readf(" %s %s", &a, &b));
		auto ans = (z[b] - z[a - 1] + MOD) % MOD;
		writeln(ans);
	}
}

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

void main() {
    immutable int MAX = 10^^5+1;
    immutable int MOD = 10^^9+7;

    int T, K;
    scanf("%d %d", &T, &K);

    auto dp = new int[](MAX);
    foreach (i; 1..MAX) {
        dp[i] = (dp[i-1] + 1) % MOD;
        if (i - K >= 0)
            dp[i] = ((dp[i] + dp[i-K]) % MOD + 1);
    }

    int a, b;
    foreach (_; 0..T) {
        scanf("%d %d", &a, &b);
        writeln(dp[b] - dp[a-1]);
    }
}

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

void main() {
    immutable int MAX = 10^^5+1;
    immutable int MOD = 10^^9+7;

    int T, K;
    scanf("%d %d", &T, &K);

    auto dp = new int[](MAX);
    foreach (i; 1..MAX) {
        dp[i] = (dp[i-1] + 1) % MOD;
        if (i - K >= 0)
            dp[i] = ((dp[i] + dp[i-K]) % MOD + 1);
    }

    int a, b;
    foreach (_; 0..T) {
        scanf("%d %d", &a, &b);
        writeln((dp[b] - dp[a-1]) % MOD + MOD % MOD);
    }
}

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

void main() {
    immutable int MAX = 10^^5+1;
    immutable int MOD = 10^^9+7;

    int T, K;
    scanf("%d %d", &T, &K);

    auto dp = new int[](MAX);
    foreach (i; 1..MAX) {
        dp[i] = (dp[i-1] + 1) % MOD;
        if (i - K >= 0)
            dp[i] = ((dp[i] + dp[i-K]) % MOD + 1) % MOD;
    }

    int a, b;
    foreach (_; 0..T) {
        scanf("%d %d", &a, &b);
        writeln((dp[b] - dp[a-1]) % MOD + MOD % MOD);
    }
}

module main;

import std.stdio, std.string;

void init(int[] dp, int[] s, int k)
{
    static auto mod = 1000000007;
    foreach (i; 0 .. k)
    {
        dp[i] = 1;
    }
    foreach (i; k .. dp.length)
    {
        dp[i] = (dp[i - 1] + dp[i - k]) % mod;
    }
    s[1] = dp[1];
    foreach (i; 2 .. s.length)
    {
        s[i] = (s[i - 1] + dp[i]) % mod;
    }
}

int main(string[] args)
{
    int k, t;
    while (scanf("%d%d", &t, &k) == 2)
    {
        auto dp = new int[100001];
        auto s = new int[100001];
        init(dp, s, k);
        foreach (i; 0 .. t)
        {
            int a, b;
            scanf("%d%d", &a, &b);
            writefln("%d", s[b] - s[a - 1]);
        }
    }
    return 0;
}

import std.stdio;
import std.exception;

void main() {
	size_t t, k;
	enforce(readf(" %s %s", &t, &k));

	enum MOD = cast(int)(1e9 + 7);
	enum N = 100500;
	int[N] z;
	z[0] = 1;
	foreach (cur; 1..N) {
		z[cur] = z[cur - 1];
		if (cur >= k)
			z[cur] += z[cur - k];
		z[cur] %= MOD;
	}
	foreach (cur; 1..N) {
		z[cur] += z[cur - 1];
		z[cur] %= MOD;
	}

	foreach (test; 0..t) {
		size_t a, b;
		enforce(readf(" %s %s", &a, &b));
		auto ans = z[b] - z[a - 1];
		writeln(ans);
	}
}


You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Determine if it is true that the given string $$$s$$$ is a substring of YesYesYes... (Yes repeated many times in a row).

The first line of input data contains the singular $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Each test case is described by a single string of Latin letters $$$s$$$ ($$$1 \le |s| \le 50$$$) — the part of Polycarp's answer that you heard, where $$$|s|$$$ — is the length of the string $$$s$$$.

Output $$$t$$$ lines, each of which is the answer to the corresponding test case. As an answer, output "YES" if the specified string $$$s$$$ is a substring of the string YesYesYes...Yes (the number of words Yes is arbitrary), and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

12

YES

esYes

codeforces

es

se

YesY

esYesYesYesYesYesYe

seY

Yess

sY

o

Yes

NO
YES
NO
YES
NO
YES
YES
NO
NO
YES
NO
YES

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		bool ok = false;
		foreach (i; 0..3)
		{
			auto t = "Yes".cycle.drop (i).take (s.length);
			if (equal (s, t))
			{
				ok = true;
			}
		}
		writeln (ok ? "YES" : "NO");
	}
}

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

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

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

void solve() {
    auto x = readln.strip();
    bool norm = true;
outer: foreach(i, e; x) {
        if (i == 0) {
            if ((e != 'Y') && (e != 'e') && (e !='s')) {
                norm = false;
                break outer;
            }
        }
        else {
            if ((e == 'Y' && x[i-1] == 's') || (e == 'e' && x[i-1] == 'Y') || (e == 's' && x[i-1] == 'e'))
                continue;
            else {
                norm = false;
                break outer;
            }
        }
    }
    if (norm)
        writeln("yes");
    else
        writeln("no");

}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto s = readln.strip;
    char prevch = s[0];
    bool good = (prevch == 'Y' || prevch == 'e' || prevch == 's');
    foreach (ch ; s[1 .. $]) {
      if ((ch == 'Y' && prevch == 's') ||
          (ch == 'e' && prevch == 'Y') ||
          (ch == 's' && prevch == 'e')) {
        prevch = ch;
      } else {
        good = false;
        break;
      }
    }
    writeln(good ? "YES" : "NO");
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip.toLower;
		bool ok = false;
		foreach (i; 0..3)
		{
			auto t = "yes".cycle.drop (i).take (s.length);
			if (equal (s, t))
			{
				ok = true;
			}
		}
		writeln (ok ? "YES" : "NO");
	}
}


You are asked to watch your nephew who likes to play with toy blocks in a strange way.He has $$$n$$$ boxes and the $$$i$$$-th box has $$$a_i$$$ blocks. His game consists of two steps:   he chooses an arbitrary box $$$i$$$;  he tries to move all blocks from the $$$i$$$-th box to other boxes.  If he can make the same number of blocks in each of $$$n - 1$$$ other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box $$$i$$$ he chooses he won't be sad. What is the minimum number of extra blocks you need to put?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of boxes. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of blocks in each box. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite.

NoteIn the first test case, you can, for example, put one extra block into the first box and make $$$a = [4, 2, 2]$$$. If your nephew chooses the box with $$$4$$$ blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with $$$2$$$ blocks then he will move these two blocks to the other box with $$$2$$$ blocks.In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.In the third test case, you should put $$$3$$$ extra blocks. For example, you can put $$$2$$$ blocks in the first box and $$$1$$$ block in the third box. You'll get array $$$a = [2, 3, 1]$$$.

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 !(long)).array;
		auto m = a.maxElement * (n - 1L);
		auto t = a.sum (0L);
		auto s = max (m, t);
		s += ((n - 1) - (s % (n - 1))) % (n - 1);
		writeln (s - t);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x, tot;
		foreach (e; a)
		{
			x.chmax(e);
			tot += e;
		}
		auto y = x * (n-1);
		if (tot <= y)
			ans[ti] = y - tot;
		else
			ans[ti] = ((n-1) - (tot % (n-1))) % (n-1);
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x, tot;
		foreach (e; a)
		{
			x.chmax(e);
			tot += e;
		}
		auto y = x * (n-1);
		if (tot <= y)
			ans[ti] = y - tot;
		else
			ans[ti] = (n-1) - (tot % (n-1));
	}

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