A batch of $$$n$$$ goods ($$$n$$$ — an even number) is brought to the store, $$$i$$$-th of which has weight $$$a_i$$$. Before selling the goods, they must be packed into packages. After packing, the following will be done:   There will be $$$\frac{n}{2}$$$ packages, each package contains exactly two goods;  The weight of the package that contains goods with indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) is $$$a_i + a_j$$$. With this, the cost of a package of weight $$$x$$$ is always $$$\left \lfloor\frac{x}{k}\right\rfloor$$$ burles (rounded down), where $$$k$$$ — a fixed and given value.Pack the goods to the packages so that the revenue from their sale is maximized. In other words, make such $$$\frac{n}{2}$$$ pairs of given goods that the sum of the values $$$\left \lfloor\frac{x_i}{k} \right \rfloor$$$, where $$$x_i$$$ is the weight of the package number $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$), is maximal.For example, let $$$n = 6, k = 3$$$, weights of goods $$$a = [3, 2, 7, 1, 4, 8]$$$. Let's pack them into the following packages.   In the first package we will put the third and sixth goods. Its weight will be $$$a_3 + a_6 = 7 + 8 = 15$$$. The cost of the package will be $$$\left \lfloor\frac{15}{3}\right\rfloor = 5$$$ burles.  In the second package put the first and fifth goods, the weight is $$$a_1 + a_5 = 3 + 4 = 7$$$. The cost of the package is $$$\left \lfloor\frac{7}{3}\right\rfloor = 2$$$ burles.  In the third package put the second and fourth goods, the weight is $$$a_2 + a_4 = 2 + 1 = 3$$$. The cost of the package is $$$\left \lfloor\frac{3}{3}\right\rfloor = 1$$$ burle. With this packing, the total cost of all packs would be $$$5 + 2 + 1 = 8$$$ burles.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) and $$$k$$$ ($$$1 \le k \le 1000$$$). The number $$$n$$$ — is even. The second line of each test case contains exactly $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all the test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print on a separate line a single number — the maximum possible total cost of all the packages.

