Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).Your task is to count the number of segments where Horace can "see an elephant".

The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.

Print the number of segments in the bears' wall where Horace can "see an elephant".

NoteThe picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.

import std.stdio;

immutable int p = 13957;

immutable int MOD = 1000000007;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p % MOD;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p % MOD + b[i];
    h %= MOD;
    if (h < 0) {
      h += MOD;
    }
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p % MOD + a[i];
    cur %= MOD;
    if (cur < 0) {
      cur += MOD;
    }
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1] % MOD;
      if (cur < 0) {
        cur += MOD;
      }
    }
    if (i >= w - 1) {
      cur %= MOD;
      if (cur < 0) {
        cur += MOD;
      }
      ans += cur == h;
    }
  }
  writeln(ans);
}

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

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

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

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

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

int M, N;
int[] A, B;
int[] P, Q;

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

		if (N == 1) {
			writeln(M);
		} else {
			P = new int[M - 1];
			foreach (i; 0 .. M - 1) {
				P[i] = A[i + 1] - A[i];
			}
			Q = new int[N - 1];
			foreach (i; 0 .. N - 1) {
				Q[i] = B[i + 1] - B[i];
			}
debug{
writeln("P = ",P);
writeln("Q = ",Q);
}
			int[] fail = new int[Q.length + 1];
			int j = fail[0] = -1;
			foreach (i; 0 .. Q.length) {
				for (; j >= 0 && Q[j] != Q[i]; j = fail[j]) {}
				fail[i + 1] = ++j;
			}
debug{
writeln("fail = ",fail);
}
			int ans;
			j = 0;
			foreach (i; 0 .. P.length) {
				for (; j >= 0 && Q[j] != P[i]; j = fail[j]) {}
				if (++j == Q.length) {
					++ans;
					j = fail[j];
				}
			}
			writeln(ans);
		}
	}
	} catch (EOFException) {}
}

import std.stdio;
import std.algorithm;

void main() { while (solve()) {} }

auto getZ(int[] s) {
	int n = cast(int)s.length;
	int lf = -1, rg = -1;
	auto z = new int[n];
	z[0] = 0;
	foreach (i; 1..n) {
		z[i] = 0;
		if (i < rg) z[i] = min(z[i - lf], rg - i);
		while (i + z[i] < n && s[i + z[i]] == s[z[i]])
			z[i]++;
		if (i + z[i] > rg) {
			lf = i;
			rg = i + z[i];
		}
	}
	return z;
}

bool solve() {
	int n, w;
	if (!readf(" %s %s", &n, &w)) return false;
	auto a = new int[n], b = new int[w];
	foreach (ref x; a) readf(" %s", &x);
	foreach (ref x; b) readf(" %s", &x);
	if (w == 1) {
		writeln(n);
		return true;
	}
	auto da = new int[n - 1];
	foreach (i, ref dx; da)
		dx = a[i + 1] - a[i];
	auto db = new int[w - 1];
	foreach (i, ref dx; db)
		dx = b[i + 1] - b[i];
	auto s = db ~ da;
	auto z = getZ(s);
	int ans = 0;
	foreach (val; z[db.length..$])
		if (val >= db.length) ans++;
	writeln(ans);
	return true;

}

import std.stdio;

immutable int p = 37;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  a[0] = 0;
  for (int i = 1; i < n; i++) {
    cur = cur * p + a[i];
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 13957;

immutable int MOD = 1000000009;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p % MOD;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p % MOD + b[i];
    h %= MOD;
    if (h < 0) {
      h += MOD;
    }
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p % MOD + a[i];
    cur %= MOD;
    if (cur < 0) {
      cur += MOD;
    }
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1] % MOD;
      if (cur < 0) {
        cur += MOD;
      }
    }
    if (i >= w - 1) {
      cur %= MOD;
      if (cur < 0) {
        cur += MOD;
      }
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 37;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p + a[i];
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 37;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  a[0] = 0;
  for (int i = 1; i <= n; i++) {
    if (i < n) {
      cur = cur * p + a[i];
    }
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 11;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p + a[i];
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 1000000007;

immutable int MOD = 1000000009;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p % MOD;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p % MOD + b[i];
    h %= MOD;
    if (h < 0) {
      h += MOD;
    }
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p % MOD + a[i];
    if (cur < 0) {
      cur += MOD;
    }
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1] % MOD;
      if (cur < 0) {
        cur += MOD;
      }
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 13579;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p + a[i];
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 1000000007;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p + a[i];
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 23719;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p + b[i];
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p + a[i];
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1];
    }
    if (i >= w - 1) {
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 1000000007;

immutable int MOD = 1000000009;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p % MOD;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p % MOD + b[i];
    h %= MOD;
    if (h < 0) {
      h += MOD;
    }
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p % MOD + a[i];
    cur %= MOD;
    if (cur < 0) {
      cur += MOD;
    }
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1] % MOD;
      if (cur < 0) {
        cur += MOD;
      }
    }
    if (i >= w - 1) {
      cur %= MOD;
      if (cur < 0) {
        cur += MOD;
      }
      ans += cur == h;
    }
  }
  writeln(ans);
}

import std.stdio;

immutable int p = 13957;

immutable int MOD = 1000000007;

void main() {
  int n, w; readf(" %s %s", &n, &w);
  auto pw = new long[n + 10];
  pw[0] = 1;
  for (int i = 1; i < pw.length; i++) {
    pw[i] = pw[i - 1] * p % MOD;
  }
  auto a = new int[n];
  auto b = new int[w];
  for (int i = 0; i < n; i++) {
    readf(" %s", &a[i]);
  }
  for (int i = n - 1; i > 0; i--) {
    a[i] -= a[i - 1];
  }
  a[0] = 0;
  long h = 0;
  long mult = 1;
  for (int i = 0; i < w; i++) {
    readf(" %s", &b[i]);
  }
  for (int i = w - 1; i > 0; i--) {
    b[i] -= b[i - 1];
  }
  b[0] = 0;
  for (int i = 1; i < w; i++) {
    h = h * p % MOD + b[i];
    h %= MOD;
    if (h < 0) {
      h += MOD;
    }
  }
  long cur = 0;
  int ans = 0;
  for (int i = 0; i < n; i++) {
    cur = cur * p % MOD + a[i];
    cur %= MOD;
    if (cur < 0) {
      cur += MOD;
    }
    writeln(i, ' ', cur, ' ', h);
    if (i >= w) {
      cur -= pw[w - 1] * a[i - w + 1] % MOD;
      if (cur < 0) {
        cur += MOD;
      }
    }
    if (i >= w - 1) {
      cur %= MOD;
      if (cur < 0) {
        cur += MOD;
      }
      ans += cur == h;
    }
    writeln(i, ' ', cur, ' ', h);
  }
  writeln(ans);
}

