You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.Some long and uninteresting story was removed...The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter x is denoted by x'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2 < 3, 2' < 3', 3' < 2.A word x1, x2, ..., xa is not lexicographically greater than y1, y2, ..., yb if one of the two following conditions holds:   a ≤ b and x1 = y1, ..., xa = ya, i.e. the first word is the prefix of the second word;  there is a position 1 ≤ j ≤ min(a, b), such that x1 = y1, ..., xj - 1 = yj - 1 and xj < yj, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.  For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.Note that some words can be equal.

The first line contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to m. Each of the next n lines contains a description of one word in format li, si, 1, si, 2, ..., si, li (1 ≤ li ≤ 100 000, 1 ≤ si, j ≤ m), where li is the length of the word, and si, j is the sequence of letters in the word. The words are given in the order Denis has them in the sequence. It is guaranteed that the total length of all words is not greater than 100 000.

In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes). If the required is possible, in the second line print k — the number of letters Denis has to capitalize (make large), and in the third line print k distinct integers — these letters. Note that you don't need to minimize the value k. You can print the letters in any order. If there are multiple answers, print any of them.

NoteIn the first example after Denis makes letters 2 and 3 large, the sequence looks like the following:  2'  1  1 3' 2'  1 1 The condition 2' < 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' < 1, then the third word is not lexicographically larger than the fourth word.In the second example the words are in lexicographical order from the beginning, so Denis can do nothing.In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.

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

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

