You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.

The first line contains three space-separated integers n (1 ≤ n ≤ 103), k1 and k2 (0 ≤ k1 + k2 ≤ 103, k1 and k2 are non-negative) — size of arrays and number of operations to perform on A and B respectively. Second line contains n space separated integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — array A. Third line contains n space separated integers b1, b2, ..., bn ( - 106 ≤ bi ≤ 106)— array B.

Output a single integer — the minimum possible value of  after doing exactly k1 operations on array A and exactly k2 operations on array B.

NoteIn the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)2 + (2 - 3)2 = 2. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)2 + (2 - 2)2 = 0. This is the minimum possible error obtainable.In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)2 + (4 - 4)2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)2 + (4 - 5)2 = 1.

/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv, std.math;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n, k1, k2;
    sc.read(n, k1, k2);
    long[] a, b;
    sc.read(a, b);
    foreach (i; 0..n) a[i] = abs(a[i]-b[i]);

    foreach (ph; 0..k1+k2) {
        int i = a.maxIndex.to!int;
        a[i] = abs(a[i]-1);
    }

    writeln(a.map!"a*a".sum);
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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

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

void main()
{
  int n, k1, k2; readV(n, k1, k2);
  int[] a; readA(n, a);
  int[] b; readA(n, b);

  auto c = new int[](n);
  foreach (i; 0..n) c[i] = (a[i]-b[i]).abs;
  auto h = c.heapify;

  foreach (_; 0..k1+k2) {
    auto hi = h.front;
    h.replaceFront((hi-1).abs);
  }

  auto ans = 0L;
  foreach (hi; h)
    ans += hi.to!long ^^ 2;

  writeln(ans);
}

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

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

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

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

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

      auto ds = new long[N];
      foreach (i; 0 .. N) {
        ds[i] = abs(B[i] - A[i]);
      }
      const dsSum = ds.sum;
      long ans;
      if (KA + KB >= dsSum) {
        ans = (KA + KB - dsSum) % 2;
      } else {
        foreach (k; 0 .. KA + KB) {
          const im = ds.maxIndex;
          --ds[im];
        }
        foreach (i; 0 .. N) {
          ans += ds[i]^^2;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv, std.math;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n, k1, k2;
    sc.read(n, k1, k2);
    int[] a, b;
    sc.read(a, b);
    foreach (i; 0..n) a[i] = abs(a[i]-b[i]);

    foreach (ph; 0..k1+k2) {
        int i = a.maxIndex.to!int;
        a[i] = abs(a[i]-1);
    }

    writeln(a.map!"a*a".sum);
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/


Today, as a friendship gift, Bakry gave Badawy $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ and challenged him to choose an integer $$$X$$$ such that the value $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$ is minimum possible, where $$$\oplus$$$ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.

The first line contains integer $$$n$$$ ($$$1\le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$).

Print one integer — the minimum possible value of $$$\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$$$.

NoteIn the first sample, we can choose $$$X = 3$$$.In the second sample, we can choose $$$X = 5$$$.

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

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

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

    auto tr = new int[int][] (1);
    int sz = 0;

    void add(int x) {
        debug { tr[0].writeln; }
        int nd = 0;
        foreach_reverse (b; 0 .. 30) {
            int dir = (x & (1 << b)) ? 1 : 0;
            if (dir !in tr[nd]) {
                int[int] dict;
                tr ~= dict;
                tr[nd][dir] = ++sz;
            }

            nd = tr[nd][dir];
        }
    }

    foreach (e; arr) {
        add(e);
    }

    debug { tr.writeln; }

    int dfs(int v, int lvl) {
        if (tr[v].empty()) { return 0; }

        if (tr[v].length == 1) {
            auto k = tr[v].keys[0];
            return dfs(tr[v][k], lvl-1);
        }

        return (1 << lvl)
            + min(dfs(tr[v][0], lvl-1), dfs(tr[v][1], lvl-1));
    }

    auto ans = dfs(0, 29);

    ans.writeln;
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto rd = new InputReader ();
  immutable n = rd.next!uint ();
  auto a = rd.nextA!uint (n);
  sort (a);
  a.length -= a.uniq.copy (a).length;
  immutable m = a.length.to!int;
  uint f (int l, int r, int k, uint start) {
    if (k < 0) return 0;
    debug stderr.writefln ("f %d %d %d %d",l, r, k, start);
    immutable uint mask = 1 << k;
    auto e = assumeSorted (a[l .. r]);
    immutable int mid = l + e.lowerBound (start + mask).length.to!int;
    debug stderr.writeln ("mid = ", mid);
    if (l < mid && mid < r) {
      return mask + min (f (l, mid, k - 1, start), f (mid, r, k - 1, start + mask));
    }
    return f (l, r, k - 1, (r == mid) ? start : (start + mask));
  }
  writeln (f (0, m, 29, 0U));
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(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);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(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 = E.init)
{
  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;
}

class TreeNode
{
  TreeNode[2] children = [null, null];
  int noChildren()
  {
    return (children[0] !is null) + (children[1] !is null);
  }
  void insert(string str)
  {
    if (str.length == 0) return;
    size_t i = str[0] == '0'? 0 : 1;
    if (children[i] is null)
      children[i] = new TreeNode();
    children[i].insert(str[1 .. $]);
  }
}

int minans = int.max;
void dfs(TreeNode treeNode, int digit, int accans)
{
  int noChildren = treeNode.noChildren;
  if (noChildren == 0)
    {
      minans = min(accans, minans);
    }
  else if (noChildren == 1)
    {
      if (treeNode.children[0] !is null)
        dfs(treeNode.children[0], digit - 1, accans);
      else
        dfs(treeNode.children[1], digit - 1, accans);
    }
  else
    {
      dfs(treeNode.children[0], digit - 1, accans | (1 << digit));
      dfs(treeNode.children[1], digit - 1, accans | (1 << digit));
    }
}

void main()
{
  int n;
  read(n);
  string toString(int n)
  {
    char[] res = new char[30];
    foreach(i; 0 .. 30)
      {
        res[i] = ((n & (1 << (29 - i))) == 0)? '0' : '1';
      }
    return res.idup;
  }
  auto a = makeArray!string(n, toString(next!int));
  TreeNode root = new TreeNode();
  foreach(ai; a)
    root.insert(ai);
  dfs(root, 29, 0);
  writeln(minans);
}

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//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 main()
{
	auto n = RD!int;
	auto a = RDA;

	bool[long][32] set;

	foreach (i; 0..32)
	{
		foreach (j; 0..n)
		{
			auto x = a[j] >> (31 - i);
			set[i][x] = true;
		}
	}

	long ans = long.max;
	foreach (i; 0..n)
	{
		long tmp;
		foreach (j; 0..32)
		{
			auto x = a[i] >> (31 - j);
			x ^= 1;
			if (set[j].get(x, false))
			{
				tmp += 1L << (31 - j);
			}
		}
		debug writeln(tmp);
		ans.chmin(tmp);
	}

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

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto rd = new InputReader ();
  immutable n = rd.next!uint ();
  auto a = rd.nextA!uint (n);
  sort (a);
  a.length -= a.uniq.copy (a).length;
  immutable m = a.length.to!int;
  uint f (int l, int r, int k, uint start) {
    if (k == 0) return 0;
    debug stderr.writefln ("f %d %d %d %d",l, r, k, start);
    immutable uint mask = 1 << k;
    auto e = assumeSorted (a[l .. r]);
    immutable int mid = l + e.lowerBound (start + mask).length.to!int;
    debug stderr.writeln ("mid = ", mid);
    if (l < mid && mid < r) {
      return mask + min (f (l, mid, k - 1, start), f (mid, r, k - 1, start + mask));
    }
    return f (l, r, k - 1, (r == mid) ? start : (start + mask));
  }
  writeln (f (0, m, 29, 0U));
}


Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally:   If it is the first move, he chooses any element and deletes it;  If it is the second or any next move:   if the last deleted element was odd, Polycarp chooses any even element and deletes it;  if the last deleted element was even, Polycarp chooses any odd element and deletes it.   If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements of $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible sum of non-deleted elements of the array after end of the game.

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

immutable long MOD = 10^^9 + 7;

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

    auto X = A.filter!(a => a % 2 == 0).array;
    auto Y = A.filter!(a => a % 2 == 1).array;
    X.sort!"a > b";
    Y.sort!"a > b";

    long ans = 0;
    long tmp = 0;

    for (int i = 0; i < X.length && i < Y.length; ++i) {
        ans += X[i] + Y[i];
    }

    if (X.length > Y.length) {
        ans += X[Y.length];
    } else if (X.length < Y.length) {
        ans += Y[X.length];
    }

    ans = A.sum - ans;
    ans.writeln;
}


Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).

Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.

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