import std.stdio;
import std.algorithm;

void main() { while (solve()) {} }

auto getZ(int[] s) {
	int n = cast(int)s.length;
	int lf = -1, rg = -1;
	auto z = new int[n];
	z[0] = 0;
	foreach (i; 1..n) {
		z[i] = 0;
		if (i < rg) z[i] = min(z[i - lf], rg - i);
		while (i + z[i] < n && s[i + z[i]] == s[z[i]])
			z[i]++;
		if (i + z[i] > rg) {
			lf = i;
			rg = i + z[i];
		}
	}
	return z;
}

bool solve() {
	int n, w;
	if (!readf(" %s %s", &n, &w)) return false;
	auto a = new int[n], b = new int[w];
	foreach (ref x; a) readf(" %s", &x);
	foreach (ref x; b) readf(" %s", &x);
	if (w == 1) {
		writeln(n);
		return true;
	}
	auto da = new int[n - 1];
	foreach (i, ref dx; da)
		dx = a[i + 1] - a[i];
	auto db = new int[w - 1];
	foreach (i, ref dx; db)
		dx = b[i + 1] - b[i];
	auto s = db ~ da;
	auto z = getZ(s);
	int ans = 0;
	foreach (val; z[db.length..$])
		if (val == db.length) ans++;
	writeln(ans);
	return true;
}


Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array $$$a$$$ of $$$n$$$ integers. You are also given an integer $$$k$$$. Lord Omkar wants you to do $$$k$$$ operations with this array.Define one operation as the following:   Set $$$d$$$ to be the maximum value of your array.  For every $$$i$$$ from $$$1$$$ to $$$n$$$, replace $$$a_{i}$$$ with $$$d-a_{i}$$$. The goal is to predict the contents in the array after $$$k$$$ operations. Please help Ray determine what the final sequence will look like!

Each test contains multiple test cases. The first line contains the number of cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) – the length of your array and the number of operations to perform. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ – the initial contents of your array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each case, print the final version of array $$$a$$$ after $$$k$$$ operations described above.

NoteIn the first test case the array changes as follows:Initially, the array is $$$[-199, 192]$$$. $$$d = 192$$$.After the operation, the array becomes $$$[d-(-199), d-192] = [391, 0]$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n;
		long k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		k -= 1;
		auto d = a.maxElement;
		a[] = d - a[];
		k &= 1;
		while (k > 0)
		{
			d = a.maxElement;
			a[] = d - a[];
			k -= 1;
		}
		writefln !("%(%s %)") (a);
	}
}

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

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

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

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

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

        auto ans = new long[N];
        if (K % 2 == 0) {
          const AMin = A.minElement;
          foreach (i; 0 .. N) {
            ans[i] = A[i] - AMin;
          }
        } else {
          const AMax = A.maxElement;
          foreach (i; 0 .. N) {
            ans[i] = AMax - A[i];
          }
        }

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

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n, k;
  @Dim("n") long[] a;

  void solve(long tc = -1)
  {
    if (k % 2 == 1)
      {
        auto m = a.fold!max;
        foreach(ai; a)
          {
            write(m - ai, " ");
          }
        writeln;
      }
    else
      {
        auto m = a.fold!min;
        foreach(ai; a)
          {
            write(ai - m, " ");
          }
        writeln;
      }
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		{
			int x = int.min;
			foreach (i; 0..n)
			{
				x.chmax(a[i]);
			}
			foreach (i; 0..n)
			{
				a[i] = x - a[i];
			}
		}
		if (k % 2 == 0)
		{
			int x = int.min;
			foreach (i; 0..n)
			{
				x.chmax(a[i]);
			}
			foreach (i; 0..n)
			{
				a[i] = x - a[i];
			}
		}
		ans[ti] = a;
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}


In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?

The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \leq a, b \leq 10^{9}$$$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.

In the first line print a single integer $$$n$$$ ($$$0 \leq n \leq a$$$) — the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \leq m \leq b$$$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \ldots, q_m$$$ ($$$1 \leq q_i \leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.

NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total.

void main() {
    import std.range : dropExactly, retro, sequence, take;
    import std.stdio : readf, writefln;

    int a, b;
    readf!" %d %d"(a, b);

    int nn;
    int ns;
    foreach (n; sequence!"n".dropExactly(1)) {
        ns += n;
        if (ns > a + b)
            break;
        nn++;
    }

    int[] d1;
    d1.reserve(nn);
    int[] d2;
    d2.reserve(nn);

    foreach (n; sequence!"n".dropExactly(1).take(nn).retro) {
        if (n <= a) {
            a -= n;
            d1 ~= n;
        }
        else {
            d2 ~= n;
        }
    }
    writefln("%s\n%(%s %)\n%s\n%(%s %)", d1.length, d1, d2.length, d2);
}

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 a, b;
    readf("%s %s", &a, &b);
    readln;

    int s = a + b;
    int k = 0;
    while (((k+1).to!long * (k+2)) / 2 <= s) ++k;

    int[][2] nrs;
    int cur = k;
    while (cur > 0) {
        if (cur <= a) {
            nrs[0] ~= cur;
            a -= cur;
        } else {
            nrs[1] ~= cur;
            b -= cur;
        }
        --cur;
    }

    foreach (arr; nrs) {
        arr.length.writeln;
        arr.writefln!("%(%s %)");
    }
}


