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

immutable int INF = 10 ^^ 8 * 3 + 1;

void main()
{
    readln;
    auto s = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    int ans = INF;
    foreach (i, fs, cst; lockstep(s, c)) {
        int getMin(int[] s, int[]c, bool delegate(int) valsFilter) {
            auto vals = zip(s,c).filter!(t => valsFilter(t[0])).map!(t => t[1]);
            return vals.empty() ? INF : vals.minElement;
        }
        auto prev = getMin(s[0..i], c[0..i], x => x < fs);
        auto nxt = getMin(s[i+1..$], c[i+1..$], x => x > fs);
        if (prev != INF && nxt != INF) ans = min(ans, cst + prev + nxt);
    }

    writeln(ans == INF ? -1 : ans);
}

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

immutable int INF = 10 ^^ 8 + 1;

void main()
{
    readln;
    auto s = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    int ans = INF + INF + INF;
    foreach (i, fs, cst; lockstep(s, c)) {
        int prev = INF;
        foreach (j; 0..i) {
            if (s[j] < fs) prev = min(prev, c[j]);
        }
        int nxt = INF;
        foreach (j; i+1..s.length) {
            if (fs < s[j]) nxt = min(nxt, c[j]);
        }
        if (prev != INF && nxt != INF) ans = min(ans, cst + prev + nxt);
    }

    writeln(ans == INF + INF + INF ? -1 : ans);
}

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

immutable int INF = 10 ^^ 8 * 3 + 1;

void main()
{
    readln;
    auto s = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    int ans = INF;
    foreach (i, fs, cst; lockstep(s, c)) {
        int getMin(int[] s, int[]c, bool delegate(int) valsFilter) {
            int ret = INF;
            foreach (_, fs, cst; lockstep(s,c)) {
                if (valsFilter(fs)) ret = min(cst, ret);
            }
            return ret;
        }
        auto prev = getMin(s[0..i], c[0..i], x => x < fs);
        auto nxt = getMin(s[i+1..$], c[i+1..$], x => x > fs);
        if (prev != INF && nxt != INF) ans = min(ans, cst + prev + nxt);
    }

    writeln(ans == INF ? -1 : ans);
}

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

  int n; rd(n);
  auto s=readln.split.to!(int[]);
  auto c=readln.split.to!(int[]);

  auto tmp=s.dup;
  sort(tmp);
  int[int] map;
  foreach(e; tmp){
    if((e in map)==null) map[e]=map.length.to!(int);
  }
  foreach(i; 0..n) s[i]=map[s[i]];

  auto best=new int[][](n+1, n+1);
  const int inf=1_000_000_000;
  foreach(i; 0..(n+1)) fill(best[i], inf);
  foreach(i; 0..n){
    chmin(best[i][s[i]], c[i]);
    for(int j=s[i]; j>0; j--) chmin(best[i][j-1], best[i][j]);
  }
  for(int i=n-1; i>0; i--){
    foreach(j; 0..n){
      chmin(best[i-1][j], best[i][j]);
    }
  }

  int mn=inf;
  foreach(i; 0..n)foreach(j; (i+1)..n)if(s[i]<s[j]){
    mn=min(mn, c[i]+c[j]+best[j+1][s[j]+1]);
  }

  if(mn==inf) writeln(-1);
  else writeln(mn);
}

void chmin(T)(ref T l, T r){if(l>r)l=r;}

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

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;
import std.bigint;
import core.checkedint;

void main()
{
	int n = readln.chomp.to!int;
	long[] s = readln.chomp.split.map!(to!long).array;
	int[] c = readln.chomp.split.map!(to!int).array;
	long[] sub = new long[](n);
	foreach (i; 0..n) {
		int v = int.max;
		foreach (j; i + 1 .. n) {
			if (s[i] >= s[j]) {
				continue;
			}
			v = min(v, c[j]);
		}
		sub[i] = v;
	}
	long ans = int.max;
	foreach (i; 0..n) {
		foreach (j; i + 1 .. n) {
			if (s[i] >= s[j]) {
				continue;
			}
			debug verbose(i, j, sub[j], c[i] + c[j] + sub[j]);
			ans = min(ans, c[i] + c[j] + sub[j]);
		}
	}
	if (ans >= int.max) {
		writeln = -1;
	} else {
		ans.writeln;
	}
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

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

immutable int INF = 10 ^^ 8 * 3 + 1;

void main()
{
    readln;
    auto s = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    int ans = INF;
    foreach (i, fs, cst; lockstep(s, c)) {
        int getMin(int[] s, int[]c, bool delegate(int) valsFilter) {
            auto vals = zip(s,c).filter!(t => valsFilter(t[0])).map!(t => t[1]);
            return vals.empty() ? INF : vals.front();
        }
        auto prev = getMin(s[0..i], c[0..i], x => x < fs);
        auto nxt = getMin(s[i+1..$], c[i+1..$], x => x > fs);
        if (prev != INF && nxt != INF) ans = min(ans, cst + prev + nxt);
    }

    writeln(ans == INF ? -1 : ans);
}

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

immutable int INF = 10 ^^ 8 * 3;

void main()
{
    readln;
    auto s = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    int ans = INF;
    foreach (i, fs, cst; lockstep(s, c)) {
        int getMin(int[] s, int[]c, bool delegate(int) valsFilter) {
            int ret = INF;
            foreach (_, fs, cst; lockstep(s,c)) {
                if (valsFilter(fs)) ret = min(cst, ret);
            }
            return ret;
        }
        auto prev = getMin(s[0..i], c[0..i], x => x < fs);
        auto nxt = getMin(s[i+1..$], c[i+1..$], x => x > fs);
        if (prev != INF && nxt != INF) ans = min(ans, cst + prev + nxt);
    }

    writeln(ans == INF ? -1 : ans);
}


import std;

int t,n;

int U(int cur) {
    return cur == 9 ? 0 : cur + 1;
}

int D(int cur) {
    return cur == 0 ? 9 : cur - 1;
}

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d", &n);
        getchar();
        auto fin = readln.split.to!(int[]);
        foreach (w; 0 .. n) {
            auto l = readln.split.to!(string[]);
            foreach (com; l[1].array.reverse)
                if (com == 'U')
                    fin[w] = D(fin[w]);
                else
                    fin[w] = U(fin[w]);
        }
        writefln("%(%s %)", fin);
    }

}

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 a = readln.splitter.map !(to !(int)).array;
		foreach (i; 0..n)
		{
			auto temp = readln.split;
			foreach (ref c; temp[1])
			{
				a[i] = (a[i] + ((c == 'U') ? 9 : 1)) % 10;
			}
		}
		writefln !("%(%s %)") (a);
	}
}


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

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