int main() {
    Scanner sc = new Scanner(stdin);
    int n, m;
    sc.read(n, m);
    auto sat = TwoSat(m);
    int[][] g = new int[][n];
    foreach (i; 0..n) {
        int k;
        sc.read(k);
        g[i] = new int[k];
        foreach (j; 0..k) {
            sc.read(g[i][j]);
        }
        g[i][] -= 1;
    }

    foreach (i; 0..n-1) {
        //g[i], g[i+1]
        int mi = min(g[i].length, g[i+1].length).to!int;
        bool dif = false;
        foreach (j; 0..mi) {
            int x = g[i][j];
            int y = g[i+1][j];
            if (x != y) {
                dif = true;
                if (x > y) {
                    //only true, false
                    sat.addCond(x, true, y, false);
                    sat.addCond(x, false, y, false);
                    sat.addCond(x, true, y, true);
                } else {
                    //only ~(false, true)
                    sat.addCond(x, true, y, false);
                }
                break;
            }
        }
        if (!dif) {
            if (g[i].length > g[i+1].length) {
                writeln("No");
                return 0;
            }
        }
    }
    if (!sat.exec()) {
        writeln("No");
        return 0;
    }
    auto res = sat.res.enumerate.filter!"a[1]==true".array;
    writeln("Yes");
    writeln(res.length);
    writeln(res.map!"a[0]+1".map!(to!string).join(" "));
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/twosat.d */

// module dcomp.twosat;

// import dcomp.graph.scc;
// import dcomp.array;

struct TwoSat {

    bool[] res;

    struct Edge {int to;}
    FastAppender!(Edge[])[] g;

    void addCond(int a, bool aExp, int b, bool bExp) {
        g[2*a+(aExp?0:1)] ~= Edge(2*b+(bExp?1:0));
        g[2*b+(bExp?0:1)] ~= Edge(2*a+(aExp?1:0));
    }

    bool exec() {
        import std.array : array;
        import std.algorithm : map;
        import std.conv : to;
        int n = res.length.to!int;
        auto sccInfo = scc(g.map!(v => v.data).array);
        for (int i = 0; i < n; i++) {
            if (sccInfo.id[2*i] == sccInfo.id[2*i+1]) return false;
            res[i] = sccInfo.id[2*i] < sccInfo.id[2*i+1];
        }
        return true;
    }

    this(int n) {
        res = new bool[n];
        g = new FastAppender!(Edge[])[](2*n);
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/graph/scc.d */
// module dcomp.graph.scc;

// import dcomp.array;
// import dcomp.graph.primitive;
// import dcomp.container.deque;

struct SCCInfo {
    int[] id;
    int[][] groups;

    int[] group(int i) {
        return groups[id[i]];
    }
    this(int n) {
        id = new int[n];
    }
}

SCCInfo scc(T)(T g) {
    import std.range;
    import std.algorithm : each, map, min, reverse;
    import std.conv : to;
    int n = g.length.to!int;
    auto sccInfo = SCCInfo(n);
    with (sccInfo) {
        bool[] inS = new bool[n];
        int[] low = new int[n], ord = new int[n]; ord[] = -1;
        int time = 0;
        Deque!int st;
        int bufC = 0;
        FastAppender!(int[]) buf; buf.reserve(n);
        FastAppender!(int[][]) gBuf;
        void dfs(int v) {
            low[v] = ord[v] = time++;
            st.insertBack(v);
            inS[v] = true;
            foreach (e; g[v]) {
                if (ord[e.to] == -1) {
                    dfs(e.to);
                    low[v] = min(low[v], low[e.to]);
                } else if (inS[e.to]) {
                    low[v] = min(low[v], ord[e.to]);
                }
            }
            if (low[v] == ord[v]) {
                while (true) {
                    int u = st.back; st.removeBack;
                    buf ~= u;
                    if (u == v) break;
                }
                auto gr = buf.data[bufC..$];
                bufC = buf.length.to!int;
                gr.each!(x => inS[x] = false);
                gBuf ~= gr;
            }
        }
        foreach (i; 0..n) {
            if (ord[i] == -1) dfs(i);
        }
        groups = gBuf.data;
        reverse(groups);
        groups.each!((i, v) => v.each!(x => id[x] = i.to!int));
    }
    return sccInfo;
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/container/deque.d */
// module dcomp.container.deque;

struct DequePayload(T) {
    import core.exception : RangeError;
    import core.memory : GC;
    import std.range : ElementType, isInputRange;
    import std.traits : isImplicitlyConvertible;
    T *d;
    size_t st, length, cap;
    @property bool empty() const { return length == 0; }
    alias opDollar = length;
    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (length <= i) throw new RangeError();
        return d[(st+i >= cap) ? (st+i-cap) : st+i];
    }
    private void expand() {
        import std.algorithm : max;
        assert(length == cap);
        auto nc = max(size_t(4), 2*cap);
        T* nd = cast(T*)GC.malloc(nc * T.sizeof);
        foreach (i; 0..length) {
            nd[i] = this[i];
        }
        d = nd; st = 0; cap = nc;
    }
    void clear() {
        st = length = 0;
    }
    void insertFront(T v) {
        if (length == cap) expand();
        if (st == 0) st += cap;
        st--; length++;
        this[0] = v;
    }
    void insertBack(T v) {
        if (length == cap) expand();
        length++;
        this[length-1] = v;
    }
    void removeFront() {
        assert(!empty, "Deque.removeFront: Deque is empty");
        st++; length--;
        if (st == cap) st = 0;
    }
    void removeBack() {
        assert(!empty, "Deque.removeBack: Deque is empty");
        length--;
    }

    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }
    Range opSlice() {return Range(&this, 0, length); }

    alias Range = RangeT!(DequePayload!T);
    alias ConstRange = RangeT!(const DequePayload!T);
    alias ImmutableRange = RangeT!(immutable DequePayload!T);

    static struct RangeT(A) {
        import std.traits : CopyTypeQualifiers;
        alias E = CopyTypeQualifiers!(A, T);
        A *p;
        size_t a, b;
        @property bool empty() const { return b <= a; }
        @property size_t length() const { return b-a; }
        @property RangeT save() { return RangeT(p, a, b); }
        @property RangeT!(const A) save() const {
            return typeof(return)(p, a, b);
        }
        alias opDollar = length;
        @property ref inout(E) front() inout { return (*p)[a]; }
        @property ref inout(E) back() inout { return (*p)[b-1]; }
        void popFront() {
            version(assert) if (empty) throw new RangeError();
            a++;
        }
        void popBack() {
            version(assert) if (empty) throw new RangeError();
            b--;
        }
        ref inout(E) opIndex(size_t i) inout { return (*p)[i]; }
        RangeT opSlice() { return this.save; }
        RangeT opSlice(size_t i, size_t j) {
            version(assert) if (i > j || a + j > b) throw new RangeError();
            return typeof(return)(p, a+i, a+j);
        }
        RangeT!(const A) opSlice() const { return this.save; }
        RangeT!(const A) opSlice(size_t i, size_t j) const {
            version(assert) if (i > j || a + j > b) throw new RangeError();
            return typeof(return)(p, a+i, a+j);
        }
    }
}

struct Deque(T, bool mayNull = true) {
    import core.exception : RangeError;
    import core.memory : GC;
    import std.range : ElementType, isInputRange;
    import std.traits : isImplicitlyConvertible;

    alias Payload = DequePayload!T;
    alias Range = Payload.Range;
    alias ConstRange = Payload.ConstRange;
    alias ImmutableRange = Payload.ImmutableRange;

    Payload* p;
    private void I() { if (mayNull && !p) p = new Payload(); }
    private void C() const {
        version(assert) if (mayNull && !p) throw new RangeError();
    }
    static if (!mayNull) {
        @disable this();
    }

    private this(Payload* p) {
        this.p = p;
    }
    this(U)(U[] values...) if (isImplicitlyConvertible!(U, T)) {
        p = new Payload();
        foreach (v; values) {
            insertBack(v);
        }
    }

    this(Range)(Range r)
    if (isInputRange!Range &&
    isImplicitlyConvertible!(ElementType!Range, T) &&
    !is(Range == T[])) {
        p = new Payload();
        foreach (v; r) {
            insertBack(v);
        }
    }
    static Deque make() { return Deque(new Payload()); }
    @property bool havePayload() const { return (!mayNull || p); }

    @property bool empty() const { return (!havePayload || p.empty); }

    @property size_t length() const { return (havePayload ? p.length : 0); }

    alias opDollar = length;
    ref inout(T) opIndex(size_t i) inout {C; return (*p)[i]; }

    ref inout(T) front() inout {C; return (*p)[0]; }

    ref inout(T) back() inout {C; return (*p)[$-1]; }
    void clear() { if (p) p.clear(); }

    void insertFront(T v) {I; p.insertFront(v); }

    void insertBack(T v) {I; p.insertBack(v); }

    alias stableInsertBack = insertBack;

    void removeFront() {C; p.removeFront(); }

    void removeBack() {C; p.removeBack(); }

    Range opSlice() {I; return Range(p, 0, length); }
}

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

// import dcomp.array;

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 {
                FastAppender!(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/graph/primitive.d */
// module dcomp.graph.primitive;

import std.range : ElementType;
alias EdgeType(R) = ElementType!(ElementType!R);
/* 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);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    import core.bitop : bsf, bsr, popcnt;
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

T[N] fixed(T, size_t N)(T[N] a) {return a;}

struct FastAppender(A, size_t MIN = 4) {
    import std.algorithm : max;
    import std.conv;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

    private alias T = ElementEncodingType!A;
    private T* _data;
    private uint len, cap;

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

    void reserve(size_t nlen) {
        import core.memory : GC;
        if (nlen <= cap) return;

        void* nx = GC.malloc(nlen * T.sizeof);

        cap = nlen.to!uint;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void opOpAssign(string op : "~")(T item) {
        if (len == cap) {
            reserve(max(MIN, cap*2));
        }
        _data[len++] = item;
    }

    void insertBack(T item) {
        this ~= item;
    }

    void removeBack() {
        len--;
    }

    void clear() {
        len = 0;
    }
    ref inout(T) back() inout { assert(len); return _data[len-1]; }
    ref inout(T) opIndex(size_t i) inout { return _data[i]; }

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

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

Tuple!(int, int[]) scc(in int[][][] graph) {
  const n = cast(int)(graph[0].length);
  int compN;
  auto compIds = new int[n];
  int[] us;
  void dfs(int s, int u, int a, int b) {
    if (compIds[u] == a) {
      compIds[u] = b;
      foreach (v; graph[s][u]) {
        dfs(s, v, a, b);
      }
      if (s == 0) {
        us ~= u;
      }
    }
  }
  foreach (u; 0 .. n) {
    dfs(0, u, 0, -1);
  }
  foreach_reverse (u; us) {
    if (compIds[u] == -1) {
      dfs(1, u, -1, compN);
      ++compN;
    }
  }
  return tuple(compN, compIds);
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto L = new int[N];
      auto S = new int[][N];
      foreach (i; 0 .. N) {
        L[i] = readInt();
        S[i] = new int[L[i]];
        foreach (j; 0 .. L[i]) {
          S[i][j] = readInt() - 1;
        }
      }

      bool ans = true;
      auto graph = new int[][][](2, M << 1);
      void addEdge(int x, int y) {
        graph[0][x] ~= y;
        graph[1][y] ~= x;
      }

      foreach (i; 0 .. N - 1) {
        for (int j = 0; ; ++j) {
          if (j == L[i]) {
            break;
          } else if (j == L[i + 1]) {
            ans = false;
            break;
          } else {
            const u = S[i][j], v = S[i + 1][j];
            if (u < v) {
              // CAP(u) || NOCAP(v)
              addEdge(u << 1 | 0, v << 1 | 0);
              addEdge(v << 1 | 1, u << 1 | 1);
              break;
            } else if (u > v) {
              // CAP(u) && NOCAP(v)
              addEdge(u << 1 | 0, u << 1 | 1);
              addEdge(v << 1 | 1, v << 1 | 0);
              break;
            }
          }
        }
      }
      auto res = scc(graph);
      foreach (u; 0 .. M) {
        ans = ans && (res[1][u << 1 | 0] != res[1][u << 1 | 1]);
      }
      if (ans) {
        int[] us;
        foreach (u; 0 .. M) {
          if (res[1][u << 1 | 0] < res[1][u << 1 | 1]) {
            us ~= u;
          }
        }
        writeln("Yes");
        writeln(us.length);
        foreach (index, u; us) {
          if (index > 0) write(" ");
          write(u + 1);
        }
        writeln;
      } else {
        writeln("No");
      }
    }
  } catch (EOFException e) {
  }
}


Given an integer $$$n$$$, find any array $$$a$$$ of $$$n$$$ distinct nonnegative integers less than $$$2^{31}$$$ such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 629$$$) — the number of test cases. Then $$$t$$$ lines follow, each containing a single integer $$$n$$$ $$$(3 \leq n \leq 2\cdot10^5)$$$ — the length of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output one line containing $$$n$$$ distinct integers that satisfy the conditions. If there are multiple answers, you can output any of them.

NoteIn the first test case the XOR on odd indices is $$$4 \oplus 1 \oplus 0 \oplus 7 = 2$$$ and the XOR on even indices is $$$2 \oplus 5 \oplus 6 \oplus 3= 2$$$.

import std.stdio;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void solve() {
    int n = readln.chomp.to!int;

    if (n == 3) {
        writeln("2 1 3");
        return;
    }

    int[] x, y;
    if (n % 2 == 1) {
        x ~= 0;
    }
    int flip = 0;
    for (int i = 1; i <= n/2; i++) {
        x ~= (i | ((flip)<<20));
        y ~= (i | ((!flip)<<20));
        flip = !flip;
    }

    if (n % 4 == 2 || n % 4 == 3) {
        x[$-1] |= (1<<20);
        x[$-1] |= (1<<19);
        y[$-2] |= (1<<19);
    }

    int[] ans = new int[n];
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            ans[i] = x[i/2];
        } else {
            ans[i] = y[i/2];
        }
    }

    // check
    int sx = 0, sy = 0;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            sx ^= ans[i];
        } else {
            sy ^= ans[i];
        }
    }
    assert(sx == sy);
    assert(ans.sort.uniq.array.length == n);

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

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

import std.stdio;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void solve() {
    int n = readln.chomp.to!int;
    int[] x, y;
    if (n % 2 == 1) {
        x ~= 0;
    }
    int flip = 0;
    for (int i = 1; i <= n/2; i++) {
        x ~= (i | ((flip)<<20));
        y ~= (i | ((!flip)<<20));
        flip = !flip;
    }
    int[] ans = new int[n];
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            ans[i] = x[i/2];
        } else {
            ans[i] = y[i/2];
        }
    }

    // check
    int sx = 0, sy = 0;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            sx ^= ans[i];
        } else {
            sy ^= ans[i];
        }
    }
    assert(sx == sy);

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

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


Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.

The first line contains an integer n (1 ≤ n ≤ 5·105) — the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≤ xi ≤ 1023.

Output an integer k (0 ≤ k ≤ 5) — the length of your program. Next k lines must contain commands in the same format as in the input.

NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.

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;

void main() {
    auto N = readln.chomp.to!int;
    auto X = new int[][](10, 2);
    foreach (i; 0..10) X[i][0] = 0;
    foreach (i; 0..10) X[i][1] = 1;

    foreach (i; 0..N) {
        auto s = readln.split;
        auto op = s[0];
        auto n = s[1].to!int;
        foreach (j; 0..10) {
            bool b = (n & (1 << j)) != 0;
            if (op[0] == '|') {
                X[j][0] |= b;
                X[j][1] |= b;
            } else if (op[0] == '&') {
                X[j][0] &= b;
                X[j][1] &= b;
            } else {
                X[j][0] ^= b;
                X[j][1] ^= b;
            }
        }
    }

    int opor = 0;
    int opand = 0;
    int opxor = 0;

    foreach (i; 0..10) {
        if (X[i][0] == 0 && X[i][1] == 0) {

        } else if (X[i][0] == 0 && X[i][1] == 1) {
            opand |= (1 << i);
        } else if (X[i][0] == 1 && X[i][1] == 0) {
            opand |= (1 << i);
            opxor |= (1 << i);
        } else {
            opor |= (1 << i);
            opand |= (1 << i);
        }
    }

    writeln(3);
    writeln("| ", opor);
    writeln("& ", opand);
    writeln("^ ", opxor);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

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

enum Action { none, flip, set, unset }

void main() {
    int n;
    while (read(n)) {
        Action[10] bits;
        while (n--) {
            char c;
            int x;
            read(c, x);
            final switch (c) {
                case '&': {
                    foreach (i; 0 .. 10) {
                        if (!(x & 0x1))
                            bits[i] = Action.unset;
                        x >>= 1;
                    }
                    break;
                }
                case '|': {
                    foreach (i; 0 .. 10) {
                        if (x & 0x1)
                            bits[i] = Action.set;
                        x >>= 1;
                    }
                    break;
                }
                case '^': {
                    foreach (i; 0 .. 10) {
                        if (x & 0x1)
                            bits[i] ^= 0x1;
                        x >>= 1;
                    }
                    break;
                }
            }
        }

        auto accumulate(Action action)() {
            return iota(10).filter!(i => bits[i] == action).fold!`a | 1 << b`(0x0);
        }

        write("3\n& ", accumulate!(Action.unset) ^ 0x3FF);
        write("\n| ", accumulate!(Action.set));
        writeln("\n^ ", accumulate!(Action.flip));
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}

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

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

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

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

enum E = 10;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new string[N];
      auto X = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readToken();
        X[i] = readInt();
      }

      int[] ans = [(1 << E) - 1, 0, 0];
      foreach (e; 0 .. E) {
        auto ts = new int[2];
        foreach (s; 0 .. 2) {
          int z = s << e;
          foreach (i; 0 .. N) {
            switch (A[i]) {
              case "&": z &= X[i]; break;
              case "|": z |= X[i]; break;
              case "^": z ^= X[i]; break;
              default: assert(false);
            }
          }
          ts[s] = (z >> e) & 1;
        }
        debug {
          writeln(e, ": ", ts);
        }
        switch (ts[0] << 0 | ts[1] << 1) {
          case 0: ans[0] ^= 1 << e; break;
          case 1: ans[2] ^= 1 << e; break;
          case 2: break;
          case 3: ans[1] ^= 1 << e; break;
          default: assert(false);
        }
      }
      writeln(3);
      writefln("& %s", ans[0]);
      writefln("| %s", ans[1]);
      writefln("^ %s", ans[2]);

      debug {
        foreach (z; 0 .. 1 << E) {
          int expected = z;
          foreach (i; 0 .. N) {
            switch (A[i]) {
              case "&": expected &= X[i]; break;
              case "|": expected |= X[i]; break;
              case "^": expected ^= X[i]; break;
              default: assert(false);
            }
          }
          int actual = z;
          actual &= ans[0];
          actual |= ans[1];
          actual ^= ans[2];
          assert(expected == actual);
        }
      }
    }
  } catch (EOFException e) {
  }
}


You are given a palindromic string $$$s$$$ of length $$$n$$$.You have to count the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome. For example, consider $$$s$$$ = "aba"  If we remove $$$s_1$$$ from $$$s$$$, the string becomes "ba" which is not a palindrome.  If we remove $$$s_2$$$ from $$$s$$$, the string becomes "aa" which is a palindrome.  If we remove $$$s_3$$$ from $$$s$$$, the string becomes "ab" which is not a palindrome. A palindrome is a string that reads the same backward as forward. For example, "abba", "a", "fef" are palindromes whereas "codeforces", "acd", "xy" are not.

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3)$$$  — the number of test cases. Description of the test cases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$  — the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of lowercase English letters. It is guaranteed that $$$s$$$ is a palindrome. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer  — the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome.

NoteThe first test case is described in the statement.In the second test case, the indices $$$i$$$ that result in palindrome after removing $$$s_i$$$ are $$$3, 4, 5, 6$$$. Hence the answer is $$$4$$$. In the third test case, removal of any of the indices results in "d" which is a palindrome. Hence the answer is $$$2$$$.

void main() { runSolver(); }

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

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

      int ans;
      foreach_reverse(i; 0..(N - 1)/2 + 1) {
        if (S[i] == S[(N - 1) / 2]) ans++; else break;
      }

      return ans * 2 - (N & 1);
    }

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

  outputForAtCoder(&solve);
}

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

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

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

void main() { runSolver(); }

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

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

      int ans;
      foreach(i; 0..(N - 1)/2 + 1) {
        if (S[i] == S[(N - 1) / 2]) ans++;
      }

      return ans * 2 - (N & 1);
    }

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

  outputForAtCoder(&solve);
}

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

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

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

void main() { runSolver(); }

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

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

      return N.iota.count!(i => S[i] == S[N / 2]);
    }

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

  outputForAtCoder(&solve);
}

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

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

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Initially all elements of $$$a$$$ are either $$$0$$$ or $$$1$$$. You need to process $$$q$$$ queries of two kinds:  1 x : Assign to $$$a_x$$$ the value $$$1 - a_x$$$.  2 k : Print the $$$k$$$-th largest value of the array. As a reminder, $$$k$$$-th largest value of the array $$$b$$$ is defined as following: Sort the array in the non-increasing order, return $$$k$$$-th element from it. For example, the second largest element in array $$$[0, 1, 0, 1]$$$ is $$$1$$$, as after sorting in non-increasing order it becomes $$$[1, 1, 0, 0]$$$, and the second element in this array is equal to $$$1$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the length of the given array and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — elements of the initial array. Each of the following $$$q$$$ lines contains two integers. The first integer is $$$t$$$ ($$$1 \le t \le 2$$$) — the type of query.   If $$$t = 1$$$ the second integer is $$$x$$$ ($$$1 \le x \le n$$$) — the position of the modified number. You have to assign to $$$a_x$$$ the value $$$1 - a_x$$$. If $$$t = 2$$$ the second integer is $$$k$$$ ($$$1 \le k \le n$$$) — you need to print the $$$k$$$-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying $$$t = 2$$$).

For each query of the second type, print a single integer — the answer to the query.

NoteInitially $$$a = [1, 1, 0, 1, 0]$$$.The first operation is printing the third largest value, which is $$$1$$$.The second operation is assigning $$$a_2$$$ the value $$$0$$$, $$$a$$$ becomes $$$[1, 0, 0, 1, 0]$$$.The third operation is printing the third largest value, it is $$$0$$$.The fourth operation is printing the first largest value, it is $$$1$$$.The last operation is printing the fifth largest value, it is $$$0$$$.

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

void main ()
{
	int n, q;
	while (readf !(" %s %s") (n, q) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto s = sum (a);
		foreach (r; 0..q)
		{
			int t, z;
			readf !(" %s %s") (t, z);
			if (t == 1)
			{
				auto x = z - 1;
				s -= (a[x] == 1);
				a[x] ^= 1;
				s += (a[x] == 1);
			}
			else
			{
				auto k = z;
				writeln (to !(int) (k <= s));
			}
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto q = RD!int;
	auto a = RDA;

	long cnt = a.sum;
	long[] ans;
	foreach (i; 0..q)
	{
		auto t = RD!int;
		if (t == 1)
		{
			auto x = RD!int-1;
			if(a[x] == 1)
			{
				--cnt;
				a[x] = 0;
			}
			else
			{
				++cnt;
				a[x] = 1;
			}
		}
		else
		{
			auto k = RD!int;
			if (k <= cnt)
				ans ~= 1;
			else
				ans ~= 0;
		}
	}

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

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

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

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

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

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

      auto as = A.dup;
      int now = cast(int)(as.count(1));

      foreach (q; 0 .. Q) {
        const typ = readInt();
        if (typ == 1) {
          const x = readInt() - 1;
          if (as[x] == 1) --now;
          as[x] = 1 - as[x];
          if (as[x] == 1) ++now;
        } else {
          const k = readInt();
          writeln((now >= k) ? 1 : 0);
        }
      }
    }
  } catch (EOFException e) {
  }
}


One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.

Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.

NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

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

        int read_int() {
                return read_string.to!int;
        }

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int m = cin.read_int;
                int count = 0;
                for (int i = 0; i < n; i++) {
                        for (int j = 0; j < m; j++) {
                                int a = cin.read_int;
                                int b = cin.read_int;
                                if (a || b) count++;
                        }
                }
                writeln(count);
        }
}

import std.stdio;

void main() {

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

    int last, next, ans;
    foreach (i; 0 .. n)
        foreach (j; 0 .. 2*m) {
            readf(" %s ", &next);

            if (next && !(last && j & 1))
                ++ans;
            last = next;
        }

    writeln(ans);
}

import std.stdio;
int or(int a, int b)
{
	if (a==1 || b==1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int main()
{
	int a=0;
	int b=0;
	readf(" %d", &a);
	readf(" %d", &b);
	int count=0;
	int[] n = new int[2*b];
	int[] m = new int[b];
	for (int i=0; i<a; i++)
	{
		for (int j=0; j<2*b; j++)
		{
			readf(" %d", &n[j]);
		}
		for (int j=0; j<b; j++)
		{
			m[j]=or(n[2*j],n[2*j+1]);
		}
		for (int j=0; j<b; j++)
		{
			if (m[j]==1)
			{
				count=count+1;
			}
		}
	}
	writeln(count);
	return 0;
}


After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).

The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.

For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.

Note  The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.

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

immutable int MAX_L = 20;
immutable int    NA = -1;

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		auto a = new int [] [n];
		auto p = new int [n];
		foreach (i; 1..n)
		{
			readf (" %s", &p[i]);
			p[i]--;
			a[p[i]] ~= i;
		}

		auto s = new int [n];
		auto d = new int [MAX_L] [n];
		foreach (ref e; d)
		{
			e[] = NA;
		}

		void recur (int v)
		{
			s[v] = 1;
			foreach (u; a[v])
			{
				recur (u);
				s[v] += s[u];
				if (d[v][0] == NA || s[d[v][0]] < s[u])
				{
					d[v][0] = u;
				}
			}
		}

		recur (0);

		foreach (k; 1..MAX_L)
		{
			foreach (v; 0..n)
			{
				if (d[v][k - 1] != NA)
				{
					d[v][k] = d[d[v][k - 1]][k - 1];
				}
			}
		}

		foreach (r; 0..q)
		{
			int v;
			readf (" %s", &v);
			v--;
			int u = v;
			foreach_reverse (k; 0..MAX_L)
			{
				debug {writeln (u, " ", k);}
				if (d[u][k] != NA)
				{
					if (s[v] - s[d[u][k]] <= s[v] / 2)
					{
						u = d[u][k];
					}
				}
			}
			writeln (u + 1);
		}
	}
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. For each $$$i$$$ ($$$1 \le i \le n$$$) the following inequality is true: $$$-2 \le a_i \le 2$$$.You can remove any number (possibly $$$0$$$) of elements from the beginning of the array and any number (possibly $$$0$$$) of elements from the end of the array. You are allowed to delete the whole array.You need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is maximal. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output any of them. The product of elements of an empty array (array of length $$$0$$$) should be assumed to be $$$1$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Then the descriptions of the input test cases follow. The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) —the length of array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_i| \le 2$$$) — elements of array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output two non-negative numbers $$$x$$$ and $$$y$$$ ($$$0 \le x + y \le n$$$) — such that the product (multiplication) of the array numbers, after removing $$$x$$$ elements from the beginning and $$$y$$$ elements from the end, is maximal. If there is more than one way to get the maximal product, it is allowed to output any of them. Consider the product of numbers on empty array to be $$$1$$$.

NoteIn the first case, the maximal value of the product is $$$2$$$. Thus, we can either delete the first three elements (obtain array $$$[2]$$$), or the last two and one first element (also obtain array $$$[2]$$$), or the last two elements (obtain array $$$[1, 2]$$$). Thus, in the first case, the answers fit: "3 0", or "1 2", or "0 2".In the second case, the maximum value of the product is $$$1$$$. Then we can remove all elements from the array because the value of the product on the empty array will be $$$1$$$. So the answer is "3 0", but there are other possible answers.In the third case, we can remove the first two elements of the array. Then we get the array: $$$[-2, 2, -1]$$$. The product of the elements of the resulting array is $$$(-2) \cdot 2 \cdot (-1) = 4$$$. This value is the maximum possible value that can be obtained. Thus, for this case the answer is: "2 0".

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() {
    int N = read!int;
    auto A = readarray!int;

    int[] zs = [-1];
    foreach (i, a; A) {
        if (a == 0) zs ~= i;
    }
    zs ~= N;

    int max_nt = 0;
    int[] ans = [0, 0];
    for (int k = 0; k + 1 < zs.length; k++) {
        int l = zs[k], r = zs[k + 1];
        l++; // exclude leftmost zero
        int nm = 0;
        int nt = 0;
        for (int i = l; i < r; i++) {
            assert(A[i] != 0);
            if (A[i] < 0) nm++;
            if (abs(A[i]) == 2) nt++;
        }
        if (nm % 2 == 0) {
            if (max_nt < nt) {
                max_nt = nt;
                ans = [l, r];
            }
        } else {
            // remove left or right
            int lrt = 0, rrt = 0; // left removed t
            int li = -1, ri = -1;
            for (int i = l; i < r; i++) {
                if (abs(A[i]) == 2) lrt++;
                if (A[i] < 0) {
                    li = i + 1;
                    break;
                }
            }
            for (int i = r-1; i >= l; i--) {
                if (abs(A[i]) == 2) rrt++;
                if (A[i] < 0) {
                    ri = i;
                    break;
                }
            }
            if (lrt > rrt) {
                // remove right
                int tnt = nt - rrt;
                if (max_nt < tnt) {
                    max_nt = tnt;
                    ans = [l, ri];
                }
            } else {
                // remove left
                int tnt = nt - lrt;
                if (max_nt < tnt) {
                    max_nt = tnt;
                    ans = [li, r];
                }
            }
        }
    }
    auto removed = [ ans[0], N - ans[1] ];
    writefln("%(%s %)", removed);
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto res = [0, 0, 0]; // pow, lo, hi
		auto startVal = [0, 0];
		auto startPos = [0, int.max];
		int isNeg = 0;
		int val = 0;
		foreach (int pos, c; a)
		{
			if (c == 0)
			{
				startVal = [0, 0];
				startPos = [pos + 1, int.max];
				isNeg = 0;
				val = 0;
				continue;
			}
			if (c < 0)
			{
				isNeg ^= 1;
				c *= -1;
			}
			c -= 1;
			val += c;
			if (startPos[isNeg] == int.max)
			{
				startVal[isNeg] = val;
				startPos[isNeg] = pos + 1;
			}
			res = max (res,
			    [val - startVal[isNeg], startPos[isNeg], pos + 1]);
		}
		writeln (res[1], " ", n - res[2]);
	}
}


Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $$$p_i$$$ — the index of the router to which the $$$i$$$-th router was connected after being purchased ($$$p_i < i$$$).There are $$$n$$$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $$$n$$$-th router.

The first line contains integer number $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of the routers. The following line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is equal to index of the router to which the $$$i$$$-th was connected after purchase.

Print the path from the $$$1$$$-st to the $$$n$$$-th router. It starts with $$$1$$$ and ends with $$$n$$$. All the elements in the path should be distinct.

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

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

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

    int x = n;
    int[] ans = [x];
    do {
        ans ~= arr[x-2];
        x = arr[x-2];
    } while (x != 1);

    ans.reverse();

    ans.writefln!"%(%s %)";
}


The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer.This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.

The first input line contains two integers n and m (1 ≤ n ≤ 105; 1 ≤ m ≤ 106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 ≤ ti, Ti, xi, costi ≤ 106). The numbers in the lines are separated by single spaces.

Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.

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

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

    long ans = 0L;
    while (n--) {
        int t, T, x, cost;
        readf("%s %s %s %s", &t, &T, &x, &cost);
        readln;

        int capacity = T - t;

        if (m <= capacity) {
            ans += cost;
            continue;
        }

        if (capacity <= 0) {
            ans += cost + m.to!long * x;
            continue;
        }

        auto cur1 = (m + capacity - 1).to!long / capacity * cost;
        auto cur2 = cost + m.to!long * x;

        auto cur = min(cur1, cur2);

        debug { cur.writeln; }

        ans += cur;
    }

    ans.writeln;
}

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

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

    long ans = 0L;
    while (n--) {
        int t, T, x, cost;
        readf("%s %s %s %s", &t, &T, &x, &cost);
        readln;

        int capacity = T - t;

        if (m <= capacity) {
            ans += cost;
            continue;
        }

        if (capacity <= 0) {
            ans += cost + m.to!long * x;
            continue;
        }

        auto cur1 = (m + capacity - 1).to!long / capacity * cost;
        auto cur2 = m % capacity == 0 ? 10L ^^ 18 :
            m.to!long / capacity * cost + (capacity + m % capacity).to!long * x;
        auto cur3 = cost + m.to!long * x;

        auto cur = min(cur1, min(cur2, cur3));

        debug { cur.writeln; }

        ans += cur;
    }

    ans.writeln;
}

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

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

    long ans = 0L;
    while (n--) {
        int t, T, x, cost;
        readf("%s %s %s %s", &t, &T, &x, &cost);
        readln;

        int capacity = T - t;

        if (capacity >= m) {
            ans += cost;
            continue;
        }

        if (capacity <= 0) {
            ans += cost + m.to!long * x;
            continue;
        }

        auto cur1 = (m + capacity - 1).to!long / capacity * cost;
        auto cur2 = m % capacity == 0 ? 10 ^^ 9 :
            max(m.to!long / capacity, 1L) * cost + (capacity + m % capacity).to!long * x;
        auto cur3 = cost + m.to!long * x;

        auto cur = min(cur1, min(cur2, cur3));

        debug { cur.writeln; }

        ans += cur;
    }

    ans.writeln;
}

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

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

    auto ans = 0L;
    while (n--) {
        int t, T, x, cost;
        readf("%s %s %s %s", &t, &T, &x, &cost);
        readln;

        int capacity = T - t;

        if (capacity >= m) {
            ans += cost;
            continue;
        }

        if (capacity <= 0) {
            ans += cost + m.to!long * x;
            continue;
        }

        auto cur1 = (m + capacity - 1).to!long / capacity * cost;
        auto cur2 = m % capacity == 0 ? 10 ^^ 9 :
            m.to!long / capacity * cost + (capacity + m % capacity).to!long * x;
        auto cur3 = cost + m.to!long * x;

        auto cur = min(cur1, min(cur2, cur3));

        debug { cur.writeln; }

        ans += cur;
    }

    ans.writeln;
}

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

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

    auto ans = 0L;
    while (n--) {
        int t, T, x, cost;
        readf("%s %s %s %s", &t, &T, &x, &cost);
        readln;

        int capacity = T - t;

        if (capacity >= m) {
            ans += cost;
            continue;
        }

        if (capacity <= 0) {
            ans += cost + m.to!long * x;
            continue;
        }

        auto cur1 = (m + capacity - 1).to!long / capacity * cost;
        auto cur2 = m % capacity == 0 ? 10 ^^ 9 :
            max(m.to!long / capacity, 1) * cost + (capacity + m % capacity).to!long * x;
        auto cur3 = cost + m.to!long * x;

        auto cur = min(cur1, min(cur2, cur3));

        debug { cur.writeln; }

        ans += cur;
    }

    ans.writeln;
}

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

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

    auto ans = 0L;
    while (n--) {
        int t, T, x, cost;
        readf("%s %s %s %s", &t, &T, &x, &cost);
        readln;

        int capacity = T - t;

        if (capacity >= m) {
            ans += cost;
            continue;
        }

        if (capacity <= 0) {
            ans += cost + m.to!long * x;
            continue;
        }

        auto cur1 = (m + capacity - 1).to!long / capacity * cost;
        auto cur2 = m % capacity == 0 ? 10 ^^ 9 :
            m.to!long / capacity * cost + (capacity + m % capacity) * x;
        auto cur3 = cost + m.to!long * x;

        auto cur = min(cur1, min(cur2, cur3));

        debug { cur.writeln; }

        ans += cur;
    }

    ans.writeln;
}


There are $$$n + 1$$$ cities, numbered from $$$0$$$ to $$$n$$$. $$$n$$$ roads connect these cities, the $$$i$$$-th road connects cities $$$i - 1$$$ and $$$i$$$ ($$$i \in [1, n]$$$).Each road has a direction. The directions are given by a string of $$$n$$$ characters such that each character is either L or R. If the $$$i$$$-th character is L, it means that the $$$i$$$-th road initially goes from the city $$$i$$$ to the city $$$i - 1$$$; otherwise it goes from the city $$$i - 1$$$ to the city $$$i$$$.A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city $$$i$$$ to the city $$$i + 1$$$, it is possible to travel from $$$i$$$ to $$$i + 1$$$, but not from $$$i + 1$$$ to $$$i$$$. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $$$i$$$, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city $$$i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters, each character is either L or R. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$n + 1$$$ integers. The $$$i$$$-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the $$$i$$$-th city.

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()
{
    auto t = readln.chomp.to!int;

    while (t--) {
        auto n = readln.chomp.to!int;
        auto v = readln.chomp.array;

        void go(dchar[] v, int[dchar][] arr) {
            arr[0]['L'] = 0;
            arr[0]['R'] = 0;
            foreach (i, e; v.enumerate(1)) {
                auto calc = (dchar now, dchar other) =>
                    e == now ? 1 + arr[i-1][other] : 0;

                arr[i]['L'] = calc('L', 'R');
                arr[i]['R'] = calc('R', 'L');
            }
        }

        auto pref = new int[dchar][] (n+1);
        go(v, pref);

        auto suf = new int[dchar][] (n+1);
        go(v.retro().array, suf);
        suf.reverse();

        debug { pref.writeln; suf.writeln; }

        auto ans = (n+1).iota.map!(x => 1 + pref[x]['L'] + suf[x]['R']);

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

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int N; get(N);
        char[] ds; get(ds);
        auto ls = new int[][](N + 1, 2);
        auto rs = new int[][](N + 1, 2);
        foreach (i; 0..N) {
            if (ds[i] == 'L') ls[i+1][0] = ls[i][1] + 1;
            if (ds[i] == 'R') ls[i+1][1] = ls[i][0] + 1;
        }
        foreach_reverse (i; 0..N) {
            if (ds[i] == 'R') rs[i][0] = rs[i+1][1] + 1;
            if (ds[i] == 'L') rs[i][1] = rs[i+1][0] + 1;
        }
        writefln!"%(%d %)"(0.iota(N + 1).map!(i => ls[i][0] + rs[i][0] + 1));
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a == 'L'}).array;
		auto fwd = new int [] [] (2, n);

		auto go ()
		{
			auto res = new int [] [] (2, n + 1);
			foreach (i; 0..n)
			{
				foreach (d; 0..2)
				{
					if (d ^ s[i])
					{
						res[d][i + 1] = res[!d][i] + 1;
					}
				}
			}
			return res;
		}

		auto lo = go ();
		reverse (s);
		s[] ^= 1;
		auto hi = go ();
		foreach (ref line; hi)
		{
			reverse (line);
		}
		writefln !("%(%s %)")
		    (iota (n + 1).map !(i => lo[0][i] + hi[0][i] + 1));
	}
}