Once Divan analyzed a sequence $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ non-negative integers as follows. He considered each non-empty subsequence of the sequence $$$a$$$, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence $$$a$$$.A sequence $$$c$$$ is a subsequence of a sequence $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[1, \, 2, \, 3, \, 4]$$$, $$$[2, \, 4]$$$, and $$$[2]$$$ are subsequences of $$$[1, \, 2, \, 3, \, 4]$$$, but $$$[4, \, 3]$$$ and $$$[0]$$$ are not.Divan was very proud of his analysis, but now he lost the sequence $$$a$$$, and also the coziness value! However, Divan remembers the value of bitwise OR on $$$m$$$ contiguous subsegments of the sequence $$$a$$$. It turns out that each element of the original sequence is contained in at least one of these $$$m$$$ segments.Divan asks you to help find the coziness of the sequence $$$a$$$ using the information he remembers. If several coziness values are possible, print any.As the result can be very large, print the value modulo $$$10^9 + 7$$$.

The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each test case contains two integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the sequence and the number of contiguous segments whose bitwise OR values Divan remembers, respectively. The following $$$m$$$ lines describe the segments, one per line. Each segment is described with three integers $$$l$$$, $$$r$$$, and $$$x$$$ ($$$1 \le l \le r \le n$$$, $$$0 \le x \le 2^{30} - 1$$$) — the first and last elements of the segment and the bitwise OR of $$$a_l, a_{l + 1}, \ldots, a_r$$$, respectively. It is guaranteed that each element of the sequence is contained in at least one of the segments. It is guaranteed that there exists a sequence that satisfies all constraints. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.

For each test case print the coziness any suitable sequence $$$a$$$ modulo $$$10^9 + 7$$$.

NoteIn first example, one of the sequences that fits the constraints is $$$[0, 2]$$$. Consider all its non-empty subsequences:  $$$[0]$$$: the bitwise XOR of this subsequence is $$$0$$$;  $$$[2]$$$: the bitwise XOR of this subsequence is $$$2$$$;  $$$[0, 2]$$$: the bitwise XOR of this subsequence is $$$2$$$. The sum of all results is $$$4$$$, so it is the answer.In second example, one of the sequences that fits the constraints is $$$[0, \, 5, \, 5]$$$.In third example, one of the sequences that fits the constraints is $$$[5, \, 6, \, 7, \, 0, \, 2]$$$.

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

const long MOD = 1_000_000_007;

// Modexp
ll modexp(ll base, ll exp){
    ll x = base % MOD;
    ll y = exp;
    ll res = 1;
    while(y > 0){
        if(y & 1){
            res *= x; res %= MOD;
        }
        x *= x; x %= MOD;
        y >>= 1;
    }
    return res;
}

void solve(){
    long n = scan;
    long m = scan;
    long res = 0;
    for(int i = 0; i < m; ++i){
        long l = scan;
        long r = scan;
        long x = scan;
        res |= x;
    }
    res *= modexp(2, n-1);
    res %= MOD;
    writeln(res);
}

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

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

immutable multi = true;

immutable long p = 1_000_000_000L + 7;
alias Zp = Z!p;
long[] p2;

static this()
{
	p2 = new long[](2_000_00 + 1);
	p2[0] = 1;
	foreach(i; 1 .. p2.length)
		p2[i] = (p2[i-1] * 2)%p;
}

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	struct Rel
	{
		int i, acc;
	}
	auto rel = new Rel[][](n + 1);
	auto cum = new int[](n + 1);
	foreach(i; 0 .. m)
	{
		auto l = readInt!int - 1;
		auto r = readInt!int;
		auto x = readInt!int;
		rel[r] ~= Rel(l, x);
		rel[l] ~= Rel(r, x);
	}
	auto filled = new bool[](n + 1);
	void dfs(int v, int fill)
	{
		if (filled[v])
		{
			assert(fill == cum[v]);
			return;
		}
		cum[v] = fill;
		filled[v] = true;
		foreach(r; rel[v])
		{
			auto w = r.i;
			auto x = r.acc;
			dfs(w, x ^ fill);
		}
	}
	foreach(i; 0 .. n + 1)
	{
		if (!filled[i])
			dfs(i, 0);
	}
	auto orig = new int[](n);
	int[30] cnt;
	foreach(i, ref oi; orig)
	{
		oi = cum[i+1] ^ cum[i];
		int b = 0;
		while (oi)
		{
			cnt[b] += int((oi & 1) != 0);
			b++;
			oi >>= 1;
		}
	}
	long ans = 0;
	foreach(i; 0 .. 30)
	{
		if (cnt[i] == 0) continue;
		long term = 1;
		term *= p2[i];
		term *= p2[n - 1];
		term %= p;
		ans += term;
		ans %= p;
	}
	ans.writeln;
}

// modular {{{
struct Z(immutable long m)
{
	long rep;
	static immutable bool primeModulus = isPrime(m);
	static Z!m[] fact;
	static if (primeModulus) { static Z!m[] invFact; }
	static makeFactorials(int n)
	{
		fact = new Z!m[](n + 1);
		fact[0] = Z!m(1);
		foreach(i; 1 .. n + 1) fact[i] = Z!m(i) * fact[i - 1];
		static if (primeModulus)
		{
			invFact = new Z!m[](n + 1);
			invFact[n] = fact[n].inv;
			foreach_reverse(i; 0 .. n) invFact[i] = Z!m(i + 1) * invFact[i + 1];
		}
	}

	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else static if (operator == "/" && primeModulus)
		{
			assert(rhs != Z!m(0));
			return this * rhs.inv;
		}
		else
		{
			static assert(text("Operator ", operator, " not supported"));
		}
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	static if (primeModulus)
	{
		Z!m inv()
		{
			return this^^(m - 2);
		}
		static Z!m C(int n, int k)
		{
			if (k < 0 || k > n) return Z!m(0);
			return fact[n] * invFact[k] * invFact[n - k];
		}
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}
bool isPrime(long n)
{
	for(long d = 2; d * d <= n; d++)
		if (n % d == 0) return false;
	return true;
}
unittest
{
	alias Zp = Z!23;
	static assert(Zp.primeModulus);
	foreach(i; 1 .. 23) assert(Zp(i) * Zp(i).inv == Zp(1));
	Zp.makeFactorials(22);
	foreach(i; 0 .. 23) assert(Zp.fact[i] * Zp.invFact[i] == Zp(1));
	assert(Zp.C(3, 2) == Zp(3));
	assert(Zp.C(4, 2) == Zp(6));
}
// }}}

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

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

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

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

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


Positive integer $$$x$$$ is called divisor of positive integer $$$y$$$, if $$$y$$$ is divisible by $$$x$$$ without remainder. For example, $$$1$$$ is a divisor of $$$7$$$ and $$$3$$$ is not divisor of $$$8$$$.We gave you an integer $$$d$$$ and asked you to find the smallest positive integer $$$a$$$, such that  $$$a$$$ has at least $$$4$$$ divisors;  difference between any two divisors of $$$a$$$ is at least $$$d$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3000$$$) — the number of test cases. The first line of each test case contains a single integer $$$d$$$ ($$$1 \leq d \leq 10000$$$).