void main()
{
  int x, d; readV(x, d);

  auto e = 1L;
  long[] a;
  while (x > 0) {
    auto i = (x+1).bsr;
    foreach (j; 0..i) a ~= e;
    e += d;
    x -= (1<<i)-1;
  }

  writeln(a.length);
  foreach (i, ai; a) {
    write(ai);
    if (i < a.length-1) write(" ");
  }
  writeln;
}

pragma(inline) {
  pure bool bitTest(T)(T n, size_t i) { return (n & (T(1) << i)) != 0; }
  pure T bitSet(T)(T n, size_t i) { return n | (T(1) << i); }
  pure T bitReset(T)(T n, size_t i) { return n & ~(T(1) << i); }
  pure T bitComp(T)(T n, size_t i) { return n ^ (T(1) << i); }

  pure T bitSet(T)(T n, size_t s, size_t e) { return n | ((T(1) << e) - 1) & ~((T(1) << s) - 1); }
  pure T bitReset(T)(T n, size_t s, size_t e) { return n & (~((T(1) << e) - 1) | ((T(1) << s) - 1)); }
  pure T bitComp(T)(T n, size_t s, size_t e) { return n ^ ((T(1) << e) - 1) & ~((T(1) << s) - 1); }

  import core.bitop;
  pure int bsf(T)(T n) { return core.bitop.bsf(ulong(n)); }
  pure int bsr(T)(T n) { return core.bitop.bsr(ulong(n)); }
  pure int popcnt(T)(T n) { return core.bitop.popcnt(ulong(n)); }
}

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 X = readLong();
      const D = readLong();

      int[] es;
      for (long x = X; x > 0; ) {
        // 2^e - 1 <= x
        const e = bsr(x + 1);
        es ~= e;
        x -= ((1L << e) - 1);
      }
      debug {
        writeln("es = ", es);
      }

      long[] ans;
      long val = 1;
      foreach (e; es) {
        ans ~= repeat(val, e).array;
        val += D;
      }
      writeln(ans.length);
      foreach (i, a; ans) {
        if (i > 0) write(" ");
        write(a);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

    long B = 10L^^10;

    long x, d;
    sc.read(x, d);
    long U = 1;
    long[] res;
    foreach_reverse (ph; 1..40) {
        long y = (1L << ph) - 1;
        long z = x / y; x %= y;
        foreach (_; 0..z) {
            U += B;
            foreach (i; 0..ph) {
                res ~= U;
            }
        }
    }
    writeln(res.length);
    writeln(res.map!(to!string).join(" "));
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

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

// module dkh.foundation;

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

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

// import dkh.container.stackpayload;

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

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

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

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

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

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

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

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

    long B = 10L^^10;

    long x, d;
    sc.read(x, d);
    long U = 1;
    long[] res;
    foreach_reverse (ph; 1..40) {
        long y = (1L << ph) - 1;
        long z = x / y; x %= y;
        foreach (_; 0..z) {
            U += B;
            foreach (i; 0..ph) {
                res ~= U;
            }
        }
    }
    writeln(res.map!(to!string).join(" "));
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

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

// module dkh.foundation;

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

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

// import dkh.container.stackpayload;

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

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

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

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

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

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

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

void main()
{
  int x, d; readV(x, d);

  auto e = 1;
  long[] a;
  while (x > 0) {
    auto i = (x+1).bsr;
    foreach (j; 0..i) a ~= e;
    e += d;
    x -= (1<<i)-1;
  }

  writeln(a.length);
  foreach (i, ai; a) {
    write(ai);
    if (i < a.length-1) write(" ");
  }
  writeln;
}

pragma(inline) {
  pure bool bitTest(T)(T n, size_t i) { return (n & (T(1) << i)) != 0; }
  pure T bitSet(T)(T n, size_t i) { return n | (T(1) << i); }
  pure T bitReset(T)(T n, size_t i) { return n & ~(T(1) << i); }
  pure T bitComp(T)(T n, size_t i) { return n ^ (T(1) << i); }

  pure T bitSet(T)(T n, size_t s, size_t e) { return n | ((T(1) << e) - 1) & ~((T(1) << s) - 1); }
  pure T bitReset(T)(T n, size_t s, size_t e) { return n & (~((T(1) << e) - 1) | ((T(1) << s) - 1)); }
  pure T bitComp(T)(T n, size_t s, size_t e) { return n ^ ((T(1) << e) - 1) & ~((T(1) << s) - 1); }

  import core.bitop;
  pure int bsf(T)(T n) { return core.bitop.bsf(ulong(n)); }
  pure int bsr(T)(T n) { return core.bitop.bsr(ulong(n)); }
  pure int popcnt(T)(T n) { return core.bitop.popcnt(ulong(n)); }
}

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

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

void main()
{
  int x, d; readV(x, d);

  auto e = 1;
  long[] a;
  while (x > 0) {
    auto i = (x+1).bsr;
    foreach (j; 0..i) a ~= e;
    e += d;
    x -= (1<<i)-1;
  }

  foreach (i, ai; a) {
    write(ai);
    if (i < a.length-1) write(" ");
  }
  writeln;
}

pragma(inline) {
  pure bool bitTest(T)(T n, size_t i) { return (n & (T(1) << i)) != 0; }
  pure T bitSet(T)(T n, size_t i) { return n | (T(1) << i); }
  pure T bitReset(T)(T n, size_t i) { return n & ~(T(1) << i); }
  pure T bitComp(T)(T n, size_t i) { return n ^ (T(1) << i); }

  pure T bitSet(T)(T n, size_t s, size_t e) { return n | ((T(1) << e) - 1) & ~((T(1) << s) - 1); }
  pure T bitReset(T)(T n, size_t s, size_t e) { return n & (~((T(1) << e) - 1) | ((T(1) << s) - 1)); }
  pure T bitComp(T)(T n, size_t s, size_t e) { return n ^ ((T(1) << e) - 1) & ~((T(1) << s) - 1); }

  import core.bitop;
  pure int bsf(T)(T n) { return core.bitop.bsf(ulong(n)); }
  pure int bsr(T)(T n) { return core.bitop.bsr(ulong(n)); }
  pure int popcnt(T)(T n) { return core.bitop.popcnt(ulong(n)); }
}

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 X = readLong();
      const D = readLong();

      int[] es;
      for (long x = X; x > 0; ) {
        // 2^e - 1 <= x
        const e = bsr(x + 1);
        es ~= e;
        x -= ((1L << e) - 1);
      }
      debug {
        writeln("es = ", es);
      }

      long[] ans;
      long val;
      foreach (e; es) {
        ans ~= repeat(val, e).array;
        val += D;
      }
      writeln(ans.length);
      foreach (i, a; ans) {
        if (i > 0) write(" ");
        write(a);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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 X = readLong();
      const D = readLong();

      int[] es;
      for (long x = X; x > 0; ) {
        // 2^e - 1 <= x
        const e = bsr(x + 1);
        es ~= e;
        x -= ((1L << e) - 1);
      }
      debug {
        writeln("es = ", es);
      }

      long[] ans;
      long val;
      foreach (e; es) {
        ans ~= repeat(val, e).array;
        val += D;
      }
      writeln(ans.length);
      foreach (i, a; ans) {
        if (i > 0) write(" ");
        write(a);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


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

auto cnt = new int[](26);

void solve() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto S = readln.chomp;

    int ans = 0;

    foreach (i; 0..K/2+K%2) {
        cnt[] = 0;
        if (K % 2 && i == K / 2) {
            foreach (j; 0..N/K) {
                int a = j * K + i;
                cnt[S[a]-'a'] += 1;
                ans += 1;
            }
        } else {
            foreach (j; 0..N/K) {
                int a = j * K + i;
                int b = (j + 1) * K - i - 1;
                cnt[S[a]-'a'] += 1;
                cnt[S[b]-'a'] += 1;
                ans += 2;
            }
        }
        ans -= cnt.reduce!max;
    }

    ans.writeln;
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        solve();
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int len =  n / k;
		int l, r = k-1;
		while (l <= r)
		{
			auto cnt = new int[](26);
			foreach (i; 0..len)
			{
				auto c1 = s[i*k+l] - 'a';
				auto c2 = s[i*k+r] - 'a';
				++cnt[c1];
				++cnt[c2];
			}
			int x;
			foreach (i; 0..26)
			{
				x.chmax(cnt[i]);
			}
			if (l == r)
				ans[ti] += len - x / 2;
			else
				ans[ti] += len * 2 - x;
			debug writeln("ans:", ans[ti]);
			++l;
			--r;
		}
	}

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


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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto s = RD!string;
	int[] ans1, ans2;
	int l, r = cast(int)s.length-1;
	foreach (i; 0..s.length)
	{
		if (s[i] == '(') break;
		++l;
	}
	foreach_reverse (i; 0..s.length)
	{
		if (s[i] == ')') break;
		--r;
	}
	while (l < r)
	{
		ans1 ~= l+1;
		ans2 ~= r+1;
		++l; --r;
		foreach (i; l..s.length)
		{
			if (s[i] == '(') break;
			++l;
		}
		foreach_reverse (i; 0..r+1)
		{
			if (s[i] == ')') break;
			--r;
		}
	}
	ans2.sort();

	if (ans1.empty && ans2.empty)
	{
		writeln(0);
	}
	else
	{
		writeln(1);
		writeln(ans1.length + ans2.length);
		(ans1~ans2).map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

void main() {
  auto s = readln.stripRight;
  const l = s.length.to!int;
  auto b = new bool[l];
  int[][] ans;
  while (true) {
    int i = 0, j = l - 1;
    int[] u, v;
    while (true) {
      while (i < l && (b[i] || s[i] != '(')) ++i;
      while (j >= 0 && (b[j] || s[j] != ')')) --j;
      if (i > j) break;
      u ~= i + 1;
      v ~= j + 1;
      b[i] = b[j] = true;
    }
    reverse (v);
    u ~= v;
    if (u.empty) break;
    ans ~= u;
  }
  writeln (ans.length);
  foreach (p; ans) {
    writeln (p.length);
    writefln ("%(%s %)", p);
  }

}

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 S = readToken();
      const L = cast(int)(S.length);

      auto sums = new int[][](2, L + 1);
      foreach (i; 0 .. L) {
        sums[0][i + 1] = sums[0][i] + ((S[i] == '(') ? 1 : 0);
        sums[1][i + 1] = sums[1][i] + ((S[i] == ')') ? 1 : 0);
      }
      int mn = L + 1;
      int km = -1;
      foreach (k; 0 .. L + 1) {
        if (sums[0][k] == sums[1][L] - sums[1][k]) {
          if (chmin(mn, sums[0][k])) {
            km = k;
          }
        }
      }
      assert(km != -1);
      if (mn == 0) {
        writeln(0);
      } else {
        int[] ans;
        foreach (i; 0 .. km) if (S[i] == '(') ans ~= i;
        foreach (i; km .. L) if (S[i] == ')') ans ~= i;
        writeln(1);
        writeln(ans.length);
        foreach (index, i; ans) {
          if (index > 0) write(" ");
          write(i + 1);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int i = 0;
		int j = s.length.to !(int) - 1;
		int [] ans;
		while (true)
		{
			while (i < j && s[i] != '(')
			{
				i += 1;
			}
			while (i < j && s[j] != ')')
			{
				j -= 1;
			}
			if (i >= j)
			{
				break;
			}
			ans ~= i;
			ans ~= j;
			i += 1;
			j -= 1;
		}
		ans[] += 1;
		sort (ans);
		writefln !("%d") (ans.length > 0);
		if (!ans.empty)
		{
			writeln (ans.length);
			writefln !("%(%s %)") (ans);
		}
	}
}


//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s==t)
        puts("0");
    else if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=i+1;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j+1;
            }
        }
        writeln(r.length);
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
        writeln;
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s==t)
        puts("0");
    else if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=i+1;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j+1;
            }
        }
        writeln(r.length);
        writefln!"%(%d %)"(r);
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip.dup;
		auto t = readln.strip;
		int [] ans;
		foreach (i; 0..n)
		{
			foreach (j; i..n)
			{
				if (s[j] == t[i])
				{
					foreach_reverse (p; i..j)
					{
						ans ~= p + 1;
						swap (s[p], s[p + 1]);
					}
					break;
				}
			}
		}
		if (s != t)
		{
			writeln (-1);
			continue;
		}
		writeln (ans.length);
		writefln ("%(%s %)", ans);
	}
}

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

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

    auto s = readln.chomp.to!(dchar[]).array;
    auto t = readln.chomp;

    int[] ans;
    foreach (int i, e; t) {
        debug { writeln(i, ' ', e); }

        if (!s.drop(i).canFind(e)) {
            writeln(-1);
            return;
        }

        int p = n - cast(int) s.drop(i).find(e).length - 1;

        debug { writeln(s.drop(i), ' ', s.drop(i).find(e), ' ', s.drop(i).find(e).array.length); p.writeln; }

        while (i <= p) {
            swap(s[p], s[p+1]);
            ans ~= p;
            --p;
        }
    }

    ans.length.writeln;
    ans.map!(x => x+1).writefln!("%(%s %)");
}

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

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

    auto s = readln.chomp.to!(dchar[]).array;
    auto t = readln.chomp;

    int[] ans;
    foreach (int i, e; t) {
        debug { writeln(i, ' ', e); }

        if (!s.drop(i).canFind(e)) {
            writeln(-1);
            return;
        }

        int p = n - cast(int) s.drop(i).find(e).length - 1;

        debug { writeln(s.drop(i), ' ', s.drop(i).find(e), ' ', s.drop(i).find(e).array.length); p.writeln; }

        while (i <= p) {
            swap(s[p], s[p+1]);
            ans ~= p;
            --p;
        }
    }

    ans.map!(x => x+1).writefln!("%(%s %)");
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=0;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j;
            }
        }
        writeln(r.length);
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=0;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j;
            }
        }
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
        writeln;
        debug writeln(s," ",t);
    }
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int[] r;
    int n=readln.chomp.to!int;
    char[] s=readln.strip.to!(char[]),
           t=readln.strip.to!(char[]);
    if(s.dup.array.sort!=t.dup.array.sort)
        puts("-1");
    else{
        foreach(i;0..n){
            if(s[i]==t[i]) continue;
            int j=0;
            while(j<n && s[j]!=t[i])
                j++;
            while(j>i){
                s.swapAt(j,j-1);
                j--;
                r~=j+1;
            }
        }
        writeln(r.length);
        write(r[0]);
        foreach(i;1..r.length)
            write(" ",r[i]);
    }
}


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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    readf("%d\n", &n);
    foreach (i; 0..n) {
        auto s = chomp(readln());
        if (s.length < 5) {
            writeln("OMG>.< I don't know!");
        } else {
            bool is_freda = s[$-5..$] == "lala.";
            bool is_rainbow = s[0..5] == "miao.";
            if (is_freda && !is_rainbow) {
                writeln("Freda's");
            } else if (!is_freda && is_rainbow) {
                writeln("Rainbow's");
            } else {
                writeln("OMG>.< I don't know!");
            }
        }
    }
}

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

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

    int n;
    readf(" %s\n", &n);
    string str;
    foreach ( i ; 0 .. n ) {
        readf("%s\n", &str);
        bool f = (str.length >= 5 && str[$ - 5 .. $] == "lala.");
        bool r = (str.length >= 5 && str[0 .. 5] == "miao.");
        if (f && (f ^ r)) writeln("Freda's");
        else if (r && (f ^ r)) writeln("Rainbow's");
        else writeln("OMG>.< I don't know!");
    }

    return 0;
}

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

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

    int n;
    readf(" %s\n", &n);
    string str;
    foreach ( i ; 0 .. n ) {
        readf(" %s\n", &str);
        bool f = (str.length >= 5 && str[$ - 5 .. $] == "lala.");
        bool r = (str.length >= 5 && str[0 .. 5] == "miao.");
        if (f && (f ^ r)) writeln("Freda's");
        else if (r && (f ^ r)) writeln("Rainbow's");
        else writeln("OMG>.< I don't know!");
    }

    return 0;
}

