You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Rows are numbered from top to bottom from $$$1$$$ to $$$n$$$, columns are numbered from left to right from $$$1$$$ to $$$n$$$. The element located at the intersection of row $$$i$$$ and column $$$j$$$ is called $$$A_{ij}$$$. Consider a set of $$$4$$$ operations:  Cyclically shift all rows up. The row with index $$$i$$$ will be written in place of the row $$$i-1$$$ ($$$2 \le i \le n$$$), the row with index $$$1$$$ will be written in place of the row $$$n$$$.  Cyclically shift all rows down. The row with index $$$i$$$ will be written in place of the row $$$i+1$$$ ($$$1 \le i \le n - 1$$$), the row with index $$$n$$$ will be written in place of the row $$$1$$$.  Cyclically shift all columns to the left. The column with index $$$j$$$ will be written in place of the column $$$j-1$$$ ($$$2 \le j \le n$$$), the column with index $$$1$$$ will be written in place of the column $$$n$$$.  Cyclically shift all columns to the right. The column with index $$$j$$$ will be written in place of the column $$$j+1$$$ ($$$1 \le j \le n - 1$$$), the column with index $$$n$$$ will be written in place of the column $$$1$$$.     The $$$3 \times 3$$$ matrix is shown on the left before the $$$3$$$-rd operation is applied to it, on the right — after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations:  Select any element $$$A_{ij}$$$ and assign it with new value $$$A_{ij} \oplus 1$$$. In other words, the value of $$$(A_{ij} + 1) \bmod 2$$$ will have to be written into element $$$A_{ij}$$$. Each application of this xor-operation costs one burl. Note that the $$$4$$$ shift operations — are free. These $$$4$$$ operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, $$$A_{ij} = 1$$$ if $$$i = j$$$ and $$$A_{ij} = 0$$$ otherwise).

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. Before each test case, an empty line is written in the input. The first line of each test case contains a single number $$$n$$$ ($$$1 \le n \le 2000$$$) This is followed by $$$n$$$ lines, each containing exactly $$$n$$$ characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix. It is guaranteed that the sum of $$$n^2$$$ values over all test cases does not exceed $$$4 \cdot 10^6$$$.

For each test case, output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the $$$A$$$ matrix to become unitary.

NoteIn the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only "1". Then it will be necessary to apply xor-operation to the only "1" that is not on the main diagonal.In the second test case, you can make a unitary matrix by applying the operation $$$2$$$ — cyclic shift of rows upward twice to the matrix.

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

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

void solve() {
    readln;
    int N = read!int;
    auto F = iota(N).map!(_ => readln.chomp).array;
    int no = 0;
    for (int y = 0; y < N; y++) {
        for (int x = 0; x < N; x++) {
            no += (F[y][x] == '1');
        }
    }
    int ans = N*N;
    for (int y = 0; y < N; y++) {
        int dno = 0;
        for (int k = 0; k < N; k++) {
            int i = (y + k) % N, j = k;
            dno += (F[i][j] == '1');
        }
        ans = min(ans, no - dno + N - dno);
    }
    writeln(ans);
}

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

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)
	{
		readln;
		auto n = readln.strip.to !(int);
		auto s = new int [n];
		foreach (i; 0..n)
		{
			auto t = readln.strip.map !(q{a - '0'}).array;
			foreach (j; 0..n)
			{
				s[(i + n - j) % n] += t[j];
			}
		}
		auto total = s.sum;
		auto res = s.map !(c => total - c + n - c).minElement;
		writeln (res);
	}
}


You are given a connected undirected graph with n vertices and m edges. The vertices are enumerated from 1 to n. You are given n integers c1, c2, ..., cn, each of them is between  - n and n, inclusive. It is also guaranteed that the parity of cv equals the parity of degree of vertex v. The degree of a vertex is the number of edges connected to it.You are to write a weight between  - 2·n2 and 2·n2 (inclusive) on each edge in such a way, that for each vertex v the sum of weights on edges connected to this vertex is equal to cv, or determine that this is impossible.

The first line contains two integers n and m (2 ≤ n ≤ 105, n - 1 ≤ m ≤ 105) — the number of vertices and the number of edges. The next line contains n integers c1, c2, ..., cn ( - n ≤ ci ≤ n), where ci is the required sum of weights of edges connected to vertex i. It is guaranteed that the parity of ci equals the parity of degree of vertex i. The next m lines describe edges of the graph. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), meaning that the i-th edge connects vertices ai and bi. It is guaranteed that the given graph is connected and does not contain loops and multiple edges.

If there is no solution, print "NO". Otherwise print "YES" and then m lines, the i-th of them is the weight of the i-th edge wi ( - 2·n2 ≤ wi ≤ 2·n2).

/+ dub.sdl:
    name "D"
    dependency "dcomp" version=">=0.9.0"
+/

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

import std.typecons;

int main() {
    Scanner sc = new Scanner(stdin);
    int n, m;
    long[] c;
    sc.read(n, m, c);
    alias E = Tuple!(int, "to", int, "id");
    E[][] g = new E[][](n);
    foreach (i; 0..m) {
        int a, b;
        sc.read(a, b); a--; b--;
        g[a] ~= E(b, i);
        g[b] ~= E(a, i);
    }
    long[] res = new long[m];
    int[] dps = new int[n];
    int[] par = new int[n];
    int[] pid = new int[n]; pid[0] = -1;
    bool[] vis = new bool[n];

    int eid = -1, edown = -1, eup = -1, edps = -1;
    long dfs(int p, int b, int ndp = 0) {
        dps[p] = ndp;
        par[p] = b;
        vis[p] = true;
        long sm = c[p];
        foreach (e; g[p]) {
            int d = e.to;
            if (d == b) continue;
            if (!vis[d]) {
                pid[d] = e.id;
                long u = dfs(d, p, ndp+1);
                res[e.id] = u;
                sm -= u;
                continue;
            }
            if (dps[p] < dps[d]) continue;
            // back edge
            if ((dps[p] - dps[d]) % 2) continue;
            // odd cycle
            eid = e.id;
            edown = p; eup = d; edps = dps[p];
        }
        return sm;
    }

    long u = dfs(0, -1);
    if (edps % 2) u *= -1;
    if (u) {
        if (eid == -1) {
            writeln("NO");
            return 0;
        }
        u /= 2;
        res[eid] += u; u *= -1;
        int s = edown;
        while (s != eup) {
            res[pid[s]] += u; u *= -1;
            s = par[s];
        }
        u *= 2;
        while (s) {
            res[pid[s]] += u; u *= -1;
            s = par[s];
        }
    }

    writeln("YES");
    writeln(res.map!(to!string).join("\n"));
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/container/stackpayload.d */
// module dcomp.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/dcomp/source/dcomp/foundation.d */

// module dcomp.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/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.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 read(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);
        }
    }
}

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

int N, M;
long[] C;
int[] A, B;

int[][] G;
int[] par, pari;
int[] dep;
long[] ans;
int odI, odU, odV;