For each test case print one integer $$$a$$$ — the answer for this test case.

NoteIn the first test case, integer $$$6$$$ have following divisors: $$$[1, 2, 3, 6]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$1$$$. There is no smaller integer with at least $$$4$$$ divisors.In the second test case, integer $$$15$$$ have following divisors: $$$[1, 3, 5, 15]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$2$$$.The answer $$$12$$$ is INVALID because divisors are $$$[1, 2, 3, 4, 6, 12]$$$. And the difference between, for example, divisors $$$2$$$ and $$$3$$$ is less than $$$d=2$$$.

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

const int sz = 100005;
bool[] isPrime;
ll[] primes;
void prime_sieve(){
    isPrime = new bool[](sz + 5);
    isPrime[] = 1;
    foreach(p; 2..10000){
        if(isPrime[p]){
            for(ll divi = p*p; divi <= sz; divi += p){
                isPrime[divi.to!int] = 0;
            }
        }
    }
    for(int i = 2; i <= sz; ++i){
        if(isPrime[i]) primes ~= i;
    }
}

void theCode(){
    ll d;
    d = scan;
    int lo = -1, hi = primes.length.to!int-1;
    while(hi - lo > 1){
        int mid = (hi + lo )>> 1;
        ((primes[mid] < d+1) ? lo : hi) = mid;
    }
    long p0 = primes[hi];
    lo = -1, hi = primes.length.to!int-1;
    while(hi - lo > 1){
        int mid = (hi + lo )>> 1;
        ((primes[mid] < d + p0) ? lo : hi) = mid;
    }
    long p1 = primes[hi];
    writeln(p0*p1);
}

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

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

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

enum PCNT = 10^^6;

bool[PCNT+1] PS;

void prime_init()
{
    PS[] = true;
    PS[0] = false;
    PS[1] = false;
    foreach (i; 2..PCNT+1) {
        if (PS[i]) {
            auto x = i*2;
            while (x <= PCNT) {
                PS[x] = false;
                x += i;
            }
        }
    }
}

void main()
{
    prime_init();
    int[] ps;
    foreach (i; 1..PCNT + 1) if (PS[i]) ps ~= i;

    int T; get(T);
    while (T--) {
        int d; get(d);
        if (d == 1) {
            writeln(6);
            continue;
        }
        long search(long p) {
            int l, r = ps.length.to!int;
            while (l + 1 < r) {
                auto m = (l + r) / 2;
                if (ps[m] >= p + d) {
                    r = m;
                } else {
                    l = m;
                }
            }
            return ps[r];
        }
        auto p = search(1);
        auto q = search(p);
        writeln(p * q);
    }
}

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

auto sieve (int limit)
{
	auto res = new bool [limit];
	res[2..$] = true;
	for (int d = 2; d * d < limit; d++)
	{
		if (res[d])
		{
			for (int e = d; e * d < limit; e++)
			{
				res[e * d] = false;
			}
		}
	}
	return res;
}

immutable int limit = 30_000;

void main ()
{
	auto s = sieve (limit);

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto d = readln.strip.to !(int);
		auto x = 1;
		auto res = x;
		foreach (i; 0..2)
		{
			x += d;
			while (!s[x])
			{
				x += 1;
			}
			res *= x;
		}
		writeln (res);
	}
}

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

const int sz = 100005;
bool[] isPrime;
void prime_sieve(){
    isPrime = new bool[](sz + 5);
    isPrime[] = 1;
    foreach(p; 2..10000){
        if(isPrime[p]){
            for(ll divi = p*p; divi <= sz; divi += p){
                isPrime[divi.to!int] = 0;
            }
        }
    }
}

void theCode(){
    ll n;
    n = scan;
    ll fp;
    for(ll d = n+1; d < 100000 ; ++d){
        if(isPrime[d.to!int]){
            fp = d;
            ll res = (2*fp - 1) * fp;
            writeln(res);
            return;
        }
    }
}

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

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

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

void theCode(){
    ll n;
    n = scan;
    ll res = (2*n + 1) * (n + 1);
    writeln(res);
}

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

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


Arkady is playing Battleship. The rules of this game aren't really important.There is a field of $$$n \times n$$$ cells. There should be exactly one $$$k$$$-decker on the field, i. e. a ship that is $$$k$$$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the size of the field and the size of the ship. The next $$$n$$$ lines contain the field. Each line contains $$$n$$$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).

Output two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship. If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.

NoteThe picture below shows the three possible locations of the ship that contain the cell $$$(3, 2)$$$ in the first sample.

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