import std.stdio;
import std.array;
import std.string;

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    readf("%d ", &n);
    foreach (i; 0..n) {
        auto s = chomp(readln());
        if (s.length < 5) {
            writeln("OMG>.< I don't know!");
        } else {
            bool is_freda = s[$-5..$] == "lala.";
            bool is_rainbow = s[0..5] == "miao.";
            if (is_freda && !is_rainbow) {
                writeln("Freda's");
            } else if (!is_freda && is_rainbow) {
                writeln("Rainbow's");
            } else {
                writeln("OMG>.< I don't know!");
            }
        }
    }
}

import std.stdio;
import std.array;
import std.string;

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    readf("%d ", &n);
    foreach (i; 0..n) {
        auto s = strip(readln());
        if (s.length < 5) {
            writeln("OMG>.< I don't know!");
        } else {
            bool is_freda = s[$-5..$] == "lala.";
            bool is_rainbow = s[0..5] == "miao.";
            if (is_freda && !is_rainbow) {
                writeln("Freda's");
            } else if (!is_freda && is_rainbow) {
                writeln("Rainbow's");
            } else {
                writeln("OMG>.< I don't know!");
            }
        }
    }
}


import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.numeric;
import std.range;
import std.stdio;
import std.typecons;

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

int [MAX_N] t;