long dfs(int u, int p, int pi) {
  par[u] = p;
  pari[u] = pi;
  dep[u] = (p == -1) ? 0 : (dep[p] + 1);
  long ret = C[u];
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      if (dep[v] == -1) {
        ans[i] = dfs(v, u, i);
        ret -= ans[i];
      } else if (dep[u] > dep[v]) {
        if ((dep[u] - dep[v]) % 2 == 0) {
          odI = i;
          odU = u;
          odV = v;
        }
      }
    }
  }
  return ret;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      C = new long[N];
      foreach (u; 0 .. N) {
        C[u] = readLong();
      }
      A = new int[M];
      B = new int[M];
      foreach (i; 0 .. M) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      pari = new int[N];
      dep = new int[N];
      dep[] = -1;
      ans = new long[M];
      odI = odU = odV = -1;
      const rt = 0;
      const res = dfs(rt, -1, -1);
      debug {
        writeln("ans = ", ans);
        writefln("od = %s: %s %s", odI, odU, odV);
        writeln("res = ", res);
      }
      if (res != 0) {
        if (odI != -1 && res % 2 == 0) {
          long d = (-1)^^(dep[odV] % 2) * (res / 2);
          ans[odI] += d;
          for (int w = odU; w != odV; w = par[w]) {
            d *= -1;
            ans[pari[w]] += d;
          }
          d *= 2;
          for (int w = odV; w != rt; w = par[w]) {
            d *= -1;
            ans[pari[w]] += d;
          }
        } else {
          ans = null;
        }
      }

      if (!ans.empty) {
        auto cs = new long[N];
        foreach (i; 0 .. M) {
          cs[A[i]] += ans[i];
          cs[B[i]] += ans[i];
        }
        if (C != cs) {
          ans = null;
        }
      }

      if (!ans.empty) {
        writeln("YES");
        foreach (i; 0 .. M) {
          writeln(ans[i]);
        }
      } else {
        writeln("NO");
      }
    }
  } catch (EOFException e) {
  }
}

/+ dub.sdl:
    name "C"
    dependency "dcomp" version=">=0.9.0"
+/

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

import std.typecons;

// import dcomp.segtree.lazyseg;

int main() {
    Scanner sc = new Scanner(stdin);

    int n, m;
    sc.read(n, m);
    int[][] g = new int[][n];
    foreach (i; 0..m) {
        int a, b;
        sc.read(a, b); a--; b--;
        g[a] ~= b; g[b] ~= a;
    }

    int[] par = new int[n];
    int[] dps = new int[n];
    bool[] vis = new bool[n];

    int[] ri = new int[n+1]; ri[] = n;

    void add(int s, int t) {
        int mi = t, ma = t;
        while (s != t) {
            mi = min(mi, s);
            ma = max(ma, s);
            s = par[s];
        }
        ri[mi] = min(ri[mi], ma);
    }

    void dfs(int p, int b = -1, int ndp = 0) {
        par[p] = b;
        dps[p] = ndp;
        vis[p] = true;
        foreach (d; g[p]) {
            if (d == b) continue;
            if (!vis[d]) {
                dfs(d, p, ndp+1);
                continue;
            }
            if (dps[p] < dps[d]) continue;
            add(p, d);
        }
    }
    foreach (i; 0..n) {
        if (vis[i]) continue;
        dfs(i);
    }
    foreach_reverse (i; 0..n-1) {
        ri[i] = min(ri[i], ri[i+1]);
    }
//    writeln(ri);

    int q;
    sc.read(q);
    long[] res = new long[q];

    alias E = Tuple!(int, "left", int, "id", bool, "pos");
    E[][] ev = new E[][](n+1);

    foreach (i; 0..q) {
        int a, b;
        sc.read(a, b); a--;
        res[i] = long(b-a) * long(b-a + 1) / 2;
        ev[b] ~= E(a, i, false);
        ev[b] ~= E(b, i, true);
        ev[a] ~= E(a, i, true);
        ev[a] ~= E(b, i, false);
    }

    alias N = Tuple!(long, int);
    auto seg = LazySeg!(N, long,
        (a, b) => N(a[0]+b[0], a[1]+b[1]),
        (a, b) => N(a[0]+a[1]*b, a[1]),
        "a+b",
        N(0, 0), 0)(N(0, 1).repeat.take(n).array);
    foreach (r; 0..n+1) {
        foreach (e; ev[r]) {
            long u = seg[e.left..$].sum[0];
            if (e.pos) {
                res[e.id] += u;
            } else {
                res[e.id] -= u;
            }
        }
        seg[ri[r]..$] += 1;
    }
    writeln(res.map!(to!string).join("\n"));

    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */

// module dcomp.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/dcomp/source/dcomp/segtree/lazyseg.d */
// module dcomp.segtree.lazyseg;

// import dcomp.segtree.primitive;

import std.functional : binaryFun;

alias LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL, alias Engine = LazySegEngine) =
    SegTree!(Engine, T, L , binaryFun!opTT, binaryFun!opTL, binaryFun!opLL, eT, eL);

struct LazySegEngine(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    import std.typecons : Tuple;
    alias DataType = T;
    alias LazyType = L;
    alias BinSearch = binSearchLazy;
    alias S = Tuple!(T, "d", L, "lz");
    uint n, sz, lg;
    S[] s;
    this(uint n) {
        import std.conv : to;
        import std.algorithm : each;
        this.n = n;
        uint lg = 0;
        while ((2^^lg) < n) lg++;
        this.lg = lg;
        sz = 2^^lg;
        s = new S[](2*sz);
        s.each!((ref x) => x = S(eT, eL));
    }
    this(T[] first) {
        import std.conv : to;
        import std.algorithm : each;
        n = first.length.to!uint;
        uint lg = 0;
        while ((2^^lg) < n) lg++;
        this.lg = lg;
        sz = 2^^lg;

        s = new S[](2*sz);
        s.each!((ref x) => x = S(eT, eL));
        foreach (i; 0..n) {
            s[sz+i].d = first[i];
        }
        foreach_reverse (i; 1..sz) {
            update(i);
        }
    }
    @property uint length() const { return n; }
    pragma(inline):
    private void lzAdd(uint k, in L x) {
        s[k].lz = opLL(s[k].lz, x);
        s[k].d = opTL(s[k].d, x);
    }
    public void push(uint k) {
        if (s[k].lz == eL) return;
        lzAdd(2*k, s[k].lz);
        lzAdd(2*k+1, s[k].lz);
        s[k].lz = eL;
    }
    private void update(uint k) {
        s[k].d = opTT(s[2*k].d, s[2*k+1].d);
    }
    T single(uint k) {
        k += sz;
        foreach_reverse (uint i; 1..lg+1) {
            push(k>>i);
        }
        return s[k].d;
    }
    void singleSet(uint k, T x) {
        k += sz;
        foreach_reverse (uint i; 1..lg+1) {
            push(k>>i);
        }
        s[k].d = x;
        foreach (uint i; 1..lg+1) {
            update(k>>i);
        }
    }
    T sum(uint a, uint b) {
        assert(0 <= a && a <= b && b <= n);
        if (a == b) return eT;
        a += sz; b--; b += sz;
        uint tlg = lg;
        while (true) {
            uint k = a >> tlg;
            if (a >> tlg != b >> tlg) {
                tlg++;
                break;
            }
            if (((a-1) >> tlg) + 2 == (b+1) >> tlg) return s[k].d;
            push(k);
            tlg--;
        }
        T sm = eT;
        foreach_reverse (l; 0..tlg) {
            uint k = a >> l;
            if ((a-1)>>l != a>>l) {
                sm = opTT(s[k].d, sm);
                break;
            }
            push(k);
            if (!((a >> (l-1)) & 1)) sm = opTT(s[2*k+1].d, sm);
        }
        foreach_reverse (l; 0..tlg) {
            uint k = b >> l;
            if (b>>l != (b+1)>>l) {
                sm = opTT(sm, s[k].d);
                break;
            }
            push(k);
            if ((b >> (l-1)) & 1) sm = opTT(sm, s[2*k].d);
        }
        return sm;
    }
    void add(uint a, uint b, L x) {
        assert(0 <= a && a <= b && b <= n);
        if (a == b) return;
        a += sz; b--; b += sz;
        uint tlg = lg;
        while (true) {
            uint k = a >> tlg;
            if (a >> tlg != b >> tlg) {
                tlg++;
                break;
            }
            if (((a-1) >> tlg) + 2 == (b+1) >> tlg) {
                lzAdd(k, x);
                foreach (l; tlg+1..lg+1) {
                    update(a >> l);
                }
                return;
            }
            push(k);
            tlg--;
        }
        foreach_reverse (l; 0..tlg) {
            uint k = a >> l;
            if ((a-1)>>l != a>>l) {
                lzAdd(k, x);
                foreach (h; l+1..tlg) {
                    update(a >> h);
                }
                break;
            }
            push(k);
            if (!((a >> (l-1)) & 1)) lzAdd(2*k+1, x);
        }
        foreach_reverse (l; 0..tlg) {
            uint k = b >> l;
            if (b>>l != (b+1)>>l) {
                lzAdd(k, x);
                foreach (h; l+1..tlg) {
                    update(b >> h);
                }
                break;
            }
            push(k);
            if ((b >> (l-1)) & 1) lzAdd(2*k, x);
        }
        foreach (l; tlg..lg+1) {
            update(a >> l);
        }
    }
}