int[] f(string s, int k)
{
    int[] taken = [-1];

    foreach (i, c; s)
    {
        if (c == '#')
        {
            taken ~= cast(int) i;
        }
    }

    taken ~= cast(int) s.length;

    int[] result = new int[s.length];

    int curInTaken = 1;

    foreach (i, ref v; result)
    {
        while (taken[curInTaken] < i)
        {
            curInTaken++;
        }

        if (i == taken[curInTaken] || k >= taken[curInTaken] - taken[curInTaken - 1])
        {
            v = 0;
        }
        else
        {
            v = min(i - taken[curInTaken - 1], taken[curInTaken] - i, k, taken[curInTaken] - taken[curInTaken - 1] - k);
        }
    }

    return result;
}

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

    readln();

    string[] field;
    int[][] a;

    foreach (i; 0 .. n)
    {
        auto s = readln().strip();
        a ~= f(s, k);
        field ~= s;
    }

    foreach (i; 0 .. n)
    {
        string s;

        foreach (j; 0 .. n)
        {
            s ~= field[j][i];
        }

        auto r = f(s, k);

        foreach (j; 0 .. n)
        {
            a[j][i] += r[j];
        }
    }

    int x = 0, y = 0, mx = 0;

    foreach (i; 0 .. n)
    {
        foreach (j; 0 .. n)
        {
            if (a[i][j] > mx)
            {
                mx = a[i][j];
                x = j;
                y = i;
            }
        }
    }

    writeln(y+1, ' ', x+1);
}

import std.algorithm.iteration : map;
import std.algorithm.searching : maxElement;
import std.array;
import std.range : enumerate;
import std.stdio;

void main()
{
  int n, k;
  readf!"%d %d\n"(n, k);
  auto board = stdin.byLineCopy().array();
  int[][] count = new int[][](n, n);

  foreach (r; 0..n) {
    foreach (c; 0..n) {
      auto valid = true;

      // check horizontal
      foreach (i; 0..k) {
	if (c+i >= n || board[r][c+i] == '#') {
	  valid = false;
	  break;
	}
      }
      if (valid) {
	foreach (i; 0..k) {
	  count[r][c+i]++;
	}
      }

      valid = true;
      // check vertical
      foreach (j; 0..k) {
	if (r+j >= n || board[r+j][c] == '#') {
	  valid = false;
	  break;
	}
      }
      if (valid) {
	foreach (j; 0..k) {
	  count[r+j][c]++;
	}
      }
    }
  }

  auto countIdx = count.map!(a => a.enumerate.maxElement!"a.value");
  auto best = countIdx.enumerate.maxElement!"a.value.value";
  writef("%d %d\n", best.index + 1, best.value.index + 1);
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readC(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=rdsp;foreach(ref v;t)pick(r,v[i]);}}

void main()
{
  int n, k; readV(n, k);
  string[] s; readC(n, s);

  auto a = new int[][](n, n);

  auto checkH(int r, int c)
  {
    foreach (i; 0..k)
      if (s[r][c+i] == '#') return false;
    return true;
  }

  auto addH(int r, int c)
  {
    foreach (i; 0..k) a[r][c+i] += 1;
  }

  auto checkV(int r, int c)
  {
    foreach (i; 0..k)
      if (s[r+i][c] == '#') return false;
    return true;
  }

  auto addV(int r, int c)
  {
    foreach (i; 0..k) a[r+i][c] += 1;
  }

  foreach (r; 0..n)
    foreach (c; 0..n) {
      if (c <= n-k && checkH(r, c)) addH(r, c);
      if (r <= n-k && checkV(r, c)) addV(r, c);
    }

  auto m = a.map!(ai => ai.maxElement).maxElement;
  foreach (r; 0..n)
    foreach (c; 0..n)
      if (a[r][c] == m) {
        writeln(r+1, " ", c+1);
        return;
      }
}

import std.algorithm.iteration : map;
import std.algorithm.searching : maxElement;
import std.array;
import std.range : enumerate;
import std.stdio;

void main()
{
  int n, k;
  readf!"%d %d\n"(n, k);
  auto board = stdin.byLineCopy().array();
  int[][] count = new int[][](n, n);

  foreach (r; 0..n-k+1) {
    foreach (c; 0..n-k+1) {
      auto valid = true;

      // check horizontal
      foreach (i; 0..k) {
	if (board[r][c+i] == '#') {
	  valid = false;
	  break;
	}
      }
      if (valid) {
	foreach (i; 0..k) {
	  count[r][c+i]++;
	}
      }

      valid = true;
      // check vertical
      foreach (j; 0..k) {
	if (board[r+j][c] == '#') {
	  valid = false;
	  break;
	}
      }
      if (valid) {
	foreach (j; 0..k) {
	  count[r+j][c]++;
	}
      }
    }
  }

  auto countIdx = count.map!(a => a.enumerate.maxElement!"a.value");
  auto best = countIdx.enumerate.maxElement!"a.value.value";
  writef("%d %d\n", best.index + 1, best.value.index + 1);
}


Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

The first line of the input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — the initial sum in rubles Andrew has.  The second line of the input contains one integer $$$d$$$ ($$$30 \leq d \leq 100$$$) — the price of one dollar in rubles.  The third line of the input contains integer $$$e$$$ ($$$30 \leq e \leq 100$$$) — the price of one euro in rubles.

Output one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.

NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill.

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