int get (int i)
{
	return t[i + MED_N];
}

int get (int l, int r)
{
	int res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res += t[l];
			l++;
		}
		if (!(r & 1))
		{
			res += t[r];
			r--;
		}
	}
	return res;
}

void put (int i, int v)
{
	for (i += MED_N; i > 0; i >>= 1)
	{
		t[i] += v;
	}
}

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		t[] = 0;
		foreach (i; 0..n)
		{
			put (i, 1);
		}
		int turn = 0;
		int lo = 0;
		int hi = n - 1;
		foreach (j; 0..q)
		{
			int qtype;
			readf (" %s", &qtype);
			if (qtype == 1)
			{
				int p;
				readf (" %s", &p);
				if (turn)
				{
					p = hi - lo + 1 - p;
				}
				int side = (p + p <= hi - lo + 1);
				if (side)
				{
					int c = lo + p;
					foreach (i; 0..p)
					{
						int v =
						    get (c - i - 1);
						put (c - i - 1, -v);
						put (c + i, +v);
					}
					lo = c;
				}
				else
				{
					p = hi - lo + 1 - p;
					int c = hi - p;
					foreach (i; 0..p)
					{
						int v =
						    get (c + i + 1);
						put (c + i + 1, -v);
						put (c - i, +v);
					}
					hi = c;
				}
				if (!side ^ turn)
				{
					turn ^= 1;
				}
			}
			else if (qtype == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				if (!turn)
				{
					x = lo + x;
					y = lo + y - 1;
				}
				else
				{
					swap (x, y);
					x = hi - x + 1;
					y = hi - y;
				}
				writeln (get (x, y));
			}
			else
			{
				enforce (false);
			}
		}
	}
}

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

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

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

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

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

void bitAdd(long[] bit, int pos, long val) {
	for (int x = pos; x < bit.length; x |= x + 1) bit[x] += val;
}
long bitSum(long[] bit, int pos) {
	long ret;
	for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) ret += bit[x];
	return ret;
}