void main() {
    int N, M, Q; readf("%d %d %d\n", &N, &M, &Q);
    int H = N;
    int W = M;
    auto F = new char[][](H, W);
    foreach (i; 0 .. H) {
        F[i] = readln.chomp.dup;
    }
    auto L = new char[H*W]; {
        foreach (x; 0 .. W) {
            foreach (y; 0 .. H) {
                L[x*H + y] = F[y][x];
            }
        }
    }
    int C = 0; {
        foreach (y; 0 .. H) {
            foreach (x; 0 .. W) {
                C += (F[y][x] == '*');
            }
        }
    }
    int s = 0; {
        foreach (y; 0 .. H) {
            foreach (x; 0 .. W) {
                if (F[y][x] == '*' && x * H + y < C) {
                    s++;
                }
            }
        }
    }

    foreach (q; 0 .. Q) {
        int Y, X; readf("%d %d\n", &Y, &X);
        Y--; X--;
        int i = X * H + Y;
        if (L[i] == '*') {
            // remove
            if (i < C) {
                L[i] = '.';
                s--;
                C--;
                if (L[C] == '*') s--;
            } else {
                L[i] = '.';
                C--;
                if (L[C] == '*') s--;
            }
        } else {
            // add
            if (i < C) {
                L[i] = '*';
                s++;
                if (L[C] == '*') s++;
                C++;
            } else {
                L[i] = '*';
                if (L[C] == '*') s++;
                C++;
            }
        }
        writeln(C - s);
    }
}


Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.