void main() {
    int n,d,e;
    readf!" %s %s %s"(n,d,e);

    int ans = n;

    for (int k = 0; k <= n / d; k++) {
        int rest = n - k * d;
        ans = min(ans, rest % (e*5));
    }

    writeln(ans);
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const D = readInt();
      const E = readInt();

      int ans = N;
      for (int a = 0; D * a <= N; ++a) {
        const n = N - D * a;
        chmin(ans, n % (E * 5));
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

//long mod = 10^^9 + 7;
long mod = 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 main()
{
	auto n = RD!int;
	auto d = RD;
	auto e = RD*5;

	long ans = long.max;
	while (n >= e)
	{
		ans = min(n % d, ans);
		n  -= e;
	}
	ans = min(n % d, ans);

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


Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.

You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.

Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

void makeKmpPrefixFunction(string pattern, int[] kmpPreFunc) {
	int m = pattern.length;
	int k = -1;
	int q = 0;
	kmpPreFunc[q] = k;
	while (q < m) {
		while (k >= 0 && pattern[k] != pattern[q])
			k = kmpPreFunc[k];
		++k;
		++q;
		kmpPreFunc[q] = k;
	}
}

int main() {
    debug stdin = File("in.txt", "r");

    string answer = "Just a legend";

    string str;
    readf("%s\n", &str);
    int[] kmpPreFunc = new int[str.length + 1];
    makeKmpPrefixFunction(str, kmpPreFunc);
    int mm = kmpPreFunc[$ - 1];
    if (mm > 0) {
        bool found = false;
        foreach ( i ; 1 .. str.length ) {
            if (kmpPreFunc[i] == mm) {
                found = true;
                answer = str[0 .. mm];
            }
        }
        if (!found) {
            foreach ( i ; 0 .. mm + 1 ) kmpPreFunc[i] = 0;
            makeKmpPrefixFunction(str[0 .. mm], kmpPreFunc);
            if (kmpPreFunc[mm] > 0) answer = str[0 .. kmpPreFunc[mm]];
        }
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

void makeKmpPrefixFunction(string pattern, int[] kmpPreFunc) {
	int m = pattern.length;
	int k = -1;
	int q = 0;
	kmpPreFunc[q] = k;
	while (q < m) {
		while (k >= 0 && pattern[k] != pattern[q])
			k = kmpPreFunc[k];
		++k;
		++q;
		kmpPreFunc[q] = k;
	}
}

int main() {
    debug stdin = File("in.txt", "r");

    string answer = "Just a legend";

    string str;
    readf("%s\n", &str);
    int[] kmpPreFunc = new int[str.length + 1];
    makeKmpPrefixFunction(str, kmpPreFunc);
    int mm = kmpPreFunc[str.length];
    if (mm > 0) {
        bool found = false;
        foreach ( i ; 1 .. str.length ) {
            if (kmpPreFunc[i] == mm) {
                found = true;
                answer = str[0 .. mm];
                break;
            }
        }
        if (!found) {
            foreach ( i ; 0 .. mm + 1 ) kmpPreFunc[i] = 0;
            makeKmpPrefixFunction(str[0 .. mm], kmpPreFunc);
            if (kmpPreFunc[mm] > 0) answer = str[0 .. kmpPreFunc[mm]];
        }
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int matchlen(string str, int pos) {
    pragma(inline, true);
    int res = 0;
    for (int i = 0; i < pos && i*3 < str.length; ++i) {
        if (str[i] == str[i + pos]) ++res;
    }
    return res;
}

int main() {
    debug stdin = File("in.txt", "r");

    string str;
    readf("%s\n", &str);
    if (str.length < 3) {
        writeln("Just a legend");
        return 0;
    }
    foreach_reverse ( i ; 1 .. 1 + str.length / 3 ) {
next:   foreach ( j ; i .. 1 + i + str.length - 3 * i ) {
            foreach ( k ; 0 .. i ) {
                if (str[k] != str[k + j] || str[k + j] != str[$ - i + k])
                    continue next;
            }
            writeln(str[0 .. i]);
            return 0;
        }
    }
    writeln("Just a legend");

    return 0;
}


Polycarp has $$$3$$$ positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He can perform the following operation exactly once.  Choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$. Can Polycarp make it so that after performing the operation, the sequence of three numbers $$$a$$$, $$$b$$$, $$$c$$$ (in this order) forms an arithmetic progression? Note that you cannot change the order of $$$a$$$, $$$b$$$ and $$$c$$$.Formally, a sequence $$$x_1, x_2, \dots, x_n$$$ is called an arithmetic progression (AP) if there exists a number $$$d$$$ (called "common difference") such that $$$x_{i+1}=x_i+d$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$. In this problem, $$$n=3$$$.For example, the following sequences are AP: $$$[5, 10, 15]$$$, $$$[3, 2, 1]$$$, $$$[1, 1, 1]$$$, and $$$[13, 10, 7]$$$. The following sequences are not AP: $$$[1, 2, 4]$$$, $$$[0, 1, 0]$$$ and $$$[1, 3, 2]$$$.You need to answer $$$t$$$ independent test cases.

The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains $$$3$$$ integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$).

For each test case print "YES" (without quotes) if Polycarp can choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$ to make $$$[a, b, c]$$$ be an arithmetic progression. Print "NO" (without quotes) otherwise. You can print YES and NO in any (upper or lower) case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).

YES
YES
YES
YES
NO
YES
NO
YES
YES
NO
YES

NoteIn the first and second test cases, you can choose the number $$$m=4$$$ and multiply the second number ($$$b=5$$$) by $$$4$$$.In the first test case the resulting sequence will be $$$[10, 20, 30]$$$. This is an AP with a difference $$$d=10$$$.In the second test case the resulting sequence will be $$$[30, 20, 10]$$$. This is an AP with a difference $$$d=-10$$$.In the third test case, you can choose $$$m=1$$$ and multiply any number by $$$1$$$. The resulting sequence will be $$$[1, 2, 3]$$$. This is an AP with a difference $$$d=1$$$.In the fourth test case, you can choose $$$m=9$$$ and multiply the first number ($$$a=1$$$) by $$$9$$$. The resulting sequence will be $$$[9, 6, 3]$$$. This is an AP with a difference $$$d=-3$$$.In the fifth test case, it is impossible to make an AP.

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 a = readln.splitter.map!(to!long).array;
    long a0 = a[1] - (a[2] - a[1]);
    if (a0 % a[0] == 0 && a0 / a[0] > 0) {
      writeln("YES");
      continue;
    }
    if ((a[0] + a[2]) % 2 == 0 &&
        (((a[0] + a[2]) / 2) % a[1] == 0) &&
        (((a[0] + a[2]) / 2) / a[1] > 0)) {
      writeln("YES");
      continue;
    }
    long a2 = a[1] + (a[1] - a[0]);
    if (a2 % a[2] == 0 && a2 / a[2] > 0) {
      writeln("YES");
      continue;
    }
    writeln("NO");
  }
}

void main() { runSolver(); }

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

  auto solve() {
    void subSolve(long[] nums) {
      bool ans;

      long[] candidates = [
        nums[1] - (nums[2] - nums[1]),
        (nums[0] + nums[2]) % 2 == 0 ? (nums[0] + nums[2]) / 2 : -1,
        nums[1] + (nums[1] - nums[0])
      ];

      // [nums, candidates].deb;
      foreach(i, cand; candidates) {
        if (cand <= 0) continue;

        ans |= (cand % nums[i] == 0);
      }

      writeln(ans ? "YES" : "NO");
    }

    foreach(i; 0..QN) {
      subSolve(scan!long(3));
    }
  }

  outputForAtCoder(&solve);
}

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

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

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable a = (){ int x; readf!"%s"(x); return x; }();
        immutable b = (){ int x; readf!" %s"(x); return x; }();
        immutable c = (){ int x; readf!" %s\n"(x); return x; }();

        if ((b + b - a) % c == 0 && (b + b - a) / c > 0)
            writeln("YES");
        else if ((a + c) % 2 == 0 && (a + c) / 2 % b == 0 && (a + c) / 2 / b > 0)
            writeln("YES");
        else if ((b - (c - b)) % a == 0 && (b - (c - b)) / a > 0)
            writeln("YES");
        else
            writeln("NO");
    }
}
// ""