int binSearchLazy(bool rev, alias pred, TR)(TR t, int a, int b) {
    import std.traits : TemplateArgsOf;
    alias args = TemplateArgsOf!TR;
    alias opTT = args[2];
    auto x = args[5];
    with (t) {
        static if (!rev) {

            if (pred(x)) return a-1;
            int pos = a;
            void f(int a, int b, int l, int r, int k) {
                if (b <= l || r <= a) return;
                if (a <= l && r <= b && !pred(opTT(x, s[k].d))) {
                    x = opTT(x, s[k].d);
                    pos = r;
                    return;
                }
                if (l+1 == r) return;
                push(k);
                int md = (l+r)/2;
                f(a, b, l, md, 2*k);
                if (pos >= md) f(a, b, md, r, 2*k+1);
            }
            f(a, b, 0, sz, 1);
            return pos;
        } else {

            if (pred(x)) return b;
            int pos = b-1;
            void f(int a, int b, int l, int r, int k) {
                if (b <= l || r <= a) return;
                if (a <= l && r <= b && !pred(opTT(x, s[k].d))) {
                    x = opTT(s[k].d, x);
                    pos = l-1;
                    return;
                }
                if (l+1 == r) return;
                push(k);
                int md = (l+r)/2;
                f(a, b, md, r, 2*k+1);
                if (pos < md) f(a, b, l, md, 2*k);
            }
            f(a, b, 0, sz, 1);
            return pos;
        }
    }
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.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 read(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);
        }
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/segtree/primitive.d */
// module dcomp.segtree.primitive;

import std.conv : to;

struct SegTree(alias E, Args...) {
    import std.traits : ReturnType;
    alias Engine = E!Args;
    alias T = Engine.DataType;
    alias L = Engine.LazyType;

    Engine eng;

    this(size_t n) { eng = Engine(n.to!uint); }
    this(T[] first) { eng = Engine(first); }

    @property size_t length() const { return eng.length(); }
    @property size_t opDollar() const { return eng.length(); }

    struct Range {
        Engine* eng;
        size_t start, end;
        @property const(T) sum() {
            return eng.sum(start.to!uint, end.to!uint);
        }
    }
    const(T) opIndex(size_t k) {
        assert(0 <= k && k < eng.length());
        return eng.single(k.to!uint);
    }
    void opIndexAssign(T x, size_t k) {
        assert(0 <= k && k < eng.length());
        eng.singleSet(k.to!uint, x);
    }
    size_t[2] opSlice(size_t dim : 0)(size_t start, size_t end) {
        assert(0 <= start && start <= end && end <= eng.length());
        return [start, end];
    }
    Range opIndex(size_t[2] rng) {
        return Range(&eng, rng[0].to!uint, rng[1].to!uint);
    }
    static if (!is(L == void)) {
        void opIndexOpAssign(string op : "+")(L x, size_t[2] rng) {
            eng.add(rng[0].to!uint, rng[1].to!uint, x);
        }
    }
}

import std.traits : isInstanceOf;

ptrdiff_t binSearchLeft(alias pred, TR)(TR t, ptrdiff_t a, ptrdiff_t b)
if (isInstanceOf!(SegTree, TR)) {
    return TR.Engine.BinSearch!(false, pred)(t.eng, a.to!int, b.to!int);
}

ptrdiff_t binSearchRight(alias pred, TR)(TR t, ptrdiff_t a, ptrdiff_t b)
if (isInstanceOf!(SegTree, TR)) {
    return TR.Engine.BinSearch!(true, pred)(t.eng, a.to!int, b.to!int);
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/container/stackpayload.d */
// module dcomp.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--;
    }
}

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


Ringo found a string $$$s$$$ of length $$$n$$$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $$$s$$$ into a palindrome by applying two types of operations to the string. The first operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_2s_3 \ldots s_i$$$ ($$$i - 1$$$ characters) reversed to the front of $$$s$$$.The second operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_i s_{i + 1}\ldots s_{n - 1}$$$ ($$$n - i$$$ characters) reversed to the end of $$$s$$$.Note that characters in the string in this problem are indexed from $$$1$$$.For example suppose $$$s=$$$abcdef. If he performs the first operation with $$$i=3$$$ then he appends cb to the front of $$$s$$$ and the result will be cbabcdef. Performing the second operation on the resulted string with $$$i=5$$$ will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $$$30$$$ times. The length of the resulting palindrome must not exceed $$$10^6$$$It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.

The only line contains the string $$$S$$$ ($$$3 \le |s| \le 10^5$$$) of lowercase letters from the English alphabet.

The first line should contain $$$k$$$ ($$$0\le k \le 30$$$)  — the number of operations performed. Each of the following $$$k$$$ lines should describe an operation in form L i or R i. $$$L$$$ represents the first operation, $$$R$$$ represents the second operation, $$$i$$$ represents the index chosen. The length of the resulting palindrome must not exceed $$$10^6$$$.

NoteFor the first example the following operations are performed:abac $$$\to$$$ abacab $$$\to$$$ abacabaThe second sample performs the following operations: acccc $$$\to$$$ cccacccc $$$\to$$$ ccccaccccThe third example is already a palindrome so no operations are required.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto s = RD!string;

	string[] ans;
	ans ~= "R 2";
	ans ~= "L 2";
	auto len = s.length*2 - 1;
	ans ~= "R 2";
	len += len - 2;
	ans ~= "R " ~ (len-1).to!string;

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