The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.

Print m integers — the i-th integer denotes value v for sequence a after the i-th query.

NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation

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

class SegmentTree(T = int, alias op) {
  private:
  T [] t;
  size_t n;
  final void build () pure nothrow @nogc {
    foreach_reverse (i; 1 .. n) {
      immutable k = i << 1;
      t[i] = op (t[k], t[k+1]);
    }
  }
  public:
  final void update (size_t p, T v) pure nothrow @nogc {
    for (t[p += n] = v; p > 1; p >>= 1) {
      t[p>>1] = op (t[p], t[p ^ 1]);
    }
  }
  final T reduce (size_t l, size_t r) const pure nothrow @nogc {
    T res;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res = op (res, t[l++]);
      }
      if (r & 1) {
        res = op (t[--r], res);
      }
    }
    return res;
  }
  this (const T[] a) pure nothrow {
    n = a.length;
    t = new T[n];
    t ~= a;
    build ();
  }
}

void main() {
  int n, m;
  readf (" %d %d", &n, &m);
  auto a = new uint[1<<n];
  foreach (t; 0 .. 1<<n) {
    readf (" %d", &a[t]);
  }
  enum uint q = 0x8000_0000;
  auto st = new SegmentTree!(uint, (x, y) => (x & q) ? (x ^ y) & (q - 1) : (x | y | q)) (a);
  foreach (t; 0 .. m) {
    int i;
    uint v;
    readf (" %d %d", &i, v);
    --i;
    st.update (i, v);
    writeln (st.reduce (0, 1 << n) & (q - 1));
  }
}

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

class SegmentTree(T = int, alias op) {
  private:
  T [] t;
  size_t n;
  final void build () pure nothrow @nogc {
    foreach_reverse (i; 1 .. n) {
      immutable k = i << 1;
      t[i] = op (t[k], t[k+1]);
    }
  }
  public:
  final T opIndexAssign (T value, size_t index) {
    for (t[index += n] = value; index > 1; index >>= 1) {
      t[index>>1] = op (t[index], t[index ^ 1]);
    }
    return value;
  }
  final T reduce (size_t l, size_t r) const pure nothrow @nogc {
    T res;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res = op (res, t[l++]);
      }
      if (r & 1) {
        res = op (t[--r], res);
      }
    }
    return res;
  }
  this (const T[] a) pure nothrow {
    n = a.length;
    t = new T[n];
    t ~= a;
    build ();
  }
}

void main() {
  int n, m;
  readf (" %d %d", &n, &m);
  auto a = new uint[1<<n];
  foreach (t; 0 .. 1<<n) {
    readf (" %d", &a[t]);
  }
  enum uint q = 0x8000_0000;
  auto st = new SegmentTree!(uint, (x, y) => (x & q) ? (x ^ y) & (q - 1) : (x | y | q)) (a);
  foreach (t; 0 .. m) {
    int i;
    uint v;
    readf (" %d %d", &i, v);
    st[i-1] = v;
    writeln (st.reduce (0, 1 << n) & (q - 1));
  }
}


A card pyramid of height $$$1$$$ is constructed by resting two cards against each other. For $$$h>1$$$, a card pyramid of height $$$h$$$ is constructed by placing a card pyramid of height $$$h-1$$$ onto a base. A base consists of $$$h$$$ pyramids of height $$$1$$$, and $$$h-1$$$ cards on top. For example, card pyramids of heights $$$1$$$, $$$2$$$, and $$$3$$$ look as follows:  You start with $$$n$$$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^9$$$) — the number of cards. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^9$$$.

For each test case output a single integer — the number of pyramids you will have constructed in the end.

NoteIn the first test, you construct a pyramid of height $$$1$$$ with $$$2$$$ cards. There is $$$1$$$ card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height $$$2$$$, with no cards remaining.In the third test, you build one pyramid of height $$$3$$$, with no cards remaining.In the fourth test, you build one pyramid of height $$$3$$$ with $$$9$$$ cards remaining. Then you build a pyramid of height $$$2$$$ with $$$2$$$ cards remaining. Then you build a final pyramid of height $$$1$$$ with no cards remaining.In the fifth test, one card is not enough to build any pyramids.

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

void main()
{
    auto T = readln.chomp.to!int;
    auto cs = new long[](25820);
    cs[1] = 2;
    foreach (i; 2..25820) {
        cs[i] = cs[i-1] + (i-1) * 3 + 2;
    }

    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;

        int res;
        while (N >= 2) {
            ++res;
            if (N >= cs[$-1]) {
                N -= cs[$-1];
            } else {
                int l = 1, r = cs.length.to!int-1;
                while (l+1 < r) {
                    auto m = (l+r)/2;
                    if (N >= cs[m]) {
                        l = m;
                    } else {
                        r = m;
                    }
                }
                N -= cs[l];
            }
        }
        writeln(res);
    }
}

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

int tri (int n)
{
	return n * (n + 1) / 2;
}