The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i < m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of vertexes in a graph.  The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$) — the number of vertexes in the path.  The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$) — the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i < m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.

In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$) — the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.

NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.

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

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

    auto g = new string[] (n+1);
    foreach (i; 1 .. n+1) {
        g[i] = "0" ~ readln.chomp;
    }

    debug { g.writeln; }

    immutable int INF = 10 ^^ 9 + 7;
    auto fw = new int[][] (n+1, n+1);
    foreach (i; 1 .. n+1) {
        foreach (j; 1 .. n+1) {
            fw[i][j] = g[i][j] == '1' ? 1 : INF;
        }

        fw[i][i] = 0;
    }

    foreach (k; 1 .. n+1) {
        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. n+1) {
                fw[i][j] = min(fw[i][j], fw[i][k] + fw[k][j]);
            }
        }
    }

    debug { fw.each!writeln; }

    int m;
    readf("%s", &m);
    readln;

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

    int[] ans;
    ans ~= a.front;

    foreach (p; 1 .. a.length-1) {
        if (fw[ans.back][a[p+1]] < fw[ans.back][a[p]] + fw[a[p]][a[p+1]]) {
            ans ~= a[p];
        }
    }

    ans ~= a.back;

    ans.length.writeln;
    ans.map!(to!string).join(" ").writeln;
}

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

string FMT_F = "%.10f";

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

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

//long mod = 10^^9 + 7;
long mod = 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 main()
{
	auto n = RD!int;
	auto edges = new int[][](n);
	foreach (i; 0..n)
	{
		auto s = RD!string;
		foreach (j; 0..n)
		{
			if (s[j] == '1')
			{
				edges[i] ~= j;
			}
		}
	}
	auto m = RD!int;
	auto p = RDA!int(-1);

	long[int] memo;
	long search(int start, int goal)
	{
		auto key = start * 1000 + goal;
		if (memo.get(key, -1) != -1) return memo[key];

		int[] open = [start];
		auto dist = new long[](n);
		dist[] = long.max;
		dist[start] = 0;
		while (!open.empty)
		{
			auto from = open.front; open.popFront;
			foreach (to; edges[from])
			{
				auto d = dist[from] + 1;
				if (d < dist[to])
				{
					dist[to] = d;
					if (to == goal)
					{
						memo[key] = dist[to];
						return dist[to];
					}
					open ~= to;
				}
			}
		}
		return -1;
	}

	long[] ans = [p[0]+1];
	int i, j = 1;
	long last = search(p[0], p[1]);
	while (j < m-1)
	{
		auto d1 = last + search(p[j], p[j+1]);
		auto d2 = search(p[i], p[j+1]);
		if (d2 >= d1) // 省略可能な場合
		{
			++j;
			last = d1;
		}
		else
		{
			ans ~= [p[j]+1];
			i = j;
			++j;
			last = d1 - last;
		}
	}
	ans ~= p[$-1]+1;

	writeln(ans.length);
	ans.map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}

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

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

    auto g = new string[] (n+1);
    foreach (i; 1 .. n+1) {
        g[i] = "0" ~ readln.chomp;
    }

    debug { g.writeln; }

    immutable int INF = 10 ^^ 9 + 7;
    auto fw = new int[][] (n+1, n+1);
    foreach (i; 1 .. n+1) {
        foreach (j; 1 .. n+1) {
            fw[i][j] = g[i][j] == '1' ? 1 : INF;
        }

        fw[i][i] = 0;
    }

    foreach (k; 1 .. n+1) {
        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. n+1) {
                fw[i][j] = min(fw[i][j], fw[i][k] + fw[k][j]);
            }
        }
    }

    int m;
    readf("%s", &m);
    readln;

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

    int[] ans;
    ans ~= a.front;

    foreach (p; 1 .. a.length-1) {
        if (fw[a[p-1]][a[p+1]] < fw[a[p-1]][a[p]] + fw[a[p]][a[p+1]]) {
            ans ~= a[p];
        }
    }

    ans ~= a.back;

    ans.length.writeln;
    ans.map!(to!string).join(" ").writeln;
}

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

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

    auto g = new string[] (n+1);
    foreach (i; 1 .. n+1) {
        g[i] = "0" ~ readln.chomp;
    }

    debug { g.writeln; }

    int m;
    readf("%s", &m);
    readln;

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

    int[] ans;
    ans ~= a.front;

    foreach (p; 1 .. a.length-1) {
        if (a[p-1] == a[p+1] || g[a[p-1]][a[p+1]] == '1') {
            ans ~= a[p];
        }
    }

    ans ~= a.back;

    ans.length.writeln;
    ans.map!(to!string).join(" ").writeln;
}


William has two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ items.For some segments $$$l..r$$$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $$$i$$$ from $$$l$$$ to $$$r$$$ holds $$$a_i = b_i$$$.To perform a balancing operation an even number of indices must be selected, such that $$$l \le pos_1 < pos_2 < \dots < pos_k \le r$$$. Next the items of array a at positions $$$pos_1, pos_3, pos_5, \dots$$$ get incremented by one and the items of array b at positions $$$pos_2, pos_4, pos_6, \dots$$$ get incremented by one.William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.

The first line contains a two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$), the size of arrays $$$a$$$ and $$$b$$$ and the number of segments. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^9)$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(0 \le b_i \le 10^9)$$$. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i < r_i \le n)$$$, the edges of segments.

For each segment output a single number — the minimal number of balancing operations needed or "-1" if it is impossible to equalize segments of arrays.