You are given two integers $$$l$$$ and $$$r$$$, $$$l\le r$$$. Find the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.As a reminder, $$$a \bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \bmod 8 = 2$$$.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\le t\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\le l \le r \le 10^9$$$).

For every test case, output the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.

NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \bmod b = 1 \bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \bmod b = 1$$$.

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

long maximalModulus(long left, long right) {
    if (right / 2 + 1 >= left) {
        return right % (right / 2 + 1);
    }
    else {
        long max = -1;
        long i = 1;
        long x = 1;
        while (x > max + 1) {
            x = ((right - 1) / i) + 1;
            debug{writeln("x=", x, "right&x=", right%x, "max=", max);}
            if (right%x > max) {
                max = right%x;
            }
            if (x < left) {
                return right % left;
            }
            ++i;
        }
        return max;
    }
}

// void find_mod(long left, long right)
// {
//     long max_current = 0;
//     long max_delimeter = 0;
//     for (long a = right; a >= left; a--)
//     {
//         for (long b = max(a - 1, a / 2 + 1); b >= left ; b--)
//         {
//             auto current = a % b;
//             max_current = max(max_current, current);
//             if (max_current == b - 1)
//             {
//                 writeln(max_current);
//                 debug{writeln("A",a," B",b);}
//                 return;
//             }
//         }
//     }
//     writeln(max_current);
//     return;
// }

void main()
{
    int n;
    long l, r;
    scanf("%d", &n);
    getchar();

    for (int k = 0; k < n; k++){
	    scanf("%ld %ld", &l, &r);
        getchar();
        // find_mod(l, r);
        writeln(maximalModulus(l, r));
    }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long l, r;
    readln.formattedRead!" %d %d "(l, r);
    long max_b = max(l, (r + 1) / 2);
    long max_a = min(max_b * 2, r);
    long maxrem = 0;
    foreach (i ; -5L .. 5L) {
      foreach (j ; -5L .. 5L) {
        long a = max(min(max_a + i, r), l);
        long b = max(min(max_b + j, r), l);
        if (b > a)
          continue;
        maxrem = max(maxrem, a % b);
      }
    }
    writeln(maxrem);
  }
}

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

void theCode(){
    ll l = scan;
    ll r = scan;
    if(l == r){
        writeln(0);
        return;
    }
    ll d = r/2 + 1;
    d = max(l, d);
    writeln(r % d);
}

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

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		ans[ti] = r % max(r / 2 + 1, l);
	}

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


This is the hard version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$2n$$$ operations. It can be proved that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output an integer $$$k$$$ ($$$0\le k\le 2n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.

NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.

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

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

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

        auto a = readln.chomp;
        auto b = readln.chomp;

        int[] ans;
        int p = 0;
        foreach (op; 0 .. n) {
            int cur = (a[p] - '0') ^ (op & 1);

            debug { writeln(p, ' ', op, ' ', cur); }

            if (cur == (b[n - op - 1] - '0')) {
                ans ~= 1;
            }

            ans ~= n - op;
            p = n - p - 1 + (op & 1);
        }

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

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.map !(q{a == '1'}).array;
		auto t = readln.strip.map !(q{a == '1'}).array;

		int [] answer;
		int lo = 0;
		int hi = n - 1;
		int p = 0;
		foreach_reverse (i; 0..n)
		{
			auto cur = (p ? !s[hi] : s[lo]);
			if (cur == t[i])
			{
				answer ~= 1;
			}
			answer ~= i + 1;
			if (p)
			{
				hi -= 1;
			}
			else
			{
				lo += 1;
			}
			p ^= 1;
		}
		writefln !("%s\n%(%s %)") (answer.length, answer);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const A = readToken();
        const B = readToken();

        int[] ansA, ansB;
        for (int i = 0, j; i < N; i = j) {
          for (j = i; j < N && A[i] == A[j]; ++j) {}
          if (!(j == N && A[N - 1] == '0')) {
            ansA ~= j;
          }
        }
        for (int i = 0, j; i < N; i = j) {
          for (j = i; j < N && B[i] == B[j]; ++j) {}
          if (!(j == N && B[N - 1] == '0')) {
            ansB ~= j;
          }
        }

        int[] ans;
        foreach (j; ansA) {
          ans ~= j;
        }
        foreach_reverse (j; ansB) {
          ans ~= j;
        }

        write(ans.length);
        foreach (j; ans) {
          write(" ", j);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int l, r = n-1;
		bool inv;
		foreach_reverse (i; 0..n)
		{
			int ll = inv ? r : l;
			int rr = inv ? l : r;
			debug writeln("ll:", ll, " rr:", rr);
			if ((a[rr] == b[i]) != inv)
			{
				if (inv)
					++l;
				else
					--r;
				continue;
			}
			if ((a[ll] == b[i]) != inv)
			{
				ans[ti] ~= 1;
			}
			ans[ti] ~= i+1;
			if (inv)
				--r;
			else
				++l;
			inv = !inv;
			continue;
		}
	}

	foreach (e; ans)
	{
		write(e.length);
		if (e.empty)
		{
			writeln;
			continue;
		}
		write(" ");
		e.map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

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

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

        auto a = readln.chomp;
        auto b = readln.chomp;

        int[] ans;
        int p = 0;
        foreach (op; 0 .. n) {
            int cur = (a[p] - '0') ^ op;
            if (cur == (b[n - op - 1] - '0')) {
                ans ~= 1;
            }

            ans ~= n - op;
            p = n - p - 1;
        }

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


You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.

The first line contains the only integer n (1 ≤ n ≤ 105) — the length of the permutation. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation. All the integers are distinct.

Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.

NoteIn the first example the only element can be removed.

import std.stdio;
import std.algorithm : canFind;

int next_digit(int a, int b) {
    return ((a * 10) / b);
}
int next_a(int a, int b) {
    return ((a * 10) % b);
}

void main() {
    int n;
    readf("%s\n", &n);
    int[] idx___value;
    int[] good_idxes;
    int curr_max = -1;
    int curr_max_idx = -1;
    foreach(idx; 0 .. n) {
        int curr_val;
        readf(" %s", &curr_val);
        idx___value ~= curr_val;
        if (curr_val > curr_max) {
            curr_max = curr_val;
            curr_max_idx = idx;
            good_idxes ~= curr_max_idx;
        }
    }
    // writeln(idx___value);
    // writeln(good_idxes);
    int count = good_idxes.length - 1;
    int good_len = good_idxes.length;
    int ans_idx = n - 1;
    foreach(good_idx; 0 .. good_len) {
        int curr_idx = good_idxes[good_idx];
        int next_idx = n;
        if (good_idx < good_len - 1) {
            next_idx = good_idxes[(good_idx + 1)];
        }
        curr_max_idx = -1;
        curr_max = -1;
        if (good_idx > 0) {
            curr_max_idx = good_idxes[(good_idx - 1)];
            curr_max = idx___value[curr_max_idx];
        }
        int[] to_add;
        foreach(idx; curr_idx + 1 .. next_idx) {
            if (idx___value[idx] > curr_max) {
                curr_max = idx___value[idx];
                curr_max_idx = idx;
                to_add ~= curr_max_idx;
            }
        }
        int curr_count = good_len - 1;
        curr_count += to_add.length;
        if (count < curr_count) {
            count = curr_count;
            ans_idx = curr_idx;
        }
        if (curr_count == count && idx___value[ans_idx] > idx___value[curr_idx]) {
            ans_idx = curr_idx;
        }
    }
    // writeln(count);
    if (count == good_len - 1 || count == good_len) {
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                ans_idx = idx;
                break;
            }
        }
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                // writeln("lexa");
                if (idx___value[idx] < idx___value[ans_idx]) {
                    ans_idx = idx;
                }
            }
        }
    }
    writeln(idx___value[ans_idx]);
}