NoteThe first test case is analyzed in the statement.In the second test case, you can get a total value equal to $$$4$$$ if you put the first and second goods in the first package and the third and fourth goods in the second package.In the third test case, the cost of each item is $$$0$$$, so the total cost will also be $$$0$$$.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!int(N);

      auto rbt = (new int[](0)).redBlackTree!true;
      long ans;
      foreach(a; A) {
        rbt.insert(a % K);
        ans += a / K;
      }

      int rest = N;
      while(!rbt.empty) {
        auto l = rbt.back;
        auto s = rbt.front;
        if (l + s >= K) {
          rbt.removeFront;
          rbt.removeBack;
          ans++;
          rest -= 2;
        } else {
          rbt.removeFront;
          rest--;
        }

        if (rest < 2) break;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto countModK = new long[](K);
      long ans;
      foreach(a; A) {
        countModK[a.to!int % K]++;
        ans += a / K;
      }

      long stock;
      foreach(i; 1..K) {
        if (i < K - i) stock += countModK[K - i]; else stock -= countModK[i];

        auto pick = min(stock, countModK[i]);
        ans += pick;
        stock -= pick;
        countModK[i] -= pick;
      }
      foreach(i; 1..K) if (i * 2 >= K) ans += countModK[i] / 2;

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(spread; 0..K) {
        foreach(i; 1..K) {
          auto j = spread + i;
          if (i + j < K || j >= K) continue;

          // [i, j, K].deb;
          if (i == j) {
            auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
            for(int x = taken[i]; x < taken[i] + takeSize; x += 2) {
              ans += (sorted[i][x] + sorted[i][x + 1]) / K;
            }
            taken[i] += takeSize;
          } else {
            auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
            foreach(x; 0..takeSize) {
              ans += (sorted[i][taken[i] + x] + sorted[j][taken[j] + x]) / K;
            }
            taken[i] += takeSize;
            taken[j] += takeSize;
          }
          // [ans].deb;
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[i + 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(spread; 0..K) {
        foreach(i; 1..K) {
          auto j = spread + i;
          if (i + j < K || j >= K) continue;

          // [i, j, K].deb;
          if (i == j) {
            auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
            for(int x = taken[i]; x < taken[i] + takeSize; x += 2) {
              ans += (sorted[i][x] + sorted[i][x + 1]) / K;
            }
            taken[i] += takeSize;
          } else {
            auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
            foreach(x; 0..takeSize) {
              ans += (sorted[i][taken[i] * x] + sorted[j][taken[j + x]]) / K;
            }
            taken[i] += takeSize;
            taken[j] += takeSize;
          }
          // [ans].deb;
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[i + 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(spread; 0..K) {
        foreach(i; 1..K) {
          auto j = spread + i;
          if (i + j < K || j >= K) continue;

          // [i, j, K].deb;
          if (i == j) {
            auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
            ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
            taken[i] += takeSize;
          } else {
            auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
            ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
            taken[i] += takeSize;
            taken[j] += takeSize;
          }
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[i + 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach_reverse(spread; 0..K) {
        foreach(i; 1..K) {
          auto j = spread + i;
          if (i + j < K || j >= K) continue;

          // [i, j, K].deb;
          if (i == j) {
            auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
            ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
            taken[i] += takeSize;
          } else {
            auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
            ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
            taken[i] += takeSize;
            taken[j] += takeSize;
          }
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[i + 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(i; 1..K) {
        auto minJ = max(i, K - i + 1);

        foreach(j; minJ..K) {
          // [i, j, K].deb;
          if (i == j) {
            auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
            ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
            taken[i] += takeSize;
          } else {
            auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
            ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
            taken[i] += takeSize;
            taken[j] += takeSize;
          }
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[i + 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(i; 1..K) {
        auto minJ = max(i, K - i + 1);

        foreach(j; minJ..K) {
          // [i, j, K].deb;
          if (i == j) {
            auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
            ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
            taken[i] += takeSize;
          } else {
            auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
            ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
            taken[i] += takeSize;
            taken[j] += takeSize;
          }
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[$ - i - 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;
      auto sizes = perModK.map!"a.length".array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sizes[i] - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(i; 1..K) {
        auto minJ = K - i + 1;
        if (minJ <= i) break;

        foreach(j; minJ..K) {
          auto takeSize = min(sizes[i] - taken[i], sizes[j] - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      rest.sort;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[$ - i - 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto K = scan!int;
      auto A = scan!long(N);

      auto perModK = new long[][](K, 0);
      foreach(a; A) perModK[a.to!int % K] ~= a;
      auto sorted = perModK.map!(pmk => pmk.sort).array;

      auto taken = new int[](K);
      long ans;

      // add Just Mod K = 0
      foreach(i; 0..K) {
        auto j = (K - i) % K;
        if (j < i) break;

        if (i == j) {
          auto takeSize = ((sorted[i].length - taken[i]) / 2) * 2;
          ans += sorted[i][taken[i]..taken[i] + takeSize].sum / K;
          taken[i] += takeSize;
        } else {
          auto takeSize = min(sorted[i].length - taken[i], sorted[j].length - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      // add carry overed
      foreach(i; 1..K) {
        auto minJ = K - i + 1;
        if (minJ <= i) break;

        foreach(j; minJ..K) {
          auto takeSize = min(sorted[i].length - taken[i], sorted[j].length - taken[j]);
          ans += (sorted[i][taken[i]..taken[i] + takeSize].sum + sorted[j][taken[j]..taken[j] + takeSize].sum) / K;
          taken[i] += takeSize;
          taken[j] += takeSize;
        }
      }

      auto rest = new long[](0);
      foreach(i; 0..K) rest ~= sorted[i][taken[i]..$].array;
      for(int i = 0; i < rest.length; i += 2) {
        ans += (rest[i] + rest[i + 1]) / K;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  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"];

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


Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$.  For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each test case contains exactly one line. The line consists of four integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$ ($$$0 \le x \lt y \le 10^9$$$, $$$1 \le a,b \le 10^9$$$) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.

For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position. If the two rabbits will never be at the same position simultaneously, print $$$-1$$$.

NoteThe first case is explained in the description.In the second case, each rabbit will be at position $$$3$$$ and $$$7$$$ respectively at the $$$1$$$-st second. But in the $$$2$$$-nd second they will be at $$$6$$$ and $$$4$$$ respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

import std.algorithm : max, maxElement;
import std.container : Array;
import std.stdio : stdin, write, writeln;
import std.typecons : Tuple, tuple;

struct IO {
    string readToken() {
        import std.range : empty, front, popFront, split;
        import std.stdio : readln;

        while (tokens.empty) {
            tokens = readln.split;
        }
        auto token = tokens.front;
        tokens.popFront;
        return token;
    }

    int readInt() {
        import std.conv : to;

        return readToken.to!int;
    }

    string[] tokens;
}

void main() {
    IO io;
    int T = io.readInt;
    while (T--) {
        int x = io.readInt;
        int y = io.readInt;
        int a = io.readInt;
        int b = io.readInt;
        if ((y - x) % (a + b)) {
            writeln(-1);
        }
        else {
            writeln((y - x) / (a + b));
        }
    }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		long x = rlong, y = rlong, a = rlong, b = rlong;
		if((y - x) % (a + b) == 0) ((y - x) / (a + b)).writeln;
		else (-1).writeln;
	}
}

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 x, y, a, b;

  void solve(long tc = -1)
  {
    if ((y - x) % (a + b) != 0)
      {
        writeln(-1);
      }
    else
      {
        writeln((y - x) / (a + b));
      }
  }
}

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 baseType(W)
{
  static if (isDynamicArray!W)
    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, string))
              {
                static assert(isDynamicArray!(typeOfField)
                              , " A field with dimension initialization UDA must be a dynamic array.");
                enum uda = getUDAs!(fieldSymbol, string)[0];
                mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda, q{)});
              }
            else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
              {
                pragma(msg, "Warning: You probably want to add dimension to input ", 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;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		if ((b-a)%(c+d)==0)
		{
			writeln((b-a)/(c+d));
		}
		else
		{
			writeln(-1);
		}
	}
	return 0;
}

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 = 998244353;
//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 main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto x = RD;
		auto y = RD;
		auto a = RD;
		auto b = RD;
		auto d = y - x;
		if (d % (a+b) != 0)
			ans[ti] = -1;
		else
			ans[ti] = d / (a+b);
	}

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


You are given a bracket sequence consisting of $$$n$$$ characters '(' and/or )'. You perform several operations with it.During one operation, you choose the shortest prefix of this string (some amount of first characters of the string) that is good and remove it from the string.The prefix is considered good if one of the following two conditions is satisfied:  this prefix is a regular bracket sequence;  this prefix is a palindrome of length at least two. A bracket sequence is called regular if it is possible to obtain a correct arithmetic expression by inserting characters '+' and '1' into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not.The bracket sequence is called palindrome if it reads the same back and forth. For example, the bracket sequences )), (( and )(() are palindromes, while bracket sequences (), )( and ))( are not palindromes.You stop performing the operations when it's not possible to find a good prefix. Your task is to find the number of operations you will perform on the given string and the number of remaining characters in the string.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the length of the bracket sequence. The second line of the test case contains $$$n$$$ characters '(' and/or ')' — the bracket sequence itself. It is guaranteed that the sum of $$$n$$$ over all test cases do not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).

For each test case, print two integers $$$c$$$ and $$$r$$$ — the number of operations you will perform on the given bracket sequence and the number of characters that remain in the string after performing all operations.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		ans[ti] = [0, 0];
		int i;
		while (i < n-1)
		{
			if (s[i] == ')' && s[i+1] == '(')
			{
				int pos;
				foreach (int j; i+2..n)
				{
					if (s[j] == ')')
					{
						pos = j+1;
						break;
					}
				}
				if (pos == 0) break;
				i = pos;
				++ans[ti][0];
			}
			else
			{
				i += 2;
				++ans[ti][0];
			}
		}
		ans[ti][1] = n - i;
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}


Polycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains $$$s$$$ rubles.A queue of $$$n$$$ students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If $$$a_i$$$ is positive, then the student credits that amount of money via ATM. Otherwise, the student withdraws $$$|a_i|$$$ rubles.In the beginning, the ATM is turned off and an arbitrary number of students are not served. At some point, Polycarp turns on the ATM, which has an initial amount of $$$s$$$ rubles. Then, the remaining students start queueing at the ATM. If at some point in time there is less money in the ATM than the student wants to withdraw, then the student is not served and Polycarp turns off the ATM and does not turn it on anymore.More formally, the students that are served are forming a contiguous subsequence.Polycarp wants the ATM to serve the maximum number of students. Help him in this matter. Print the numbers of the first and last student, or determine that he will not be able to serve anyone.In other words, find such a longest continuous segment of students that, starting with the sum of $$$s$$$ at the ATM, all these students will be served. ATM serves students consistently (i.e. one after another in the order of the queue).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first one contains integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 2\cdot10^5$$$; $$$0 \le s \le 10^9$$$) — the length of the $$$a$$$ array and the initial amount of rubles in the ATM. The second contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the $$$a$$$ array. Note that $$$a_i$$$ can be zero. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each line must contain the answer to the corresponding set of input data: if the answer exists, print the numbers of the first and last served student. If there is no solution, then print -1 on the line. If there are several possible answers, print any.

NoteIn the first test case, the only correct answer is 2 4, since when serving students, the number of rubles at the ATM does not become negative, and this is the maximum number of students that can be served.In the second test case, the answer is -1, as there is not enough money for any student at the ATM.In the third test case, the answer can be either 1 2 or 4 5.

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

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

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

void solve() {
    int N; long S; readf("%d %d\n", &N, &S);
    auto A = readarray!long;

    int len = 0;
    int[] ans = [0, 0];
    int l = 0, r = 0;
    long s = S;
    while (true) {
        if (r < N && s + A[r] >= 0) {
            s += A[r];
            r++;
        } else {
            if (l == r) {
                if (l == N) break;
                s = S;
                l = l + 1;
                r = r + 1;
            } else {
                s -= A[l];
                l++;
            }
        }
        if (r - l > len) {
            ans = [l, r];
            len = r - l;
        }
    }
    if (ans[0] == ans[1]) {
        writeln(-1);
    } else {
        ans[0]++;
        writefln("%(%s %)", ans);
    }
}

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, s;
		readf !(" %s %s") (n, s);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		long [] p = [0];
		foreach (ref c; a)
		{
			p ~= p.back + c;
		}

		int half = 1;
		while (half < n + 1)
		{
			half <<= 1;
		}
		auto t = new long [half * 2];
		t[] = long.max / 4;
		t[half..half + n + 1] = p[];
		foreach_reverse (i; 1..half)
		{
			t[i] = min (t[i * 2 + 0], t[i * 2 + 1]);
		}

		long getMin (int lo, int hi)
		{
			auto res = long.max / 4;
			for (lo += half, hi += half;
			    lo < hi; lo >>= 1, hi >>= 1)
			{
				if (lo & 1)
				{
					res = min (res, t[lo]);
					lo += 1;
				}
				if (hi & 1)
				{
					hi -= 1;
					res = min (res, t[hi]);
				}
			}
			return res;
		}

		int bestLo = -1;
		int bestHi = -1;
		foreach (i; 0..n)
		{
			int lo = i;
			int hi = n + 1;
			while (hi - lo > 1)
			{
				int me = (lo + hi) / 2;
				if (s < p[i] - getMin (i, me + 1))
				{
					hi = me;
				}
				else
				{
					lo = me;
				}
			}
			if (bestHi - bestLo < lo - i)
			{
				bestLo = i;
				bestHi = lo;
			}
		}

		if (bestLo == bestHi)
		{
			writeln (-1);
		}
		else
		{
			writeln (bestLo + 1, " ", bestHi);
		}
	}
}


NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $$$\operatorname{or} z$$$. Can you solve this problem too?You are given a 1-indexed array of $$$n$$$ integers, $$$a$$$, and an integer $$$z$$$. You can do the following operation any number (possibly zero) of times:  Select a positive integer $$$i$$$ such that $$$1\le i\le n$$$. Then, simutaneously set $$$a_i$$$ to $$$(a_i\operatorname{or} z)$$$ and set $$$z$$$ to $$$(a_i\operatorname{and} z)$$$. In other words, let $$$x$$$ and $$$y$$$ respectively be the current values of $$$a_i$$$ and $$$z$$$. Then set $$$a_i$$$ to $$$(x\operatorname{or}y)$$$ and set $$$z$$$ to $$$(x\operatorname{and}y)$$$. Here $$$\operatorname{or}$$$ and $$$\operatorname{and}$$$ denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in $$$a$$$ after any number (possibly zero) of operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$z$$$ ($$$1\le n\le 2000$$$, $$$0\le z<2^{30}$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$,$$$a_2$$$,$$$\ldots$$$,$$$a_n$$$ ($$$0\le a_i<2^{30}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case of the sample, one optimal sequence of operations is:  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\operatorname{or}3)=3$$$ and $$$z$$$ becomes $$$(3\operatorname{and}3)=3$$$.  Do the operation with $$$i=2$$$. Now $$$a_2$$$ becomes $$$(4\operatorname{or}3)=7$$$ and $$$z$$$ becomes $$$(4\operatorname{and}3)=0$$$.  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\operatorname{or}0)=3$$$ and $$$z$$$ becomes $$$(3\operatorname{and}0)=0$$$. After these operations, the sequence $$$a$$$ becomes $$$[3,7]$$$, and the maximum value in it is $$$7$$$. We can prove that the maximum value in $$$a$$$ can never exceed $$$7$$$, so the answer is $$$7$$$.In the fourth test case of the sample, one optimal sequence of operations is:  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(7\operatorname{or}7)=7$$$ and $$$z$$$ becomes $$$(7\operatorname{and}7)=7$$$.  Do the operation with $$$i=3$$$. Now $$$a_3$$$ becomes $$$(30\operatorname{or}7)=31$$$ and $$$z$$$ becomes $$$(30\operatorname{and}7)=6$$$.  Do the operation with $$$i=5$$$. Now $$$a_5$$$ becomes $$$(27\operatorname{or}6)=31$$$ and $$$z$$$ becomes $$$(27\operatorname{and}6)=2$$$.

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

void solve()
{
    ulong n, z;
    readf!(" %s %s")(n, z);
    readln;
    readln.splitter
        .map!(to!int)
        .map!(x => x | z)
        .maxElement!()
        .writeln;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

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

void solve()
{
    ulong n, z;
    readf!(" %s %s")(n, z);
    readln;
    auto arr = readln.splitter.map!(to!int);
    arr.map!(x => x | z).maxElement!().writeln;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

import std;

void main(){
	int t=readln().strip.to!int;
	foreach(_;0..t){
		auto z=readln().strip.split.to!(int[])[1];
		auto a=readln().strip.split.to!(int[]);
		writeln(a.map!(x=>x|z).reduce!max);
	}
}

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 Z = readLong;
        auto A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong;
        }

        long ans;
        foreach (i; 0 .. N) {
          chmax(ans, Z | A[i]);
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.

The first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands. The second line contains n space-separated integers ai (0 ≤ ai ≤ n - 1) — the statue currently placed on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≤ bi ≤ n - 1) — the desired statues of the ith island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.

Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.

NoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position.

import std.stdio;
import std.algorithm;

int[] readArray(int n) {
	int[] a = new int[n - 1];
	int start = -1;

	for (int i = 0, j = 0; i < n; i++) {
		int x;

		scanf("%d", &x);

		if (x == 1) {
			start = j;
		}

		if (x != 0) {
			a[j++] = x;
		}

	}

	int[] res = new int[n - 1];

	for (int i = 0, j = start; i < n - 1; i++, j = (j + 1) % (n - 1))
		res[i] = a[j];

	return res;
}

void main()
{
	int n;

	scanf("%d", &n);

	int[] a = readArray(n);
	int[] b = readArray(n);

	if (equal(a, b))
		printf("YES\n");
	else
		printf("NO\n");
}


Alice has an integer sequence $$$a$$$ of length $$$n$$$ and all elements are different. She will choose a subsequence of $$$a$$$ of length $$$m$$$, and defines the value of a subsequence $$$a_{b_1},a_{b_2},\ldots,a_{b_m}$$$ as $$$$$$\sum_{i = 1}^m (m \cdot a_{b_i}) - \sum_{i = 1}^m \sum_{j = 1}^m f(\min(b_i, b_j), \max(b_i, b_j)),$$$$$$ where $$$f(i, j)$$$ denotes $$$\min(a_i, a_{i + 1}, \ldots, a_j)$$$.Alice wants you to help her to maximize the value of the subsequence she choose.A sequence $$$s$$$ is a subsequence of a sequence $$$t$$$ if $$$s$$$ can be obtained from $$$t$$$ by deletion of several (possibly, zero or all) elements.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 4000$$$). The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i < 2^{31}$$$).

NoteIn the first example, Alice can choose the subsequence $$$[15, 2, 18, 13]$$$, which has the value $$$4 \cdot (15 + 2 + 18 + 13) - (15 + 2 + 2 + 2) - (2 + 2 + 2 + 2) - (2 + 2 + 18 + 12) - (2 + 2 + 12 + 13) = 100$$$. In the second example, there are a variety of subsequences with value $$$176$$$, and one of them is $$$[9, 7, 12, 20, 18]$$$.

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

enum INF = 10L^^18;

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

      long[] solve(int l, int r) {
        auto ret = new long[r - l + 1];
        if (l < r) {
          int im = -1;
          foreach (i; l .. r) {
            if (!~im || A[im] > A[i]) {
              im = i;
            }
          }
          const resL = solve(l, im);
          const resR = solve(im + 1, r);
          ret[] = -INF;
          foreach (x; 0 .. im - l + 1) foreach (y; 0 .. r - im) {
            chmax(ret[x + y], resL[x] + resR[y] - A[im] * 2L * x * y);
            chmax(ret[x + y + 1], resL[x] + resR[y] - A[im] * 2L * (x * y + x + y) + A[im] * (M - 1));
          }
        }
        return ret;
      }
      const auto ans = solve(0, N);
      writeln(ans[M]);
    }
  } catch (EOFException e) {
  }
}


Kolya got an integer array $$$a_1, a_2, \dots, a_n$$$. The array can contain both positive and negative integers, but Kolya doesn't like $$$0$$$, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be $$$0$$$. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $$$0$$$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $$$0$$$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of elements in Kolya's array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^{9} \le a_i \le 10^{9}, a_i \neq 0$$$) — the description of Kolya's array.

Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

NoteConsider the first example. There is only one subsegment with the sum $$$0$$$. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer $$$1$$$ between second and third elements of the array.There are no subsegments having sum $$$0$$$ in the second example so you don't need to do anything.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    ll[] pref = [0];
    foreach(el; arr){
        pref ~= el + pref.back;
    }
    int[long] vis;
    /* bool[long] seen; */
    foreach(el; pref){
        ++vis[el];
    }
    int[long] lastseen;
    ll cnt = 0;
    int lasti = -1;
    foreach(i; 0..n+1){
        assert(pref[i] in vis);
        if(vis[pref[i]] > 1){
            int prev = lastseen.get(pref[i], -1);
            if(lasti < prev){
                ++cnt;
                lasti = i - 2;
            }
        }
        lastseen[pref[i]] = i;
        /* writeln(lasti, " ", lastseen); */
    }
    writeln(cnt);
}

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

// Vicfred
// https://codeforces.com/contest/1426/problem/D
// greedy
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

void main () {
    long n = readln.chomp.to!long;

    long[] a = readln.split.map!(to!long).array;

    auto rbt = new RedBlackTree!long;
    long prefix = 0L;
    long ans = 0L;

    rbt.insert(0L);

    foreach(x; a) {
        prefix += x;
        if(prefix in rbt) {
            ans += 1L;
            rbt = new RedBlackTree!long;
            rbt.insert(0L);
            prefix = x;
        }
        rbt.insert(prefix);
    }

    ans.writeln;

}

// Vicfred
// https://codeforces.com/contest/1426/problem/D
// greedy
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.stdio;
import std.string;

void main () {
    long n = readln.chomp.to!long;

    long[] a = readln.split.map!(to!long).array;

    auto rbt = new RedBlackTree!long;
    long prefix = 0L;
    long ans = 0L;

    rbt.insert(0L);

    foreach(x; a) {
        prefix += x;
        if(prefix in rbt) {
            ans += 1L;
            rbt.insert(0L);
            prefix = x;
        }
        rbt.insert(prefix);
    }

    ans.writeln;

}


You are given two strings $$$s$$$ and $$$t$$$, both consisting only of lowercase Latin letters.The substring $$$s[l..r]$$$ is the string which is obtained by taking characters $$$s_l, s_{l + 1}, \dots, s_r$$$ without changing the order.Each of the occurrences of string $$$a$$$ in a string $$$b$$$ is a position $$$i$$$ ($$$1 \le i \le |b| - |a| + 1$$$) such that $$$b[i..i + |a| - 1] = a$$$ ($$$|a|$$$ is the length of string $$$a$$$).You are asked $$$q$$$ queries: for the $$$i$$$-th query you are required to calculate the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

The first line contains three integer numbers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^3$$$, $$$1 \le q \le 10^5$$$) — the length of string $$$s$$$, the length of string $$$t$$$ and the number of queries, respectively. The second line is a string $$$s$$$ ($$$|s| = n$$$), consisting only of lowercase Latin letters. The third line is a string $$$t$$$ ($$$|t| = m$$$), consisting only of lowercase Latin letters. Each of the next $$$q$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the arguments for the $$$i$$$-th query.

Print $$$q$$$ lines — the $$$i$$$-th line should contain the answer to the $$$i$$$-th query, that is the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

NoteIn the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto Q = s[2];

    auto S = readln.chomp;
    auto T = readln.chomp;
    auto A = new int[](N+1);

    foreach (i; 0..N-M+1) {
        bool ok = true;
        foreach (j; i..i+M) {
            if (S[j] != T[j-i]) {
                ok = false;
                break;
            }
        }
        if (ok) A[i+1] += 1;
    }

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

    while (Q--) {
        s = readln.split.map!(to!int);
        int l = s[0] - 1;
        int r = s[1] - M;
        if (l > r)
            writeln(0);
        else
            writeln(A[r+1] - A[l]);
    }

}

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

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

    auto s = readln.chomp;
    auto t = readln.chomp;

    auto cnt = new int [] (n+1);
    while (s.canFind(t)) {
        s = s.find(t);

        debug { s.writeln; }

        ++cnt[n - s.length + 1];

        s = s.dropOne();
    }

    cnt = cnt.cumulativeFold!((a, b) => a + b).array;

    debug { cnt.writeln; }

    while (q--) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        if (b - (a-1) < t.length) {
            writeln(0);
            continue;
        }

        writeln(cnt[b - t.length + 1] - cnt[a-1]);
    }
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n, m, q; rd(n, m, q);
  auto s=readln.chomp.to!(char[]);
  auto t=readln.chomp.to!(char[]);

  auto ok=new bool[](s.length+1);
  for(int i=0; i+t.length<=s.length; i++){
    if(s[i..(i+t.length)]==t) ok[i]=true;
  }
  while(q--){
    int l, r; rd(l, r);
    l--; r--;
    int w=0;
    for(int i=l; i<=r; i++){
      if(ok[i] && i+t.length-1<=r) w++;
    }
    writeln(w);
  }
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $$$a$$$ and $$$b$$$ using the following algorithm:  If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.  The numbers are processed from right to left (that is, from the least significant digits to the most significant).  In the first step, she adds the last digit of $$$a$$$ to the last digit of $$$b$$$ and writes their sum in the answer.  At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer.  For example, the numbers $$$a = 17236$$$ and $$$b = 3465$$$ Tanya adds up as follows:$$$$$$ \large{ \begin{array}{r} + \begin{array}{r} 17236\\ 03465\\ \end{array} \\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} $$$$$$  calculates the sum of $$$6 + 5 = 11$$$ and writes $$$11$$$ in the answer.  calculates the sum of $$$3 + 6 = 9$$$ and writes the result to the left side of the answer to get $$$911$$$.  calculates the sum of $$$2 + 4 = 6$$$ and writes the result to the left side of the answer to get $$$6911$$$.  calculates the sum of $$$7 + 3 = 10$$$, and writes the result to the left side of the answer to get $$$106911$$$.  calculates the sum of $$$1 + 0 = 1$$$ and writes the result to the left side of the answer and get $$$1106911$$$. As a result, she gets $$$1106911$$$.You are given two positive integers $$$a$$$ and $$$s$$$. Find the number $$$b$$$ such that by adding $$$a$$$ and $$$b$$$ as described above, Tanya will get $$$s$$$. Or determine that no suitable $$$b$$$ exists.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of a single line containing two positive integers $$$a$$$ and $$$s$$$ ($$$1 \le a \lt s \le 10^{18}$$$) separated by a space.

For each test case print the answer on a separate line. If the solution exists, print a single positive integer $$$b$$$. The answer must be written without leading zeros. If multiple answers exist, print any of them. If no suitable number $$$b$$$ exists, output -1.

NoteThe first test case is explained in the main part of the statement.In the third test case, we cannot choose $$$b$$$ that satisfies the problem statement.

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;

long fancy_sub(long s, long a)
{
  long ans;
  long mult = 1;
  while (a > 0 || s > 0) {
    long digit_a = a % 10;
    a /= 10;
    long digit_s = s % 10;
    s /= 10;
    if (digit_s < digit_a) {
      if (s % 10 != 1)
        return -1;
      digit_s += (s % 10) * 10;
      s /= 10;
      if (digit_s < digit_a)
        return -1;
    }
    ans += (digit_s - digit_a) * mult;
    mult *= 10;
  }
  return ans;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long a, s;
    readf!" %d %d "(a, s);
    writeln(fancy_sub(s, a));
  }
}