int N, Q;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		Q = readInt;

		long[] a = new long[N];
		a[] = 1;
		long[] bit = new long[N];
		foreach (x; 0 .. N) {
			bit.bitAdd(x, +1);
		}
		bool rev = false;
		int head = 0, tail = N;

		void foldL(int p) {
debug{
writeln("  L ",p);
}
			foreach (x; head .. head + p) {
				const y = (head + p) + (head + p - 1) - x;
				a[y] += a[x];
				bit.bitAdd(y, a[x]);
			}
			head += p;
		}
		void foldR(int p) {
debug{
writeln("  R ",p);
}
			foreach (x; tail - p .. tail) {
				const y = (tail - p) + (tail - p - 1) - x;
				a[y] += a[x];
				bit.bitAdd(y, a[x]);
			}
			tail -= p;
		}

		foreach (q; 0 .. Q) {
debug{
writeln(a[head..tail]," ",rev);
}
			switch (readInt) {
				case 1: {
					const p = readInt;
					const pp = (tail - head) - p;
					if (rev) {
						if (p <= pp) {
							foldR(p);
						} else {
							foldL(pp);
							rev = !rev;
						}
					} else {
						if (p <= pp) {
							foldL(p);
						} else {
							foldR(pp);
							rev = !rev;
						}
					}
				} break;
				case 2: {
					const l = readInt;
					const r = readInt;
					long res;
					if (rev) {
						res = bit.bitSum(tail - l) - bit.bitSum(tail - r);
					} else {
						res = bit.bitSum(head + r) - bit.bitSum(head + l);
					}
					writeln(res);
				} break;
				default: assert(false);
			}
		}
	}
	} catch (EOFException) {}
}

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.numeric;
import std.range;
import std.stdio;
import std.typecons;

immutable int MED_N = 1 << 17;
immutable int MAX_N = MED_N << 1;

int [MAX_N] t;

int get (int i)
{
	return t[i + MED_N];
}

int get (int l, int r)
{
	int res = 0;
	for (l += MED_N, r += MED_N; l <= r; l >>= 1, r >>= 1)
	{
		if (l & 1)
		{
			res += t[l];
			l++;
		}
		if (!(r & 1))
		{
			res += t[r];
			r--;
		}
	}
	return res;
}

void put (int i, int v)
{
	for (i += MED_N; i > 0; i >>= 1)
	{
		t[i] += v;
	}
}

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		t[] = 0;
		foreach (i; 0..n)
		{
			put (i, 1);
		}
		int lo = 0;
		int hi = n - 1;
		foreach (j; 0..q)
		{
			int qtype;
			readf (" %s", &qtype);
			if (qtype == 1)
			{
				int p;
				readf (" %s", &p);
				int side = (p + p <= hi - lo + 1);
				if (side)
				{
					int c = lo + p;
					foreach (i; 0..p)
					{
						int v =
						    get (c - i - 1);
						put (c - i - 1, -v);
						put (c + i, +v);
					}
					lo = c;
				}
				else
				{
					p = hi - lo + 1 - p;
					int c = hi - p;
					foreach (i; 0..p)
					{
						int v =
						    get (c + i + 1);
						put (c + i + 1, -v);
						put (c - i, +v);
					}
					hi = c;
				}
			}
			else if (qtype == 2)
			{
				int x, y;
				readf (" %s %s", &x, &y);
				writeln (get (lo + x, lo + y - 1));
			}
			else
			{
				enforce (false);
			}
		}
	}
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, q;
		readf !(" %s %s") (n, q);
		readln;
		auto s = readln.strip.map !(q{a == '1'}).array;
		auto f = readln.strip.map !(q{a == '1'}).array;
		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [q];
		foreach (ref c; a)
		{
			readf !(" %s %s") (c.lo, c.hi);
			c.lo -= 1;
		}
		readln;

		auto half = 1 << bsr (n * 2 - 1);
		half = max (half, 2);
		auto limit = half << 1;
		debug {writeln (half, " ", limit);}
		auto t = new int [limit];
		auto u = new int [limit];
		auto z = new int [limit];
		u[] = -1;

		void relax (int pos)
		{
			if (u[pos] != -1)
			{
				debug {writeln ("relax ", pos);}
				t[pos] = u[pos] * z[pos];
				if (pos < half)
				{
					u[pos * 2 + 0] = u[pos];
					u[pos * 2 + 1] = u[pos];
				}
				u[pos] = -1;
			}
		}

		void recalc (int pos)
		{
			if (pos < half)
			{
				relax (pos * 2 + 0);
				relax (pos * 2 + 1);
				t[pos] = t[pos * 2 + 0] + t[pos * 2 + 1];
			}
		}

		foreach (i; 0..n)
		{
			t[i + half] = f[i];
			z[i + half] = 1;
		}
		foreach_reverse (i; 1..half)
		{
			recalc (i);
			z[i] = z[i * 2 + 0] + z[i * 2 + 1];
		}

		int calc (int pos, int tlo, int thi, int slo, int shi)
		{
			if (shi <= tlo || thi <= slo)
			{
				return 0;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				return t[pos];
			}
			int tme = (tlo + thi) >> 1;
			auto res = calc (pos * 2 + 0, tlo, tme, slo, shi) +
			    calc (pos * 2 + 1, tme, thi, slo, shi);
			recalc (pos);
			return res;
		}

		void mark (int pos, int tlo, int thi, int slo, int shi, int v)
		{
			if (shi <= tlo || thi <= slo)
			{
				return;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				u[pos] = v;
				relax (pos);
				recalc (pos);
				return;
			}
			int tme = (tlo + thi) >> 1;
			mark (pos * 2 + 0, tlo, tme, slo, shi, v);
			mark (pos * 2 + 1, tme, thi, slo, shi, v);
			recalc (pos);
		}

		debug {writefln !("%(%3s%)") (z);}
		bool ok = true;
		foreach_reverse (ref c; a)
		{
			auto d = calc (1, 0, half, c.lo, c.hi);
			debug {writeln (c.lo, " ", c.hi, " ", d);}
			debug {writeln ("after calc:");}
			debug {writefln !("%(%3s%)") (t);}
			debug {writefln !("%(%3s%)") (u);}
			int v = -1;
			if (d * 2 < c.hi - c.lo)
			{
				v = 0;
			}
			else if (d * 2 > c.hi - c.lo)
			{
				v = 1;
			}
			else
			{
				ok = false;
				break;
			}
			mark (1, 0, half, c.lo, c.hi, v);
			debug {writeln ("after mark:");}
			debug {writefln !("%(%3s%)") (t);}
			debug {writefln !("%(%3s%)") (u);}
		}

		foreach (i; 1..half + n)
		{
			relax (i);
		}
		debug {writefln !("%(%3s%)") (t);}
		debug {writefln !("%(%3s%)") (u);}
		debug {writefln !("%(%d%)") (s);}
		debug {writefln !("%(%d%)") (t[half..half + n]);}
		ok &= equal (s, t[half..half + n]);
		writeln (ok ? "YES" : "NO");
	}
}

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

class LazyPropagationSegmentTree(T = int, D = int, D init = D.init) {
  immutable size_t n;
  immutable int h;
  T[] t;
  D[] d;