import std.stdio;
import std.algorithm : canFind;

int next_digit(int a, int b) {
    return ((a * 10) / b);
}
int next_a(int a, int b) {
    return ((a * 10) % b);
}

void main() {
    int n;
    readf("%s\n", &n);
    int[] idx___value;
    int[] good_idxes;
    int curr_max = -1;
    int curr_max_idx = -1;
    foreach(idx; 0 .. n) {
        int curr_val;
        readf(" %s", &curr_val);
        idx___value ~= curr_val;
        if (curr_val > curr_max) {
            curr_max = curr_val;
            curr_max_idx = idx;
            good_idxes ~= curr_max_idx;
        }
    }
    // writeln(idx___value);
    // writeln(good_idxes);
    int count = good_idxes.length - 1;
    int good_len = good_idxes.length;
    int ans_idx = n - 1;
    foreach(good_idx; 0 .. good_len) {
        int curr_idx = good_idxes[good_idx];
        int next_idx = n;
        if (good_idx < good_len - 1) {
            next_idx = good_idxes[(good_idx + 1)];
        }
        curr_max_idx = -1;
        curr_max = -1;
        if (good_idx > 0) {
            curr_max_idx = good_idxes[(good_idx - 1)];
            curr_max = idx___value[curr_max_idx];
        }
        int[] to_add;
        foreach(idx; curr_idx + 1 .. next_idx) {
            if (idx___value[idx] > curr_max) {
                curr_max = idx___value[idx];
                curr_max_idx = idx;
                to_add ~= curr_max_idx;
            }
        }
        int curr_count = good_len - 1;
        curr_count += to_add.length;
        if (count < curr_count) {
            count = curr_count;
            ans_idx = curr_idx;
        }
        if (curr_count == count && idx___value[ans_idx] > idx___value[curr_idx]) {
            ans_idx = curr_idx;
        }
    }
    // writeln(count);
    if (count == good_idxes.length) {
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                // writeln("lexa");
                if (idx___value[idx] < idx___value[ans_idx]) {
                    ans_idx = idx;
                }
            }
        }
    }
    writeln(idx___value[ans_idx]);
}

import std.stdio;
import std.algorithm : canFind;

int next_digit(int a, int b) {
    return ((a * 10) / b);
}
int next_a(int a, int b) {
    return ((a * 10) % b);
}

void main() {
    int n;
    readf("%s\n", &n);
    int[] idx___value;
    int[] good_idxes;
    int curr_max = -1;
    int curr_max_idx = -1;
    foreach(idx; 0 .. n) {
        int curr_val;
        readf(" %s", &curr_val);
        idx___value ~= curr_val;
        if (curr_val > curr_max) {
            curr_max = curr_val;
            curr_max_idx = idx;
            good_idxes ~= curr_max_idx;
        }
    }
    // writeln(idx___value);
    // writeln(good_idxes);
    int count = good_idxes.length - 1;
    int good_len = good_idxes.length;
    int ans_idx = n - 1;
    foreach(good_idx; 0 .. good_len) {
        int curr_idx = good_idxes[good_idx];
        int next_idx = n;
        if (good_idx < good_len - 1) {
            next_idx = good_idxes[(good_idx + 1)];
        }
        curr_max_idx = -1;
        curr_max = -1;
        if (good_idx > 0) {
            curr_max_idx = good_idxes[(good_idx - 1)];
            curr_max = idx___value[curr_max_idx];
        }
        int[] to_add;
        foreach(idx; curr_idx + 1 .. next_idx) {
            if (idx___value[idx] > curr_max) {
                curr_max = idx___value[idx];
                curr_max_idx = idx;
                to_add ~= curr_max_idx;
            }
        }
        int curr_count = good_len - 1;
        curr_count += to_add.length;
        if (count < curr_count) {
            count = curr_count;
            ans_idx = curr_idx;
        }
        if (curr_count == count && idx___value[ans_idx] > idx___value[curr_idx]) {
            ans_idx = curr_idx;
        }
    }
    // writeln(count);
    if (count == good_idxes.length - 1) {
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                ans_idx = idx;
                break;
            }
        }
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                // writeln("lexa");
                if (idx___value[idx] < idx___value[ans_idx]) {
                    ans_idx = idx;
                }
            }
        }
    }
    writeln(idx___value[ans_idx]);
}

import std.stdio;

int next_digit(int a, int b) {
    return ((a * 10) / b);
}
int next_a(int a, int b) {
    return ((a * 10) % b);
}

void main() {
    int n;
    readf("%s\n", &n);
    int[] idx___value;
    int[] good_idxes;
    int curr_max = -1;
    int curr_max_idx = -1;
    foreach(idx; 0 .. n) {
        int curr_val;
        readf(" %s", &curr_val);
        idx___value ~= curr_val;
        if (curr_val > curr_max) {
            curr_max = curr_val;
            curr_max_idx = idx;
            good_idxes ~= curr_max_idx;
        }
    }
    int count = good_idxes.length;
    int good_len = good_idxes.length;
    int ans_idx = 0;
    foreach(good_idx; 0 .. good_len) {
        int curr_idx = good_idxes[good_idx];
        int next_idx = n;
        if (good_idx < good_len - 1) {
            next_idx = good_idxes[(good_idx + 1)];
        }
        curr_max_idx = -1;
        curr_max = -1;
        if (good_idx > 0) {
            curr_max_idx = good_idxes[(good_idx - 1)];
            curr_max = idx___value[curr_max_idx];
        }
        int[] to_add;
        foreach(idx; curr_idx + 1 .. next_idx) {
            if (idx___value[idx] > curr_max) {
                curr_max = idx___value[idx];
                curr_max_idx = idx;
                to_add ~= curr_max_idx;
            }
        }
        int curr_count = good_len - 1;
        curr_count += to_add.length;
        if (count < curr_count) {
            count = curr_count;
            ans_idx = curr_idx;
        }
    }
    writeln(idx___value[ans_idx]);
}

import std.stdio;
import std.algorithm : canFind;

int next_digit(int a, int b) {
    return ((a * 10) / b);
}
int next_a(int a, int b) {
    return ((a * 10) % b);
}