NoteFor the first segment from $$$2$$$ to $$$6$$$ you can do one operation with $$$pos = [2, 3, 5, 6]$$$, after this operation the arrays will be: $$$a = [0, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$6$$$ after this operation.For the second segment from $$$1$$$ to $$$7$$$ you can do three following operations:   $$$pos = [1, 3, 5, 6]$$$  $$$pos = [1, 7]$$$  $$$pos = [2, 7]$$$ After these operations, the arrays will be: $$$a = [2, 2, 2, 9, 4, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 2, 7, 8]$$$. Arrays are equal on a segment from $$$1$$$ to $$$7$$$ after these operations.For the third segment from $$$2$$$ to $$$4$$$ you can do one operation with $$$pos = [2, 3]$$$, after the operation arrays will be: $$$a = [0, 2, 2, 9, 3, 2, 7, 5]$$$, $$$b = [2, 2, 2, 9, 4, 1, 5, 8]$$$. Arrays are equal on a segment from $$$2$$$ to $$$4$$$ after this operation.It is impossible to equalize the fourth and the fifth segment.

immutable multi = false;

void solve(int tc)
{
	auto n = readInt!int;
	auto q = readInt!int;
	debug writeln(n, " ", q);
	auto a = ma(n, readInt!int);
	auto b = ma(n, readInt!int);
	auto d = new int[](n);
	foreach(i, ref di; d) di = a[i] - b[i];
	auto ssum = new long[](n + 1);
	ssum[n] = 0;
	foreach_reverse(i; 0 .. n)
	{
		ssum[i] = ssum[i+1] + d[i];
	}
	debug writeln("ssum ", ssum);
	auto ssumMin = Sparse!(long, min, "min")(ssum);
	auto ssumMax = Sparse!(long, max, "max")(ssum);
	debug writeln("entering queries ", q);
	foreach(qi; 0 .. q)
	{
		debug writeln(qi);
		auto l = readInt!int - 1;
		auto r = readInt!int - 1;
		debug writeln("query ", qi + 1, " ", l, " ", r);
		auto sumlr = ssum[l] - ssum[r+1];
		if (sumlr != 0)
		{
			writeln(-1);
			continue;
		}
		auto lsum = ssumMin[l .. r + 1].min - ssum[r+1];
		if (lsum < 0)
		{
			writeln(-1);
			continue;
		}
		auto hsum = ssumMax[l .. r + 1].max - ssum[r+1];
		hsum.writeln;
	}
}

// sparse table V, f, fName {{{
struct Sparse(V, alias f, string fName = "value")
{
	import std.math : log2;
	V[][] _table;
	int[] maxPow;
	this(V[] values)
	{
		auto n = values.length;
		maxPow = new int[](n + 1);
		maxPow[0] = int.min;
		maxPow[1] = 0;
		foreach(i; 2 .. n + 1)
		{
			int prev = maxPow[i - 1];
			maxPow[i] = prev;
			prev = (1 << prev);
			if (prev * 2 <= i) maxPow[i]++;
		}
		_table = new V[][](maxPow[n] + 1, n);
		_table[0][] = values[];

		debug writeln("constructing table ", maxPow[n]);
		foreach(p; 1 .. maxPow[n] + 1)
		foreach(i; 0 .. n - (1<<p) + 1)
			_table[p][i] = f(_table[p-1][i], _table[p-1][i+(1<<(p-1))]);
		debug writeln("done ");
	}
	int[2] opSlice(size_t i)(size_t start, size_t end) if (i == 0)
	{
		return [cast(int)start, cast(int)end];
	}
	auto opIndex(int[2] slice)
	{
		int sliceLen = slice[1] - slice[0];
		auto x = maxPow[sliceLen];
		auto twoX = (1 << x);
		auto p1 = _table[x][slice[0]];
		auto p2 = _table[x][slice[1] - twoX];
		struct Ans
		{
			mixin(q{V }, fName, q{;});
		}
		return Ans(f(p1, p2));
	}
}

unittest
{
	import std.algorithm;
	import std.stdio;
	alias MinQ = Sparse!(int, min, "min");
	writeln("testing");
	int[] array = [1, 2, 3, 4, -2, -2, -3, 0, 10];
	auto minQ = MinQ(array);
	foreach(i; 0 .. array.length)
	{
		foreach(j; i + 1 .. array.length + 1)
		{
			assert(minQ[i .. j].min == array[i .. j].fold!min);
		}
	}
}
// }}}

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

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

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

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

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

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

struct Record
{
	long diff;
	long lo;
	long hi;

	Record opBinary (string op) (const auto ref Record that) const
	    if (op == "+")
	{
		return Record (this.diff + that.diff,
		    min (this.lo, that.lo + this.diff),
		    max (this.hi, that.hi + this.diff));
	}
}

immutable int logHalf = 17;
immutable int half = 1 << logHalf;
immutable int limit = half << 1;

void main ()
{
	int n, q;
	while (readf !(" %s %s") (n, q) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;

		auto t = new Record [limit];
		foreach (i; 0..n)
		{
			t[half + i].diff = b[i] - a[i];
			t[half + i].lo = min (0, t[half + i].diff);
			t[half + i].hi = max (0, t[half + i].diff);
			debug {writeln (t[half + i]);}
		}
		foreach_reverse (i; 1..half)
		{
			t[i] = t[i * 2 + 0] + t[i * 2 + 1];
		}

		Record tGet (int lo, int hi)
		{
			int [] nums1;
			int [] nums2;
			for (lo += half, hi += half; lo < hi;
			    lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					nums1 ~= lo;
					lo += 1;
				}
				if (hi & 1)
				{
					hi -= 1;
					nums2 ~= hi;
				}
			}
			Record res;
			foreach (i; nums1 ~ nums2.retro.array)
			{
				res = res + t[i];
			}
			debug {writeln (res);}
			return res;
		}

		foreach (j; 0..q)
		{
			int l, r;
			readf !(" %s %s") (l, r);
			l -= 1;
			r -= 0;
			auto cur = tGet (l, r);
			writeln ((cur.diff == 0 && cur.lo >= 0) ? cur.hi : -1);
		}
	}
}