  abstract void calc (size_t p, int k);
  abstract void apply (size_t p, D value, int k);

  final void build (size_t l, size_t r) {
    int k = 2;
    for (l += n, r += n - 1; l > 1; k <<= 1) {
      l >>= 1;
      r >>= 1;
      foreach_reverse (i; l .. r + 1) {
        calc (i, k);
      }
    }
  }

  final void push (size_t l, size_t r) {
    int s = h, k = 1 << (h-1);
    for (l += n, r += n - 1; s > 0; --s, k >>= 1) {
      foreach (i; l >> s .. (r >> s) + 1) {
        immutable delta = d[i];
        if (delta != init) {
          apply (i << 1, delta, k);
          apply ((i << 1) | 1, delta, k);
          d[i] = init;
        }
      }
    }
  }

  this (const T[] a) {
    n = a.length;
    h = bsr (n);
    t = uninitializedArray!(T[])(n);
    t ~= a;
    d = uninitializedArray!(D[])(n);
    d[] = init;
    build (0, n);
  }
}

class AssignSumLazyPropagationSegmentTree (T = int) : LazyPropagationSegmentTree!(T, T, T.min) {
  override void calc (size_t p, int k) {
    if (d[p] == T.min) t[p] = t[p<<1] + t[(p << 1) | 1];
    else t[p] = d[p] * k;
  }

  override void apply (size_t p, T value, int k) {
    t[p] = value * k;
    if (p < n) d[p] = value;
  }

  final void assign (size_t l, size_t r, T value) {
    debug stderr.writefln ("assign (l:%d, r:%d, value:%d)", l, r, value);
    push (l, l + 1);
    push (r - 1, r);
    immutable l0 = l, r0 = r;
    int k = 1;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1, k <<= 1) {
      if (l & 1) {
        apply (l++, value, k);
      }
      if (r & 1) {
        apply (--r, value, k);
      }
    }
    build (l0, l0 + 1);
    build (r0 - 1, r0);
  }

  final T sum (size_t l, size_t r) {
    push (l, l + 1);
    push (r - 1, r);
    T res;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res += t[l++];
      }
      if (r & 1) {
        res += t[--r];
      }
    }
    return res;
  }
  this (T[] a) {
    super (a);
  }
}

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

alias Q = Tuple!(int, int);

void main() {
  auto r = new InputReader ();
  const nt = r.next!uint();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint();
    const nq = r.next!uint();
    r.seekByte(48);
    int[] a, b;
    foreach (i; 0 .. n) {
      const c = r.nextByte!false();
      a ~= c.to!int - 48;
    }
    r.seekByte(48);
    foreach (i; 0 .. n) {
      const c = r.nextByte!false();
      b ~= c.to!int - 48;
    }
    debug stderr.writeln(a);
    debug stderr.writeln(b);
    auto st = new AssignSumLazyPropagationSegmentTree!int(b);
    Q[] q;
    foreach (i; 0 .. nq) {
      const u = r.next!int - 1;
      const v = r.next!int;
      q ~= Q(u, v);
    }
    bool res = true;
    foreach_reverse (k, const w; q) {
      const l = w[1] - w[0];
      const h = (l - 1) / 2;
      int t = st.sum(w[0], w[1]);
      debug stderr.writefln("l = %d, r = %d, sum = %d, h = %d, l = %d", w[0], w[1], t, h, l);
      if (t <= h) {
        st.assign(w[0], w[1], 0);
      } else if (t + h >= l) {
        st.assign(w[0], w[1], 1);
      } else {
        debug stderr.writefln("FAILED: l = %d, r = %d", w[0], w[1]);
        res = false;
        break;
      }
    }
    if (res) {
      foreach (i; 0 .. n) {
        if (st.sum(i, i + 1) != a[i]) {
          res = false;
          break;
        }
      }
    }
    if (res) write("YES\n"); else write("NO\n");
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, q;
		readf !(" %s %s") (n, q);
		readln;
		auto s = readln.strip.map !(q{a == '1'}).array;
		auto f = readln.strip.map !(q{a == '1'}).array;
		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [q];
		foreach (ref c; a)
		{
			readf !(" %s %s") (c.lo, c.hi);
			c.lo -= 1;
		}
		readln;

		auto half = 1 << bsr (n * 2 - 1);
		auto limit = half << 1;
		auto t = new int [limit];
		auto u = new int [limit];
		auto z = new int [limit];
		u[] = -1;

		void relax (int pos)
		{
			if (u[pos] != -1)
			{
				t[pos] = u[pos] * z[pos];
				if (pos < half)
				{
					u[pos * 2 + 0] = u[pos];
					u[pos * 2 + 1] = u[pos];
				}
				u[pos] = -1;
			}
		}

		void recalc (int pos)
		{
			if (pos < half)
			{
				t[pos] = t[pos * 2 + 0] + t[pos * 2 + 1];
			}
		}

		foreach (i; 0..n)
		{
			t[i + half] = f[i];
			z[i + half] = 1;
		}
		foreach_reverse (i; 1..half)
		{
			recalc (i);
			z[i] = z[i * 2 + 0] + z[i * 2 + 1];
		}

		int calc (int pos, int tlo, int thi, int slo, int shi)
		{
			if (shi <= tlo || thi <= slo)
			{
				return 0;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				return t[pos];
			}
			int tme = (tlo + thi) >> 1;
			return calc (pos * 2 + 0, tlo, tme, slo, shi) +
			    calc (pos * 2 + 1, tme, thi, slo, shi);
		}

		void mark (int pos, int tlo, int thi, int slo, int shi, int v)
		{
			if (shi <= tlo || thi <= slo)
			{
				return;
			}
			relax (pos);
			if (slo <= tlo && thi <= shi)
			{
				u[pos] = v;
				relax (pos);
				recalc (pos);
				return;
			}
			int tme = (tlo + thi) >> 1;
			mark (pos * 2 + 0, tlo, tme, slo, shi, v);
			mark (pos * 2 + 1, tme, thi, slo, shi, v);
			recalc (pos);
		}

		debug {writefln !("%(%3s%)") (z);}
		bool ok = true;
		foreach_reverse (ref c; a)
		{
			auto d = calc (1, 0, half, c.lo, c.hi);
			debug {writeln (c.lo, " ", c.hi, " ", d);}
			int v = -1;
			if (d * 2 < c.hi - c.lo)
			{
				v = 0;
			}
			else if (d * 2 > c.hi - c.lo)
			{
				v = 1;
			}
			else
			{
				ok = false;
				break;
			}
			mark (1, 0, half, c.lo, c.hi, v);
			debug {writefln !("%(%3s%)") (t);}
			debug {writefln !("%(%3s%)") (u);}
		}

		foreach (i; 1..half + n)
		{
			relax (i);
		}
		debug {writefln !("%(%3s%)") (t);}
		debug {writefln !("%(%3s%)") (u);}
		debug {writefln !("%(%d%)") (s);}
		debug {writefln !("%(%d%)") (t[half..half + n]);}
		ok &= equal (s, t[half..half + n]);
		writeln (ok ? "YES" : "NO");
	}
}