void main() {
    int n;
    readf("%s\n", &n);
    int[] idx___value;
    int[] good_idxes;
    int curr_max = -1;
    int curr_max_idx = -1;
    foreach(idx; 0 .. n) {
        int curr_val;
        readf(" %s", &curr_val);
        idx___value ~= curr_val;
        if (curr_val > curr_max) {
            curr_max = curr_val;
            curr_max_idx = idx;
            good_idxes ~= curr_max_idx;
        }
    }
    // writeln(idx___value);
    // writeln(good_idxes);
    int count = good_idxes.length;
    int good_len = good_idxes.length;
    int ans_idx = n - 1;
    foreach(good_idx; 0 .. good_len) {
        int curr_idx = good_idxes[good_idx];
        int next_idx = n;
        if (good_idx < good_len - 1) {
            next_idx = good_idxes[(good_idx + 1)];
        }
        curr_max_idx = -1;
        curr_max = -1;
        if (good_idx > 0) {
            curr_max_idx = good_idxes[(good_idx - 1)];
            curr_max = idx___value[curr_max_idx];
        }
        int[] to_add;
        foreach(idx; curr_idx + 1 .. next_idx) {
            if (idx___value[idx] > curr_max) {
                curr_max = idx___value[idx];
                curr_max_idx = idx;
                to_add ~= curr_max_idx;
            }
        }
        int curr_count = good_len - 1;
        curr_count += to_add.length;
        if (count < curr_count) {
            count = curr_count;
            ans_idx = curr_idx;
        }
        if (curr_count == count && idx___value[ans_idx] > idx___value[curr_idx]) {
            ans_idx = curr_idx;
        }
    }
    // writeln(count);
    if (count == good_idxes.length) {
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                // writeln("lexa");
                if (idx___value[idx] < idx___value[ans_idx]) {
                    ans_idx = idx;
                }
            }
        }
    }
    writeln(idx___value[ans_idx]);
}

import std.stdio;
import std.algorithm : canFind;

int next_digit(int a, int b) {
    return ((a * 10) / b);
}
int next_a(int a, int b) {
    return ((a * 10) % b);
}

void main() {
    int n;
    readf("%s\n", &n);
    int[] idx___value;
    int[] good_idxes;
    int curr_max = -1;
    int curr_max_idx = -1;
    foreach(idx; 0 .. n) {
        int curr_val;
        readf(" %s", &curr_val);
        idx___value ~= curr_val;
        if (curr_val > curr_max) {
            curr_max = curr_val;
            curr_max_idx = idx;
            good_idxes ~= curr_max_idx;
        }
    }
    // writeln(idx___value);
    // writeln(good_idxes);
    int count = good_idxes.length;
    int good_len = good_idxes.length;
    int ans_idx = 0;
    foreach(good_idx; 0 .. good_len) {
        int curr_idx = good_idxes[good_idx];
        int next_idx = n;
        if (good_idx < good_len - 1) {
            next_idx = good_idxes[(good_idx + 1)];
        }
        curr_max_idx = -1;
        curr_max = -1;
        if (good_idx > 0) {
            curr_max_idx = good_idxes[(good_idx - 1)];
            curr_max = idx___value[curr_max_idx];
        }
        int[] to_add;
        foreach(idx; curr_idx + 1 .. next_idx) {
            if (idx___value[idx] > curr_max) {
                curr_max = idx___value[idx];
                curr_max_idx = idx;
                to_add ~= curr_max_idx;
            }
        }
        int curr_count = good_len - 1;
        curr_count += to_add.length;
        if (count < curr_count) {
            count = curr_count;
            ans_idx = curr_idx;
        }
        if (curr_count == count && idx___value[ans_idx] > idx___value[curr_idx]) {
            ans_idx = curr_idx;
        }
    }
    // writeln(count);
    if (count == good_idxes.length) {
        foreach(idx; 0 .. n) {
            if (!good_idxes.canFind(idx)) {
                // writeln("lexa");
                if (idx___value[idx] < idx___value[ans_idx]) {
                    ans_idx = idx;
                }
            }
        }
    }
    writeln(idx___value[ans_idx]);
}


You have a string $$$s_1 s_2 \ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \le k \le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the lexicographically smallest string you can see.

4
10
codeforces
9
cbacbacba
3
aaa
4
bbaa

NoteIn the first test case choose $$$k = 1$$$ to obtain "cc".In the second test case choose $$$k = 3$$$ to obtain "cbaabc".In the third test case choose $$$k = 1$$$ to obtain "aa".In the fourth test case choose $$$k = 1$$$ to obtain "bb".

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

bool lexsmaller2(int idx, string rs, int[] cache)
{
  if (cache[idx] != -1)
    return cast(bool)cache[idx];
  if (idx + 2 >= rs.length)
    return true;
  assert(idx + 2 < rs.length);
  if (rs[idx] < rs[idx + 2])
    return cache[idx] = 1;
  if (rs[idx] > rs[idx + 2])
    return cache[idx] = 0;

  return (cache[idx] = lexsmaller2(idx + 1, rs, cache)) != 0;
}

bool lexsmaller(char newch, int idx, string rs, int[] cache)
{
  if (newch < rs[idx])
    return true;
  if (newch > rs[idx])
    return false;

  if (idx + 1 >= rs.length)
    return false;

  if (newch < rs[idx + 1])
    return true;
  if (newch > rs[idx + 1])
    return false;
  return lexsmaller2(idx + 2, rs, cache);
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto s = readln.strip;
    auto rs = s.dup.reverse.idup;
    int ans = 0;
    int[] cache = new int[](n);
    cache[] = -1;
    foreach (k ; 1 .. n) {
      int idx = n - k;
      char newch = s[k];
      if (lexsmaller(newch, idx, rs, cache)) {
        ans = k;
      } else {
        break;
      }
    }
    writeln(s[0 .. ans + 1] ~ s[0 .. ans + 1].dup.reverse.idup);
  }
}

import std;

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

    foreach (test_index; 0 .. tests) {
        readln;

        immutable str = readln.chomp;

        immutable cut = (){
        immutable start = str[0];
        foreach (ret; 1 .. str.length)
                if (str[ret] == start || str[ret] > str[ret - 1])
                    return ret;
            return str.length;
        }();

        (
            str[0 .. cut]
            ~ str[0 .. cut]
                .byCodeUnit
                .retro
                .array
        ).writeln();
    }
}
// ""

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto S = cast(char[])scan;

      int k = 1;
      char last2 = S[0];
      char last = S[0];
      int eql;
      foreach(int i; 1..N) {
        // deb([i, k], [[last], [last2], [S[i]]]);
        if (i == 1) {
          if (last <= S[i]) break;
        } else {
          if (last < S[i] || last2 < S[i]) break;
        }

        last2 = last;
        last = S[i];
        k++;
      }

      return (S[0..k] ~ S[0..k].dup.reverse).to!string;
    }

    foreach(_; 0..QN) subSolve().writeln;
  }

  outputForAtCoder(&solve);
}

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

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

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

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

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

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

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

  return ok;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;

		alias mirror = len => s[0..len] ~ s[0..len].byChar.retro.array;

		int len = 1;
		bool first = true;
		int [] cand = [1, n];
		foreach (i; 0..n - 1)
		{
			if (s[i + 1] < s[i])
			{
				cand ~= i + 1;
			}
			if (s[i + 1] > s[i])
			{
				cand ~= i + 1;
				break;
			}
		}
		debug {writeln (cand);}
		cand.map !(mirror).minElement.writeln;
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const S = readToken;

        char[] ans;
        if (N >= 2 && S[0] == S[1]) {
          ans ~= S[0];
          ans ~= S[0];
        } else {
          char[] cs;
          foreach (i; 0 .. N) {
            if (i > 0 && S[i - 1] < S[i]) {
              break;
            }
            cs ~= S[i];
          }
          ans ~= cs;
          cs.reverse;
          ans ~= cs;
        }

        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