int f (int n)
{
	return tri (n) * 3 - n;
}

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		int k = 0;
		while (f (k) <= n)
		{
			k += 1;
		}
		int res = 0;
		while (k > 0)
		{
			while (f (k) <= n)
			{
				n -= f (k);
				res += 1;
			}
			k -= 1;
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		while (true)
		{
			auto r = binarySearch!((long a) => a*(a+1) + a*(a-1)/2 <= n)(0L, 10L^^9);
			if (r == 0) break;
			++ans[ti];
			n -= r*(r+1) + r*(r-1)/2;
		}
	}

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

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

int tri (int n)
{
	return n * (n + 1) / 2;
}

int f (int n)
{
	return tri (n) * 3 - n;
}

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		int k = 0;
		while (f (k) <= n)
		{
			k += 1;
		}
		int res = 0;
		while (k > 0)
		{
			if (f (k) <= n)
			{
				n -= f (k);
				res += 1;
			}
			k -= 1;
		}
		writeln (res);
	}
}


Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.  The park can be represented as a rectangular n × m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.Om Nom isn't yet sure where to start his walk from but he definitely wants:  to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders);  to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.

The first line contains three integers n, m, k (2 ≤ n, m ≤ 2000; 0 ≤ k ≤ m(n - 1)).  Each of the next n lines contains m characters — the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down).  It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders.

Print m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right.