import std.stdio;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

T sign(T)(T x)
{
    return x < 0 ? -1 : 1;
}

int main(string[] args)
{
    long x1 = read!long;
    long y1 = read!long;
    long x2 = read!long;
    long y2 = read!long;
    long n = read!long;

    long ans = 0;
    foreach (i; 0..n)
    {
        long a = read!long;
        long b = read!long;
        long c = read!long;

        if (sign(a * x1 + b * y1 + c) *
            sign(a * x2 + b * y2 + c) < 0)
        {
            ans++;
        }
    }

    writeln(ans);

    return 0;
}

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

void main ()
{
	long x1, y1;
	while (readf (" %s %s", &x1, &y1) > 0)
	{
		long x2, y2;
		readf (" %s %s", &x2, &y2);
		int n;
		readf (" %s", &n);
		int res = 0;
		foreach (i; 0..n)
		{
			long a, b, c;
			readf (" %s %s %s", &a, &b, &c);
			long d1 = a * x1 + b * y1 + c;
			long d2 = a * x2 + b * y2 + c;
			if ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0))
			{
				res++;
			}
		}
		writeln (res);
	}
}

import std.stdio;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

T sign(T)(T x)
{
    return -x;
}

int main(string[] args)
{
    int x1 = read!int;
    int y1 = read!int;
    int x2 = read!int;
    int y2 = read!int;
    int n = read!int;

    int ans = 0;
    foreach (i; 0..n)
    {
        int a = read!int;
        int b = read!int;
        int c = read!int;

        if (sign(a * x1 + b * y1 + c) *
            sign(a * x2 + b * y2 + c) < 0)
        {
            ans++;
        }
    }

    writeln(ans);

    return 0;
}

import std.stdio;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

T sign(T)(T x)
{
    return -x;
}

int main(string[] args)
{
    long x1 = read!long;
    long y1 = read!long;
    long x2 = read!long;
    long y2 = read!long;
    long n = read!long;

    long ans = 0;
    foreach (i; 0..n)
    {
        long a = read!long;
        long b = read!long;
        long c = read!long;

        if (sign(a * x1 + b * y1 + c) *
            sign(a * x2 + b * y2 + c) < 0)
        {
            ans++;
        }
    }

    writeln(ans);

    return 0;
}


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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto t  = RD!int;
	auto nk = new long[2][](t);
	foreach (i; 0..t)
	{
		nk[i] = [RD, RD];
	}

	foreach (i; 0..t)
	{
		auto n = nk[i][0];
		auto k = nk[i][1];
		long ans;
		while (n != 0)
		{
			auto x = n % k;
			if (x == 0)
			{
				n /= k;
				++ans;
			}
			else
			{
				n -= x;
				ans += x;
			}
		}
		writeln(ans);
	}

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

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 INF = 1 << 29;

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto s = readln.split.map!(to!long);
        auto N = s[0];
        auto K = s[1];
        long cnt = 0;
        while (N > 0) {
            long m = N % K;
            if (m == 0) {
                N /= K;
                cnt += 1;
            } else {
                N -= m;
                cnt += m;
            }
        }
        cnt.writeln;
    }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		long n, k;
		readf !(" %s %s") (n, k);
		long res = 0;
		while (n > 0)
		{
			res += n % k;
			n -= n % k;
			if (n > 0)
			{
				res += 1;
				n /= k;
			}
		}
		writeln (res);
	}
}

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

void main() {
  long nt;
  readf!" %d" (nt);
  while (--nt >= 0) {
    long n, k;
    readf!" %d %d" (n, k);
    long res;
    while (n >= k) {
      res += 1 + (n % k);
      debug stderr.writeln (res);
      n /= k;
    }
    res += n;
    writeln (res);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int t = read.to!int;
	foreach(_; 0 .. t){

		long n = read.to!long;
		long k = read.to!long;

		long ans;
		while(n > 0){
			if(n % k == 0) ans += 1, n /= k;
			else ans += n % k, n -= (n % k);
		}

		ans.writeln;
	}
}

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

void main ()
{
	long n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		long res = 0;
		while (n > 0)
		{
			res += n % k;
			n /= k;
		}
		writeln (res);
	}
}


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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!T(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

void main()
{
  int t;
  read(t);
  foreach(i; 0 .. t)
    {
      long n;
      read(n);
      if (n % 4 == 0)
        writeln("YES");
      else
        writeln("NO");
    }
}

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		ans[ti] = n % 4 == 0;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}

import std.conv;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		writeln (n % 4 == 0 ? "YES" : "NO");
	}
}


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

unittest{
  assert(solve(10,"DZFDFZDFDDDDDDF") == 82, "Teste 1");
  assert(solve(4,"YJSNPI") == 4, "Teste 1");
}

ulong solve(ulong k, string s){
  ulong sum = 0;

  ulong[immutable(char)] h;
  ulong[26] hi;

  foreach(c;s){
    ++h[c];
  }

  foreach(cc;h.keys){
    hi[cc-65] = h[cc];
  }

  while(k > 0){
    size_t max = 0;
    for(size_t i = 0; i < hi.length; i++){
      if(hi[i] > hi[max]){
        max = i;
      }
    }
    auto pts = min(k,hi[max]);
    k -= pts;

    sum += pts*pts;
    hi[max] = 0;
  }

  debug(1) writeln(sum);
  return sum;
}

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

  writeln(solve(k,s));
}

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

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

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

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

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