import std;

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

    foreach (test_index; 0 .. tests) {
        readln;

        immutable str = readln.chomp;

        immutable cut = (){
        foreach (ret; 1 .. str.length)
                if (str[ret] >= str[ret - 1])
                    return ret;
            return str.length;
        }();

        (
            str[0 .. cut]
            ~ str[0 .. cut]
                .byCodeUnit
                .retro
                .array
        ).writeln();
    }
}
// ""

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto S = cast(char[])scan;

      int k = 1;
      foreach(int i; 1..N) {
        if (S[i] >= S[i - 1]) break;
        k++;
      }

      return (S[0..k] ~ S[0..k].dup.reverse).to!string;
    }

    foreach(_; 0..QN) subSolve().writeln;
  }

  outputForAtCoder(&solve);
}

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

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

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

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

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

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

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

  return ok;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;

		alias mirror = len => s[0..len] ~ s[0..len].byChar.retro.array;

		int len = 1;
		bool first = true;
		int [] cand = [1, n];
		foreach (i; 0..n - 2)
		{
			if (s[i + 1] < s[i])
			{
				cand ~= i + 2;
			}
			if (s[i + 1] > s[i])
			{
				cand ~= i + 1;
				break;
			}
		}
		debug {writeln (cand);}
		cand.map !(mirror).minElement.writeln;
	}
}


Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.

The first line contains an integer n (1 ≤ n ≤ 1000).

On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.

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

const int[] dx = [1, 0, -1, 0];
const int[] dy = [0, 1, 0, -1];

void main() {
    int n; readf("%d\n", &n);
    char[][] F = new char[][n];
    for (int i = 0; i < n; i++) F[i] = new char[n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            F[i][j] = '?';
    int c = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (F[i][j] == '?') {
                F[i][j] = 'C';
                c++;
                for (int k = 0; k < 4; k++) {
                    if (0 <= i + dy[k] && i + dy[k] < n && 0 <= j + dx[k] && j + dx[k] < n)
                        F[i + dy[k]][j + dx[k]] = '.';
                }
            }
        }
    }
    c.writeln;
    F.join("\n").writeln;
}

/** CodeForces Problem 384.A (1)
 * ACM summer training contest (3)
 * Noein
 */

import std.stdio;

T mut(T)(in T inval) {
    import std.traits;

    return cast(Unqual!T) inval;
}

T imut(T)(in T inval) {
    //import std.traits;

    return cast(immutable) inval;
}

void main() {
    int n;

    readf("%s\n", &n);

    const bool odd = cast(bool) (n % 2);

    auto r = odd? n+1 : n;

    const result = (r * r / 2) - ( (odd) ? n : 0 );

    auto bitf = odd.mut;

    auto repr_str = "";

    for( int y; y < n; ++ y ) {
        for( int x; x < n; ++x ) {
            repr_str ~= ( (bitf) ? "C" : "." );
            bitf ^= true;
        }
        repr_str ~= "\n";
        if(!odd) bitf ^= true;
    }

    writeln(result, "\n", repr_str);
}

/** CodeForces Problem 384.A (1)
 * ACM summer training contest (3)
 * Noein
 */

import std.stdio;

void main() {
    int n;

    readf("%s\n", &n);

    const bool odd = cast(bool) (n % 2);

    const result = (n * n / 2) - ( (odd) ? n : 0 );

    auto bitf = false;

    auto repr_str = "";

    for( int y; y < n; ++ y ) {
        for( int x; x < n; ++x ) {
            repr_str ~= ( (bitf) ? "C" : "." );
            bitf ^= true;
        }
        repr_str ~= "\n";
        if(!odd) bitf ^= true;
    }

    writeln(repr_str);
}

/** CodeForces Problem 384.A (1)
 * ACM summer training contest (3)
 * Noein
 */

import std.stdio;

void main() {
    int n;

    readf("%s\n", &n);

    const bool odd = cast(bool) (n % 2);

    const result = (n * n / 2) - ( (odd) ? n : 0 );

    auto bitf = false;

    auto repr_str = "";

    for( int y; y < n; ++ y ) {
        for( int x; x < n; ++x ) {
            repr_str ~= ( (bitf) ? "C" : "." );
            bitf ^= true;
        }
        repr_str ~= "\n";
        if(!odd) bitf ^= true;
    }

    writeln(result, "\n", repr_str);
}


You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$. All elements of both arrays are from $$$0$$$ to $$$n-1$$$.You can reorder elements of the array $$$b$$$ (if you want, you may leave the order of elements as it is). After that, let array $$$c$$$ be the array of length $$$n$$$, the $$$i$$$-th element of this array is $$$c_i = (a_i + b_i) \% n$$$, where $$$x \% y$$$ is $$$x$$$ modulo $$$y$$$.Your task is to reorder elements of the array $$$b$$$ to obtain the lexicographically minimum possible array $$$c$$$.Array $$$x$$$ of length $$$n$$$ is lexicographically less than array $$$y$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$x_j = y_j$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$, $$$b$$$ and $$$c$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i < n$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.

Print the lexicographically minimum possible array $$$c$$$. Recall that your task is to reorder elements of the array $$$b$$$ and obtain the lexicographically minimum possible array $$$c$$$, where the $$$i$$$-th element of $$$c$$$ is $$$c_i = (a_i + b_i) \% n$$$.

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

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

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

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

    auto rbt = make!(RedBlackTree!(int, "a < b", true))(b);

    debug { rbt.writeln; }

    int[] ans;
    foreach (e; a) {
        auto mn = (n - e - 1 + n) % n;
        auto upper = rbt.upperBound(mn);
        auto up = upper.empty() ? rbt.front : upper.front;
        debug { writeln(e, ' ', mn, ' ', upper, ' ', rbt.front, ' ', up); }

        ans ~= (e + up) % n;
        rbt.removeKey(up);
    }

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

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		auto t = redBlackTree !(q{a < b}, true) (b);
		debug {writeln (t);}

		int [] c;
		foreach (i; 0..n)
		{
			auto f = t.upperBound ((n - a[i]) % n - 1);
			if (f.empty)
			{
				f = t.upperBound (0 - 1);
			}
			auto v = f.front;
			c ~= (a[i] + v) % n;
			t.removeKey (v);
		}
		writefln ("%(%s %)", c);
	}
}