NoteConsider the first sample. The notes below show how the spider arrangement changes on the field over time:...        ...        ..U       ...R.L   ->   .*U   ->   L.R   ->  ...R.U        .R.        ..R       ...Character "*" represents a cell that contains two spiders at the same time.  If Om Nom starts from the first cell of the first row, he won't see any spiders.  If he starts from the second cell, he will see two spiders at time 1.  If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2.

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s ", &n, &m, &k) > 0)
	{
		string [] a;
		foreach (i; 0..n)
		{
			a ~= readln ().strip ();
		}

		bool ask (int row, int col, char ch)
		{
			if (row < 0 || row >= n || col < 0 || col >= m)
			{
				return false;
			}
			return a[row][col] == ch;
		}

		int [] ans;
		foreach (j; 0..m)
		{
			int cur = 0;
			foreach (i; 1..n)
			{
				cur += ask (i * 2, j, 'U');
				cur += ask (i, j - i, 'R');
				cur += ask (i, j + i, 'L');
			}
			ans ~= cur;
		}

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

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.traits;

void main(){
  size_t n,m,k;
  readf("%s %s %s\n",&n,&m,&k);

  char[][] table = new char[][](n,m);

  string tmp;
  readf("%s\n",&tmp);
  for(int i = 1; i < n; i++){
    readf("%s\n",&tmp);

    for(int j = 0; j < m; j++){
      if (tmp[j] != '.'){
        table[i][j] = tmp[j];
      }
    }
  }

  // for(int i = 0; i < n; i++){
  //   for(int j = 0; j < m; j++){
  //     write(table[i][j]);
  //   }
  //   writeln();
  // }

  int[] hits = new int[m];
  for(int t = 0; t < n; t++){
    for(int om = 0; om < m; om++){
      // U && D (never hits)
      if(t % 2 == 0 && table[t][om] == 'U'){
        hits[om]++;
      }
      //L
      if(om+t >= 0 && om+t < m && table[t][om+t] == 'L'){
        hits[om]++;
      }
      //R
      //writeln(om-t);
      if(om-t >= 0 && om-t < m && table[t][om-t] == 'R'){
        hits[om]++;
      }
    }
  }
  foreach(om;hits){
    writef("%s ",om);
  }
  writeln();
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.traits;

void main(){
  size_t n,m,k;
  readf("%s %s %s\n",&n,&m,&k);

  char[][] table = new char[][](n,m);

  string tmp;
  readf("%s\n",&tmp);
  for(int i = 1; i < n; i++){
    readf("%s\n",&tmp);

    for(int j = 0; j < m; j++){
      if (tmp[j] != '.'){
        table[i][j] = tmp[j];
      }
    }
  }

  // for(int i = 0; i < n; i++){
  //   for(int j = 0; j < m; j++){
  //     write(table[i][j]);
  //   }
  //   writeln();
  // }

  int[] hits = new int[m];
  for(int t = 0; t < n-1; t++){
    for(int om = 0; om < m; om++){
      // U && D (never hits)
      if(t+2 < n && table[t+2][om] == 'U'){
        hits[om]++;
      }
      //L
      if(om+t >= 0 && om+t < m && table[t][om+t] == 'L'){
        hits[om]++;
      }
      //R
      //writeln(om-t);
      if(om-t >= 0 && om-t < m && table[t][om-t] == 'R'){
        hits[om]++;
      }
    }
  }
  foreach(om;hits){
    writef("%s ",om);
  }
  writeln();
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.traits;

void main(){
  size_t n,m,k;
  readf("%s %s %s\n",&n,&m,&k);

  char[][] table = new char[][](n,m);

  string tmp;
  readf("%s\n",&tmp);
  for(int i = 1; i < n; i++){
    readf("%s\n",&tmp);

    for(int j = 0; j < m; j++){
      if (tmp[j] != '.'){
        table[i][j] = tmp[j];
      }
    }
  }

  // for(int i = 0; i < n; i++){
  //   for(int j = 0; j < m; j++){
  //     write(table[i][j]);
  //   }
  //   writeln();
  // }

  int[] hits = new int[m];
  for(int t = 0; t < n; t++){
    for(int om = 1; om <= m; om++){
      // U && D (never hits)
      if(table[t][om-1] == 'U'){
        hits[om-1]++;
      }
      //L
      if(om-1+t >= 0 && om-1+t < m && table[t][om+t-1] == 'L'){
        hits[om-1]++;
      }
      //R
      //writeln(om-t);
      if(om-1-t >= 0 && om-1-t < m && table[t][om-t-1] == 'R'){
        hits[om-1]++;
      }
    }
  }
  foreach(om;hits){
    writef("%s ",om);
  }
  writeln();
}


A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.   You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.

The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:   d — the diameter of your cylindrical cup,  h — the initial level of water in the cup,  v — the speed of drinking process from the cup in milliliters per second,  e — the growth of water because of rain if you do not drink from the cup.

If it is impossible to make the cup empty, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.

NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by  centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in  seconds.

import std.stdio, std.string, std.conv;
import std.typecons;
import std.algorithm;
import std.math;
void main(){
    auto dhve = readln.chomp.split.map!(to!double);

    double d = dhve[0];
    double h = dhve[1];
    double v = dhve[2];
    double e = dhve[3];

    double r = d * 0.5;
    double t = (PI * r * r * h)/(v - PI * r * r * e);

    if (t < -1e-8){
      writeln("NO");
    }else{
      writeln("YES");
      writeln(t);
    }

}

module main;

import std.stdio;
import std.algorithm;
import std.math;
import std.random;
import std.conv;

void main ()
{
    float h,d,v,e,vn,Vo;
    readf(" %s %s %s %s", &d, &h, &v, &e);
    e = e*(d/2)^^2 * 3.1415926;
    if (v - e < 0) writeln("NO");
    else
    {
        writeln("YES");
        vn = v - e;
        Vo = (d/2)^^2 * 3.1415926 * h;
        Vo = Vo / vn;
        writeln(Vo);

    }

}


You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.

For each query print one integer: the answer to this query.

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

void main() {
    int q = to!int(readln.strip);

    foreach (i; 0 .. q) {
        int l,r,d;
        readf!" %s %s %s"(l,r,d);
        if (l > d) {
            writeln(d);
        } else {
            writeln((r/d+1)*d);
        }
    }
}

import std.stdio;

int main() {
    int q, l, r, d;

    scanf("%d", &q);
    while (q--) {
        scanf("%d%d%d", &l, &r, &d);
        if (d<l) printf("%d\n", d);
        else printf("%d\n", (r/d+1)*d);
    }

    return 0;
}


This is the easy version of the problem. The only difference is that in this version $$$k = 0$$$.There is an array $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most $$$k$$$ such operations before the division: choose a number in the array and change its value to any positive integer. But in this version $$$k = 0$$$, so it is not important.What is the minimum number of continuous segments you should use if you will make changes optimally?

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$k = 0$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^7$$$). It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer  — the answer to the problem.

NoteIn the first test case the division may be as follows:  $$$[18, 6]$$$  $$$[2, 4]$$$  $$$[1]$$$

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

void main()
{
    immutable int MX = 10 ^^ 7 + 23;

    auto d = new int[MX];
    d[] = 0;
    foreach (i; 2 .. sqrt(MX.to!real).to!int) {
        if (d[i] != 0) { continue; }
        foreach (ref p; d[i .. MX].stride(i)) { p = i; }
    }

    foreach (i; 0 .. MX) {
        if (d[i] == 0) { d[i] = i; }
    }

    debug { d.take(20).writeln; }

    int t;
    readf!"%s"(t);
    readln;

    while (t--) {
        int n, k;
        readf!" %s %s"(n, k);
        readln;

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

        auto tr = make!(RedBlackTree!(int[]));

        int ans = 1;
        foreach (e; a) {
            int[] odd;
            while (e > 1) {
                int curd = d[e];
                int cnt = 0;
                while (e % curd == 0) {
                    ++cnt;
                    e /= curd;
                }

                if (cnt % 2 == 1) { odd ~= curd; }
            }

            if (odd in tr) {
                ans += 1;
                tr.clear();
            }

            tr.insert(odd);
        }

        ans.writeln;
    }
}

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

void main()
{
    immutable int MX = 10 ^^ 7 + 23;

    auto d = new int[MX];
    d[] = 0;
    foreach (i; 2 .. sqrt(MX.to!real).to!int) {
        if (d[i] != 0) { continue; }
        foreach (ref p; d[i .. MX].stride(i)) { p = i; }
    }

    foreach (i; 0 .. MX) {
        if (d[i] == 0) { d[i] = i; }
    }

    debug { d.take(20).writeln; }

    int t;
    readf!"%s"(t);
    readln;

    while (t--) {
        int n, k;
        readf!" %s %s"(n, k);
        readln;

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

        auto tr = make!(RedBlackTree!(int[]));
        tr.insert([2, 3]);

        int ans = 1;
        foreach (e; a) {
            int[] odd;
            while (e > 1) {
                int curd = d[e];
                int cnt = 0;
                while (e % curd == 0) {
                    ++cnt;
                    e /= curd;
                }

                if (cnt % 2 == 1) { odd ~= curd; }
            }

            if (odd in tr) {
                ans += 1;
                tr.clear();
            }

            tr.insert(odd);
        }

        ans.writeln;
    }
}


Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:  There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.  The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.  After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.  The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.

Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.

NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.

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

import std.container;

void main() {
  int n, m;
  readf (" %d %d", &n, &m);
  auto a = new int[n];
  auto rbt = new RedBlackTree!int (iota (0, n));
  auto c = new int[n];
  a[] = -1;
  foreach (t; 0 .. m) {
    int l, r, x;
    readf (" %d %d %d", &l, &r, &x);
    --l; --r; --x;
    auto d = rbt.lowerBound (x);
    int k;
    foreach_reverse (i; d) {
      if (i < l) break;
      a[i] = x;
      c[k++] = i;
    }
    d = rbt.upperBound (x);
    foreach (i; d) {
      if (i > r) break;
      a[i] = x;
      c[k++] = i;
    }
    foreach (i; 0 .. k) {
      rbt.removeKey (c[i]);
    }
  }
  a.map! (i => (i+1).text).join(" ").writeln;
}

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto tree = redBlackTree(iota(1, N + 1, 1).array);
    auto ans = new int[N];
    foreach (i; 0 .. M) {
        int L, R, W; scanf("%d %d %d\n", &L, &R, &W);
        auto xs = tree.upperBound(L - 1);
        int[] rs;
        foreach (x; xs) {
            if (x > R) break;
            if (x == W) continue;
            ans[x - 1] = W;
            rs ~= x;
        }
        foreach (r; rs) tree.removeKey(r);
    }
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new int[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p;
        if (child_prior[(v - 1) / Z] == 1) {
            p = seg[v - 1];
        } else {
            p = segp[(v - 1) / Z];
        }
        //writeln([s, t, v]);
        int from_parent = s / Z;
        if (child_prior[from_parent] == -1) {
            for (int i = from_parent * Z; i < from_parent * Z + Z; i++) seg[i] = segp[from_parent];
        }
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = 1;
        int to_parent = t / Z;
        if (child_prior[to_parent] == -1) {
            for (int i = to_parent * Z - Z; i < to_parent * Z; i++) seg[i] = segp[to_parent];
        }
        for (int i = max(s, to_parent * Z - Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = 1;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = -1;
        }
        ans[v - 1] = p;
        static if (false) {
            writeln(seg);
            writeln(segp);
            writeln;
        }
    }
    foreach (i; 0 .. N) {
        if (ans[i] >= 0) continue;
        if (child_prior[i / Z] == 1) {
            ans[i] = seg[i];
        } else if (child_prior[i / Z] == -1) {
            ans[i] = segp[i];
        } else {
            writeln("FOO");
        }
    }
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new int[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p;
        if (child_prior[(v - 1) / Z] == 1) {
            p = seg[v - 1];
        } else {
            p = segp[(v - 1) / Z];
        }
        //writeln([s, t, v]);
        int from_parent = s / Z;
        if (child_prior[from_parent] == -1) {
            for (int i = from_parent * Z; i < from_parent * Z + Z; i++) seg[i] = segp[from_parent];
        }
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = 1;
        int to_parent = t / Z;
        if (child_prior[to_parent] == -1) {
            for (int i = to_parent * Z - Z; i < to_parent * Z; i++) seg[i] = segp[to_parent];
        }
        for (int i = max(s, to_parent * Z - Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = 1;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = -1;
        }
        ans[v - 1] = p;
        static if (false) {
            writeln(seg);
            writeln(segp);
            writeln;
        }
    }
    foreach (i; 0 .. N) {
         if (ans[i] >= 0) continue;
        if (child_prior[i / Z] == 1) {
            ans[i] = seg[i];
        } else if (child_prior[i / Z] == -1) {
            ans[i] = segp[i];
        } else {
            assert(0);
        }
    }
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new bool[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p = seg[v - 1];
        //writeln([s, t, v]);
        int from_parent = s / Z;
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = true;
        int to_parent = t / Z;
        for (int i = max(s, to_parent * Z - Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = true;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = false;
        }
        ans[v - 1] = p;
    }
    foreach (i; 0 .. N) {
        if (ans[i] >= 0) continue;
        if (child_prior[i / Z]) {
            ans[i] = seg[i];
        } else {
            ans[i] = segp[i];
        }
    }
    foreach (i; 0 .. N) if (ans[i] == i + 1) ans[i] = 0;
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new int[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p;
        if (ans[v - 1] >= 0) {
            p = ans[v - 1];
        } else if (child_prior[(v - 1) / Z] == 1) {
            p = seg[v - 1];
        } else {
            p = segp[(v - 1) / Z];
        }
        //writeln([s, t, v]);
        int from_parent = s / Z;
        if (child_prior[from_parent] == -1) {
            for (int i = from_parent * Z; i < from_parent * Z + Z; i++) seg[i] = segp[from_parent];
        }
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = 1;
        int to_parent = t / Z;
        if (child_prior[to_parent] == -1) {
            for (int i = to_parent * Z - Z; i < to_parent * Z; i++) seg[i] = segp[to_parent];
        }
        for (int i = max(s, to_parent * Z - Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = 1;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = -1;
        }
        ans[v - 1] = p;
        static if (false) {
            writeln(seg);
            writeln(segp);
            writeln(ans);
            writeln;
        }
    }
    foreach (i; 0 .. N) {
        if (ans[i] >= 0) continue;
        if (child_prior[i / Z] == 1) {
            ans[i] = seg[i];
        } else if (child_prior[i / Z] == -1) {
            ans[i] = segp[i];
        } else {
            assert(0);
        }
    }
    //foreach (i; 0 .. N) if (ans[i] == i + 1) ans[i] = 0;
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new int[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p;
        if (ans[v - 1] >= 0) {
            p = ans[v - 1];
        } else if (child_prior[(v - 1) / Z] == 1) {
            p = seg[v - 1];
        } else {
            p = segp[(v - 1) / Z];
        }
        //writeln([s, t, v]);
        int from_parent = s / Z;
        if (child_prior[from_parent] == -1) {
            for (int i = from_parent * Z; i < from_parent * Z + Z; i++) seg[i] = segp[from_parent];
        }
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = 1;
        int to_parent = (t - 1) / Z;
        if (child_prior[to_parent] == -1) {
            for (int i = to_parent * Z; i < to_parent * Z + Z; i++) seg[i] = segp[to_parent];
        }
        for (int i = max(s, to_parent * Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = 1;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = -1;
        }
        ans[v - 1] = p;
        static if (false) {
            writeln(seg);
            writeln(segp);
            writeln(ans);
            writeln;
        }
    }
    foreach (i; 0 .. N) {
        if (ans[i] >= 0) continue;
        if (child_prior[i / Z] == 1) {
            ans[i] = seg[i];
        } else if (child_prior[i / Z] == -1) {
            ans[i] = segp[i];
        } else {
            assert(0);
        }
    }
    //foreach (i; 0 .. N) if (ans[i] == i + 1) ans[i] = 0;
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new int[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p;
        if (child_prior[(v - 1) / Z] == 1) {
            p = seg[v - 1];
        } else {
            p = segp[(v - 1) / Z];
        }
        //writeln([s, t, v]);
        int from_parent = s / Z;
        if (child_prior[from_parent] == -1) {
            for (int i = from_parent * Z; i < from_parent * Z + Z; i++) seg[i] = segp[from_parent];
        }
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = 1;
        int to_parent = t / Z;
        if (child_prior[to_parent] == -1) {
            for (int i = to_parent * Z - Z; i < to_parent * Z; i++) seg[i] = segp[to_parent];
        }
        for (int i = max(s, to_parent * Z - Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = 1;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = -1;
        }
        ans[v - 1] = p;
        static if (false) {
            writeln(seg);
            writeln(segp);
            writeln;
        }
    }
    foreach (i; 0 .. N) {
        if (ans[i] >= 0) continue;
        if (child_prior[i / Z] == 1) {
            ans[i] = seg[i];
        } else if (child_prior[i / Z] == -1) {
            ans[i] = segp[i];
        } else {
            assert(0);
        }
    }
    foreach (i; 0 .. N) if (ans[i] == i + 1) ans[i] = 0;
    writefln("%(%s %)", ans);
}

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

class SegmentTree {
    // rootのindexは1
    int N;
    int[] L;
    static int FindPow2(int x) {
        int x1 = 1;
        while (x1 < x) x1 *= 2;
        return x1;
    }
    this(int N_) {
        N = FindPow2(N_);
        L = new int[N * 2];
        L[] = -1;
    }
    /* [s, t)をxに更新 */
    void update(int x, int s, int t) { update(x, s, t, 0, N, 1); }
    void update(int x, int s, int t, int a, int b, int k) {
        if (t <= a || b <= s) return;
        if (s <= a && b <= t) {
            L[k] = x;
        } else if (s < b || a < t) {
            int m = (a + b) / 2;
            update(x, s, t, a, m, k * 2);
            update(x, s, t, m, b, k * 2 + 1);
        }
    }
    /* iの値 */
    int query(int i) { return query(i, 0, N, 1); }
    int query(int i, int a, int b, int k) {
        if (i < a || b <= i) return -1;
        if (a <= i && i < b && L[k] >= 0) return L[k];
        int m = (a + b) / 2;
        return max( query(i, a, m, k * 2), query(i, m, b, k * 2 + 1) );
    }
};

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto L = new int[M],
         R = new int[M],
         W = new int[M];
    foreach (i; 0 .. M) {
        auto xs = readln.chomp.split(" ").map!(to!int).array;
        L[i] = xs[0]; L[i]--;
        R[i] = xs[1];
        W[i] = xs[2];
    }

    const MAX = 300001; const Z = 550;
    auto ans = new int[N]; ans[] = -1;
    auto seg = new int[N]; seg[] = -1;
    auto segp = new int[N];
    auto child_prior = new int[N];
    L.reverse; R.reverse; W.reverse;
    foreach (m; 0 .. M) {
        int s = L[m], t = R[m], v = W[m]; // [s, t]をvに更新
        int p;
        if (ans[v - 1] >= 0) {
            p = ans[v - 1];
        } else if (child_prior[(v - 1) / Z] == 1) {
            p = seg[v - 1];
        } else {
            p = segp[(v - 1) / Z];
        }
        //writeln([s, t, v]);
        int from_parent = s / Z;
        if (child_prior[from_parent] == -1) {
            for (int i = from_parent * Z; i < from_parent * Z + Z; i++) seg[i] = segp[from_parent];
        }
        for (int i = s; i < min(t, from_parent * Z + Z); i++) {
            seg[i] = v;
        }
        child_prior[from_parent] = 1;
        int to_parent = (t - 1) / Z;
        if (child_prior[to_parent] == -1) {
            for (int i = to_parent * Z; i < to_parent * Z + Z; i++) seg[i] = segp[to_parent];
        }
        for (int i = max(s, to_parent * Z - Z); i < t; i++) {
            seg[i] = v;
        }
        child_prior[to_parent] = 1;
        for (int i = from_parent + 1; i <= to_parent - 1; i++) {
            segp[i] = v;
            child_prior[i] = -1;
        }
        ans[v - 1] = p;
        static if (false) {
            writeln(seg);
            writeln(segp);
            writeln(ans);
            writeln;
        }
    }
    foreach (i; 0 .. N) {
        if (ans[i] >= 0) continue;
        if (child_prior[i / Z] == 1) {
            ans[i] = seg[i];
        } else if (child_prior[i / Z] == -1) {
            ans[i] = segp[i];
        } else {
            assert(0);
        }
    }
    //foreach (i; 0 .. N) if (ans[i] == i + 1) ans[i] = 0;
    writefln("%(%s %)", ans);
}

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto tree = redBlackTree(iota(1, N + 1, 1).array);
    auto ans = new int[N];
    foreach (i; 0 .. M) {
        int L, R, W; scanf("%d %d %d\n", &L, &R, &W);
        auto xs = tree.upperBound(L - 1);
        int[] rs;
        foreach (x; xs) {
            if (x > R) break;
            if (x == W) continue;
            ans[x - 1] = W;
            rs ~= x;
        }
        foreach (r; rs) tree.removeKey(r);
    }
    writeln(ans);
}


Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 1\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^{9}$$$) — the current volume and Bob's desired volume, respectively.

For each test case, output a single integer — the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.

NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$.

import std.stdio;
import std.math;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		readf(" %d", &a);
		readf(" %d", &b);
		int c=abs(a-b);
		int res=0;
		while(c!=0)
		{
			if (c>=5)
			{
				res=res+(c/5);
				c=c%5;
			}
			else if (c>=2)
			{
				res=res+(c/2);
				c=c%2;
			}
			else
			{
				res=res+c;
				c=0;
			}
		}
		writeln(res);
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

//long mod = 10^^9 + 7;
long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto T = RD!int;
	auto ans = new long[](T);
	foreach (i; 0..T)
	{
		auto a = RD!int;
		auto b = RD!int;
		auto x = min(a, b);
		auto y = max(a, b);
		auto d = y - x;
		ans[i] += d / 5;
		x += ans[i] * 5;
		if (x != y)
		{
			if (y-x >= 3)
				ans[i] += 2;
			else
				++ans[i];
		}
	}

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


You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.

NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

import std.stdio;
import core.stdc.string : memset;
void main() {
    uint t, n;
    scanf("%d", &t);

    while(t--) {
        char[55] stack;
        int top = -1;

        char[55] str;
        memset(&str, 0, char.sizeof * 55);

        scanf("%d", &n);
        scanf("%s", &str);

        for(uint i=0; i < n; i++) {
            char c = str[i];
            if(c == '(')
                stack[++top] = c;
            else if(c == ')') {
                if(top > -1 && stack[top] == '(')
                    top--;
                else
                    stack[++top] = c;
            }
        }

        printf("%d\n", (top + 1) / 2);
    }
}

import std.stdio;
import std.string : strip;

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

  foreach(i; 0..t) {
    int n;
    readf!"%d\n"(n);

    auto s = readln().strip();

    auto c = 0, a = 0;
    foreach (j; 0..n) {
      if (s[j] == ')') c--;
      if (s[j] == '(') c++;

      if (c < 0) {
        a++;
        c = 0;
      }
    }

    writeln(a);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;
		int balance = 0;
		int res = 0;
		foreach (char c; s)
		{
			balance += (c == '(') ? +1 : -1;
			res = max (res, -balance);
		}
		writeln (res);
	}
}