int N, K;
string A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		A = readToken;

		long[] cnt = new long[26];
		foreach (a; A) {
			++cnt[a - 'A'];
		}

		cnt.sort!"a > b";
		long ans;
		long k = K;
		foreach (c; cnt) {
			const tmp = min(c, k);
			ans += tmp * tmp;
			k -= tmp;
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

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

unittest{
  assert(solve(10,"DZFDFZDFDDDDDDF") == 82, "Teste 1");
  assert(solve(4,"YJSNPI") == 4, "Teste 1");
}

ulong solve(ulong k, string s){
  auto sum = 0;

  ulong[immutable(char)] h;
  ulong[26] hi;

  foreach(c;s){
    ++h[c];
  }

  foreach(cc;h.keys){
    hi[cc-65] = h[cc];
  }

  while(k > 0){
    size_t max = 0;
    for(size_t i = 0; i < hi.length; i++){
      if(hi[i] > hi[max]){
        max = i;
      }
    }
    auto pts = min(k,hi[max]);
    k -= pts;

    sum += pts*pts;
    hi[max] = 0;
  }

  debug(1) writeln(sum);
  return sum;
}

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

  writeln(solve(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(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 m = RD!int;
		auto a = new string[](n);
		foreach (i; 0..n)
		{
			a[i] = RD!string;
		}

		foreach (i; 0..n)
		{
			if (a[i][$-1] == 'R')
				++ans[ti];
		}
		foreach (i; 0..m)
		{
			if (a[$-1][i] == 'D')
				++ans[ti];
		}
	}

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

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 rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		auto board = rows.iota.map !(_ => readln.strip).array;
		int res = 0;
		foreach (row; 0..rows - 1)
		{
			res += (board[row][cols - 1] != 'D');
		}
		foreach (col; 0..cols - 1)
		{
			res += (board[rows - 1][col] != 'R');
		}
		writeln (res);
	}
}


// code by cutx64

module main;

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

void main() {

  int n;
  while(readf!"%s\n"(n)> 0) {
    auto adj = new bool[int][n];
    int[] ask(int v) {
      writefln!"? %s"(v + 1);
      stdout.flush();
      auto input = readln.splitter.map!(to!int).array;
      foreach(i; 0 .. n) {
        if (input[i] == 1) {
          adj[v][i] = true;
          adj[i][v] = true;
        }
      }
      return input;
    }
    auto d = ask(0);
    auto odds = iota(1, n).filter!(i => (d[i] & 1) == 1).array;
    auto evens = iota(1, n).filter!(i => (d[i] & 1) == 0).array;
    auto list = (odds.length < evens.length) ? odds : evens;
    foreach (ref v; list) {
      ask(v);
    }
    writeln("!");
    foreach(i; 0 .. n) {
      foreach(j, _; adj[i]) {
        if(j > i) {
          writefln!"%s %s\n"(i + 1, j + 1);
        }
      }
    }
    stdout.flush();
  }

} // main

import std.stdio;
import std.typecons;
import std.ascii;
import std.algorithm;
import std.range;
import std.container;

void main()
{
	int n = readInt!int;
	auto edges = new RedBlackTree!(Tuple!(int, int))();
	int[] query(int r)
	{
		debug writeln("asking for ", r);
		r += 1;
		writeln("? ", r);
		stdout.flush;
		int[] ans = new int[](n);
		foreach(ref ansi; ans) ansi = readInt!int;
		return ans;
	}
	void addEdges(int r, int[] dist)
	{
		foreach(i, disti; dist)
			if (disti == 1)
			{
				debug writeln("dist ", r, " -> ", i);
				auto mn = min(cast(int)i, r);
				auto mx = max(cast(int)i, r);
				edges.insert(tuple(mn, mx));

			}
	}
	auto dist0 = query(0);
	addEdges(0, dist0);
	int[2] cnt;
	foreach(di; dist0)
	{
		if (di >= 1)
		{
			cnt[di%2]++;
		}
	}
	int s = 0;
	if (cnt[1] < cnt[0]) s = 1;
	foreach(i, di; dist0)
	{
		if (di >= 1 && di % 2 == s)
		{
			addEdges(cast(int)i, query(cast(int)i));
		}
	}
	writeln("!");
	foreach(edge; edges)
	{
		writeln(edge[0] + 1, " ", edge[1] + 1);
	}
	writeln;
	stdout.flush;
}

/* INPUT ROUTINES */
static import core.stdc.stdio;
int currChar;
static this()
{
	currChar = ' ';
}

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

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

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;

		auto adj = new bool [int] [n];

		int [] ask (int v)
		{
			writeln ("? ", v + 1);
			stdout.flush ();

			auto res = readln.splitter.map !(to !(int)).array;
			foreach (i; 0..n)
			{
				if (res[i] == 1)
				{
					adj[v][i] = true;
					adj[i][v] = true;
				}
			}
			return res;
		}

		auto d = ask (0);
		auto odds = iota (1, n).filter !(i => (d[i] & 1) == 1).array;
		auto evens = iota (1, n).filter !(i => (d[i] & 1) == 0).array;
		auto list = (odds.length < evens.length) ? odds : evens;
		foreach (ref v; list)
		{
			ask (v);
		}

		writeln ("!");
		foreach (i; 0..n)
		{
			foreach (j, _; adj[i])
			{
				if (j > i)
				{
					writeln (i + 1, " ", j + 1);
				}
			}
		}
		stdout.flush ();
	}
}


// cheese-cracker [2022-05-03]

int[] pals;
long[] dp;
const long MOD = 1_000_000_007;

bool check_pal(int m){
    int[] wval;
    while(m > 0){
        wval ~= (m % 10);
        m /= 10;
    }
    int[] rev = wval.dup.reverse;
    return (wval == rev);
}

void preprocess(){
    int N = 50_000;
    for(int m = 1; m < N; ++m){
        if(check_pal(m)){
            pals ~= m;
        }
    }
    dp = new long[](N);
    dp[0] = 1;
    foreach(k; pals){
        for(int m = k; m < N; ++m){
            dp[m] += dp[m - k];
            dp[m] %= MOD;
        }
    }
}

void solve(){
    writeln(dp[scan!int]);
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
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; } }

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;
  enum MAX = 4 * 10^^4 + 10;

  auto solve() {
    int[] palindromicNumbers(int limit) {
      int [] ret;
      foreach(i; 1..limit) {
        auto s = i.to!string;
        auto r = (cast(char[])s.dup).reverse.array.to!string;
        if (s == r) ret ~= i;
      }

      return ret;
    }

    auto dp = new MInt1[](MAX + 1);
    dp[0] = 1;
    foreach(p; palindromicNumbers(MAX)) {
      foreach(from; 0..MAX - p + 1) {
        dp[from + p] += dp[from];
      }
    }

    foreach(i; 0..QN) {
      auto N = scan!int;
      dp[N].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"];

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


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

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

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

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

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

immutable LIM = 2_000_000;

int N;
long K;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;

		writeln(K * (6 * N - 1));
		foreach (i; 0 .. N) {
			writeln(
				K * (6 * i + 1), " ",
				K * (6 * i + 2), " ",
				K * (6 * i + 3), " ",
				K * (6 * i + 5)
			);
		}
	}
	} catch (EOFException) {}
}

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

int fun (int i, int x, int k) {return (i * 6 + x) * k;}

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		writeln ((n * 6 - 1) * k);
		foreach (i; 0..n)
		{
			writeln ((i * 6 + 1) * k, ' ',
			(i * 6 + 2) * k, ' ',
			(i * 6 + 3) * k, ' ',
			(i * 6 + 5) * k);
		}
	}
}