You are given an undirected graph consisting of $$$n$$$ vertices and $$$n$$$ edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$ are considered the same.You have to answer $$$t$$$ independent test cases.Recall that a path in the graph is a sequence of vertices $$$v_1, v_2, \ldots, v_k$$$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices (and the number of edges) in the graph. The next $$$n$$$ lines of the test case describe edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices the $$$i$$$-th edge connects. For each pair of vertices $$$(u, v)$$$, there is at most one edge between $$$u$$$ and $$$v$$$. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print one integer: the number of simple paths of length at least $$$1$$$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).

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 adj = new bool [int] [n];
		foreach (i; 0..n)
		{
			auto vs = readln.splitter.map !(to !(int)).array;
			vs[] -= 1;
			adj[vs[0]][vs[1]] = true;
			adj[vs[1]][vs[0]] = true;
		}

		auto vis = new int [n];
		bool removed = false;

		bool recur (int v, int p)
		{
			if (vis[v] == 1)
			{
				vis[v] = 3;
				return false;
			}
			if (vis[v] != 0)
			{
				return true;
			}
			vis[v] = 1;
			foreach (u, _; adj[v])
			{
				if (u != p)
				{
					if (!recur (u, v))
					{
						if (!removed)
						{
							adj[u].remove (v);
							adj[v].remove (u);
						}
						if (vis[v] == 3)
						{
							removed = true;
						}
						return false;
					}
				}
			}
			vis[v] = 2;
			return true;
		}

		recur (0, -1);
		vis[] = 0;

		int num (int v)
		{
			if (vis[v] == 1)
			{
				return 0;
			}
			vis[v] = 1;
			int res = 1;
			foreach (u, _; adj[v])
			{
				res += num (u);
			}
			return res;
		}

		long res = n * (n - 1L);
		foreach (i; 0..n)
		{
			auto cur = num (i);
			res -= cur * (cur - 1L) / 2;
		}
		writeln (res);
	}
}


This is an interactive problem!Ehab plays a game with Laggy. Ehab has 2 hidden integers $$$(a,b)$$$. Laggy can ask a pair of integers $$$(c,d)$$$ and Ehab will reply with:  1 if $$$a \oplus c>b \oplus d$$$.  0 if $$$a \oplus c=b \oplus d$$$.  -1 if $$$a \oplus c<b \oplus d$$$. Operation $$$a \oplus b$$$ is the bitwise-xor operation of two numbers $$$a$$$ and $$$b$$$.Laggy should guess $$$(a,b)$$$ with at most 62 questions. You'll play this game. You're Laggy and the interactor is Ehab.It's guaranteed that $$$0 \le a,b<2^{30}$$$.

To print the answer, print "! a b" (without quotes). Don't forget to flush the output after printing the answer.

NoteIn the sample:The hidden numbers are $$$a=3$$$ and $$$b=1$$$.In the first query: $$$3 \oplus 2 = 1$$$ and $$$1 \oplus 1 = 0$$$, so the answer is 1.In the second query: $$$3 \oplus 1 = 2$$$ and $$$1 \oplus 2 = 3$$$, so the answer is -1.In the third query: $$$3 \oplus 2 = 1$$$ and $$$1 \oplus 0 = 1$$$, so the answer is 0.Then, we printed the answer.

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

void main() {
  int a = 0, b = 0;
  int less = -2;
  foreach(i; iota(29,-1,-1)) {
    debug {writeln(i);}
    int query(int x, int y) {
      x <<= i; y <<= i;
      x ^= a; y ^= b;
      writefln!"? %d %d" (x,y);
      stdout.flush;
      return readln.strip.to!int;
    }
    void set(int x, int y) {
      x <<= i; y <<= i;
      a ^= x; b ^= y;
    }
    if(less == -2) less = query(0,0);
    int k = query(1,1);
    if(less != k) {
      set(less > 0, less < 0);
      less = -2;
      continue;
    }
    k = query(0,1);
    set(k > 0, k > 0);
  }
  writefln!"! %d %d" (a,b);
}

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 int M = 30;
long x, y;
int cnt = 0;

int ask(long c, long d) {
    debug {
        cnt += 1;
        if ((x^c) > (y^d)) return 1;
        else if ((x^c) == (y^d)) return 0;
        else return -1;
    }

    writeln("? ", c, " ", d);
    stdout.flush;
    return readln.chomp.to!int;
}

void answer(long a, long b) {
    writeln("! ", a, " ", b);
    stdout.flush;
}

void main() {
    debug {
        auto s = readln.split.map!(to!long);
        x = s[0];
        y = s[1];
    }

    int f = ask(0, 0);
    int ff = f;

    if (f == 0) {
        long a = 0;
        foreach_reverse (i; 0..M) {
            long c = (1L << (i + 1)) - 1;
            long d = (1L << i) - 1;
            c += a;
            d += a;
            f = ask(c, d);
            if (f == -1) {
                a += 1L << i;
            }
        }
        answer(a, a);
        return;
    }

    bool a_large = f == 1;
    long a = 0;
    long b = 0;
    auto same = new bool[](M);

    foreach_reverse (i; 0..M) {
        long c = 1L << i;
        f = ask(a+c, b+c);
        if (a_large && f == -1) {
            a += c;
            f = ask(a, b);
            a_large = f == 1;
        } else if (!a_large && f == 1) {
            b += c;
            f = ask(a, b);
            a_large = f == 1;
        } else {
            same[i] = true;
        }
    }

    foreach (i; 0..M) {
        if (!same[i]) {
            continue;
        }
        long c = 1L << i;
        f = ask(a+c, b);
        if (f == -1) {
            a += c;
            b += c;
        }
    }

    answer(a, b);
    debug{cnt.writeln;}
}


You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints.

For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists.

NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$.

import std.stdio;

void main() {
    uint t, x, y, n, b;

    scanf("%d", &t);

    while(t--) {
        uint ans;
        scanf("%d %d %d", &x, &y, &n);

        if(x > n) ans = 0;

        b = n % x;
        if(b == y)
            ans = n;
        else if(b > y)
            ans = n - (b -y);
        else
            ans = n - b - (x - y);

        printf("%d\n", ans);
    }
}

import std.stdio;

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

  foreach (i; 0..t) {
    long x, y, n;
    readf!"%d %d %d\n"(x, y, n);

    auto r = n - n % x + y;
    if (r > n) {
      r -= x;
    }

    writeln(r);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int x, y, n;
		readf !(" %s %s %s") (x, y, n);
		n -= y;
		n -= n % x;
		n += y;
		writeln (n);
	}
}


You have one chip and one chance to play roulette. Are you feeling lucky?

Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).

// xxxxx
import std.random;
import std.stdio;

void main ()
{
	rndGen.seed (unpredictableSeed);
	writeln (uniform (0, 2) ? "Even" : "Odd");
}

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

void main(){

	writeln("Odd");

}

import std.stdio;

void main ()
{
	writeln ("Even");
}

import std.stdio;

void main ()
{
	writeln (25);
}

// xxx
import std.random;
import std.stdio;

void main ()
{
	rndGen.seed (unpredictableSeed);
	writeln (uniform (0, 2) ? "Even" : "Odd");
}

import std.stdio;

void main ()
{
	writeln ("Odd");
}

// xxxx
import std.random;
import std.stdio;

void main ()
{
	rndGen.seed (unpredictableSeed);
	writeln (uniform (0, 2) ? "Even" : "Odd");
}

// x
import std.random;
import std.stdio;

void main ()
{
	rndGen.seed (unpredictableSeed);
	writeln (uniform (0, 2) ? "Even" : "Odd");
}

// xx
import std.random;
import std.stdio;

void main ()
{
	rndGen.seed (unpredictableSeed);
	writeln (uniform (0, 2) ? "Even" : "Odd");
}

import std.stdio;
import std.string;

void main ()
{
	readln.strip.writeln;
}

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

void main(){

	writeln("Even");

}