You have a full binary tree having infinite levels.Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1. The value of the root is 1. You need to answer Q queries. There are 3 types of queries:  Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected). Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them). Print the value of every node encountered on the simple path from the node with value X to the root.Positive K implies right cyclic shift and negative K implies left cyclic shift. It is guaranteed that atleast one type 3 query is present.

The first line contains a single integer Q (1 ≤ Q ≤ 105). Then Q queries follow, one per line:   Queries of type 1 and 2 have the following format: T X K (1 ≤ T ≤ 2; 1 ≤ X ≤ 1018; 0 ≤ |K| ≤ 1018), where T is type of the query. Queries of type 3 have the following format: 3 X (1 ≤ X ≤ 1018).

For each query of type 3, print the values of all nodes encountered in descending order.

NoteFollowing are the images of the first 4 levels of the tree in the first test case:Original:    After query 1 2 1:    After query 2 4 -1:

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 pickV(R,T...)(ref R r,ref T t){foreach(ref v;t)pick(r,v);}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int q; readV(q);

  auto v = new long[](64), n = new long[](64);

  foreach (_; 0..q) {
    auto rd = rdsp;
    int t; long x; pickV(rd, t, x);
    auto r = x.bsr, r2 = (1L<<r);
    switch (t) {
    case 1:
      long k; pick(rd, k);
      (v[r] += k%r2 + r2) %= r2;
      break;
    case 2:
      long k; pick(rd, k);
      (n[r] += k%r2 + r2) %= r2;
      break;
    case 3:
      auto s = new long[](r+1);
      foreach (i; 1..r+1) s[i] = (s[i-1]*2+n[i])%(1L<<i);

      auto ri = x.bitReset(r)+v[r]+s[r];
      foreach_reverse (i; 0..r+1) {
        auto si = (v[i]+s[i])%(1L<<i);
        auto y = (((1L<<i)-si+ri)%(1L<<i)).bitSet(i);
        write(y);
        if (i > 0) write(" ");
        ri >>= 1;
      }
      writeln;
      break;
    default:
      assert(0);
    }
  }
}

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

enum E = 61;

void main() {
  try {
    for (; ; ) {
      const Q = readInt();
      auto T = new int[Q];
      auto X = new long[Q];
      auto K = new long[Q];
      foreach (q; 0 .. Q) {
        T[q] = readInt();
        X[q] = readLong();
        if (T[q] == 1 || T[q] == 2) {
          K[q] = readLong();
        }
      }

      // e: [2^e, 2^(e+1))
      auto xs = new long[E];
      auto ys = new long[E];
      auto zs = new long[E];
      foreach (q; 0 .. Q) {
        int e = bsr(X[q]);
        switch (T[q]) {
          case 1: {
            (xs[e] += K[q]) &= ((1L << e) - 1);
          } break;
          case 2: {
            (ys[e] += K[q]) &= ((1L << e) - 1);
            long k = K[q] & ((1L << e) - 1);
            foreach (f; e .. E) {
              (zs[f] += k) &= ((1L << f) - 1);
              k <<= 1;
            }
          } break;
          case 3: {
            debug {
              writeln("query ", X[q]);
              writeln("  xs = ", xs);
              writeln("  ys = ", ys);
              writeln("  zs = ", zs);
            }
            long[] ans;
            long u = X[q];
            // u = (1L << e) + ((u - (1L << e) - zs[e]) & ((1L << e) - 1));
            u = (1L << e) + ((u - (1L << e) + xs[e]) & ((1L << e) - 1));
            for (; ; ) {
              const val = (1L << e) + ((u - (1L << e) - xs[e]) & ((1L << e) - 1));
              ans ~= val;
              if (e == 0) {
                break;
              }
              u = (1L << e) + ((u - (1L << e) + ys[e]) & ((1L << e) - 1));
              u >>= 1;
              --e;
            }
            foreach (idx, val; ans) {
              if (idx > 0) write(" ");
              write(val);
            }
            writeln();
          } break;
          default: assert(false);
        }
      }
    }
  } 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)); }

enum E = 61;

void main() {
  try {
    for (; ; ) {
      const Q = readInt();
      auto T = new int[Q];
      auto X = new long[Q];
      auto K = new long[Q];
      foreach (q; 0 .. Q) {
        T[q] = readInt();
        X[q] = readLong();
        if (T[q] == 1 || T[q] == 2) {
          K[q] = readLong();
        }
      }

      // e: [2^e, 2^(e+1))
      auto xs = new long[E];
      auto ys = new long[E];
      foreach (q; 0 .. Q) {
        int e = bsr(X[q]);
        switch (T[q]) {
          case 1: {
            (xs[e] += K[q]) &= ((1L << e) - 1);
          } break;
          case 2: {
            (ys[e] += K[q]) &= ((1L << e) - 1);
          } break;
          case 3: {
            debug {
              writeln("query ", X[q]);
              writeln("  xs = ", xs);
              writeln("  ys = ", ys);
            }
            long[] ans;
            long u = X[q];
            for (; ; ) {
              const val = (1L << e) + ((u - (1L << e) - xs[e]) & ((1L << e) - 1));
              ans ~= val;
              if (e == 0) {
                break;
              }
              u = (1L << e) + ((u - (1L << e) + ys[e]) & ((1L << e) - 1));
              u >>= 1;
              --e;
            }
            foreach (idx, val; ans) {
              if (idx > 0) write(" ");
              write(val);
            }
            writeln();
          } break;
          default: assert(false);
        }
      }
    }
  } 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)); }

enum E = 61;

void main() {
  try {
    for (; ; ) {
      const Q = readInt();
      auto T = new int[Q];
      auto X = new long[Q];
      auto K = new long[Q];
      foreach (q; 0 .. Q) {
        T[q] = readInt();
        X[q] = readLong();
        if (T[q] == 1 || T[q] == 2) {
          K[q] = readLong();
        }
      }

      // e: [2^e, 2^(e+1))
      auto xs = new long[E];
      auto ys = new long[E];
      auto zs = new long[E];
      foreach (q; 0 .. Q) {
        int e = bsr(X[q]);
        switch (T[q]) {
          case 1: {
            (xs[e] += K[q]) &= ((1L << e) - 1);
          } break;
          case 2: {
            (ys[e] += K[q]) &= ((1L << e) - 1);
            long k = K[q] & ((1L << e) - 1);
            foreach (f; e .. E) {
              (zs[f] += k) &= ((1L << f) - 1);
              k <<= 1;
            }
          } break;
          case 3: {
            debug {
              writeln("query ", X[q]);
              writeln("  xs = ", xs);
              writeln("  ys = ", ys);
            }
            long[] ans;
            long u = X[q];
            u = (1L << e) + ((u - (1L << e) - zs[e]) & ((1L << e) - 1));
            for (; ; ) {
              const val = (1L << e) + ((u - (1L << e) - xs[e]) & ((1L << e) - 1));
              ans ~= val;
              if (e == 0) {
                break;
              }
              u = (1L << e) + ((u - (1L << e) + ys[e]) & ((1L << e) - 1));
              u >>= 1;
              --e;
            }
            foreach (idx, val; ans) {
              if (idx > 0) write(" ");
              write(val);
            }
            writeln();
          } break;
          default: assert(false);
        }
      }
    }
  } catch (EOFException e) {
  }
}


On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last.  The red stripe was painted after the blue one, so the answer is R.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.

For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).

NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    readln;
    string[] grid;
    foreach (i ; 0 .. 8)
      grid ~= readln.strip;

    char ans = '?';

    foreach (i ; 0 .. 8) {
      char first = grid[i][0];
      bool match = (first == 'R');
      foreach (j ; 1 .. 8) {
        if (grid[i][j] != first) {
          match = false;
          break;
        }
      }
      if (match)
        ans = first;
    }

    foreach (i ; 0 .. 8) {
      char first = grid[0][i];
      bool match = (first == 'B');
      foreach (j ; 1 .. 8) {
        if (grid[j][i] != first) {
          match = false;
          break;
        }
      }
      if (match)
        ans = first;
    }

    writeln(ans);
  }
}

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

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

void solve() {
    readln;
    int N = 8;
    auto F = new string[N];
    foreach (i; 0 .. N) F[i] = readln.chomp;

    char f() {
        bool allY(int y) {
            return F[y].all!(c => c == 'R');
        }
        bool allX(int x) {
            return iota(N).all!(y => F[y][x] == 'B');
        }
        for (int y = 0; y < N; y++) {
            if (allY(y)) return 'R';
        }
        for (int x = 0; x < N; x++) {
            if (allX(x)) return 'B';
        }
        assert(false);
    }
    writeln(f());
}

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

import std;

int t;

void main() {
    scanf("%d\n", &t);
    foreach(_;0..t) {
        bool flag = false;
        foreach(k; 0..8){
            string row_s = readln.strip;
            char[] row = row_s.dup;
            if ((uniq(row).array.length == 1) && (row[0] == 'R')) {
                flag = true;
            }
        }
        readln;
        if (flag)
            writeln("R");
        else
            writeln("B");
    }
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    readln;
    string[] grid;
    foreach (i ; 0 .. 8)
      grid ~= readln.strip;
    char ans = '?';
    foreach (i ; 0 .. 8) {
      char first = grid[i][0];
      bool match = (first != '.');
      foreach (j ; 1 .. 8) {
        if (grid[i][j] != first) {
          match = false;
          break;
        }
      }
      if (match)
        ans = first;
    }
    foreach (i ; 0 .. 8) {
      char first = grid[0][i];
      bool match = (first != '.');
      foreach (j ; 1 .. 8) {
        if (grid[j][i] != first) {
          match = false;
          break;
        }
      }
      if (match)
        ans = first;
    }
    writeln(ans);
  }
}

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

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

void solve() {
    readln;
    int N = 8;
    auto F = new string[N];
    foreach (i; 0 .. N) F[i] = readln.chomp;

    char f() {
        bool allY(int y) {
            return F[y].all!(c => c == 'R') || F[y].all!(c => c == 'B');
        }
        bool allX(int x) {
            return iota(N).all!(y => F[y][x] == 'R')
                || iota(N).all!(y => F[y][x] == 'B');
        }
        for (int y = 0; y < N; y++) {
            if (allY(y)) return F[y][0];
        }
        for (int x = 0; x < N; x++) {
            if (allX(x)) return F[0][x];
        }
        assert(false);
    }
    writeln(f());
}

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

import std;

int t;

void main() {
    scanf("%d\n", &t);
    outer: foreach(_;0..t) {
        foreach(k; 0..9){
            string row_s = readln.strip;
            char[] row = row_s.dup;
            if ((uniq(row).array.length == 1) && (row[0] == 'R')) {
                writeln("R");
                continue outer;
            }
        }
        writeln("B");
    }
}


You are given a string $$$s$$$ consisting of characters 0 and/or 1.You have to remove several (possibly zero) characters from the beginning of the string, and then several (possibly zero) characters from the end of the string. The string may become empty after the removals. The cost of the removal is the maximum of the following two values:  the number of characters 0 left in the string;  the number of characters 1 removed from the string. What is the minimum cost of removal you can achieve?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), consisting of characters 0 and/or 1. The total length of strings $$$s$$$ in all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum cost of removal you can achieve.

NoteConsider the test cases of the example:  in the first test case, it's possible to remove two characters from the beginning and one character from the end. Only one 1 is deleted, only one 0 remains, so the cost is $$$1$$$;  in the second test case, it's possible to remove three characters from the beginning and six characters from the end. Two characters 0 remain, three characters 1 are deleted, so the cost is $$$3$$$;  in the third test case, it's optimal to remove four characters from the beginning;  in the fourth test case, it's optimal to remove the whole string;  in the fifth test case, it's optimal to leave the string as it is.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;
      int n = cast(int)S.length;

      auto pre = new int[](n + 1);
      auto suf = new int[](n + 1);
      foreach(i; 1..n + 1) {
        pre[i] = pre[i - 1] + (S[i - 1] == '0');
        suf[i] = suf[i - 1] + (S[n - i] == '0');
      }
      // pre.deb;
      // suf.deb;

      int a, ans;
      a = ans = pre[n];
      foreach(i; 0..a + 1) {
        ans = min(ans, a - pre[i] - suf[a - i]);
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

struct SegTree(alias pred = "a + b", T = long) {
  alias predFun = binaryFun!pred;
  int size;
  T[] data;
  T monoid;

  this(T[] src, T monoid = T.init) {
    this.monoid = monoid;

    for(int i = 2; i < 2L^^32; i *= 2) {
      if (src.length <= i) {
        size = i;
        break;
      }
    }

    data = new T[](size * 2);
    foreach(i, s; src) data[i + size] = s;
    foreach_reverse(b; 1..size) {
      data[b] = predFun(data[b * 2], data[b * 2 + 1]);
    }
  }

  void update(int index, T value) {
    int i = index + size;
    data[i] = value;
    while(i > 0) {
      i /= 2;
      data[i] = predFun(data[i * 2], data[i * 2 + 1]);
    }
  }

  T get(int index) {
    return data[index + size];
  }

  T sum(int a, int b, int k = 1, int l = 0, int r = -1) {
    if (r < 0) r = size;

    if (r <= a || b <= l) return monoid;
    if (a <= l && r <= b) return data[k];

    T leftValue = sum(a, b, 2*k, l, (l + r) / 2);
    T rightValue = sum(a, b, 2*k + 1, (l + r) / 2, r);
    return predFun(leftValue, rightValue);
  }
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;
      int n = cast(int)S.length;

      auto a = new int[](n + 2);
      auto b = new int[](n + 2);
      auto c = new int[](n + 2);
      foreach(i; 1..n + 1) a[i] = (S[i - 1] - '0') ^ 1;
      foreach(i; 1..n + 1) b[i] = b[i - 1] + a[i];
      foreach(i; iota(n, 0, -1)) c[i] = c[i + 1] + a[i];

      long ans = b[n];
      foreach(i; 0.. b[n] + 1) ans = min(ans, b[n] - (b[i] + c[n - b[n] + i + 1]));
      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

struct SegTree(alias pred = "a + b", T = long) {
  alias predFun = binaryFun!pred;
  int size;
  T[] data;
  T monoid;

  this(T[] src, T monoid = T.init) {
    this.monoid = monoid;

    for(int i = 2; i < 2L^^32; i *= 2) {
      if (src.length <= i) {
        size = i;
        break;
      }
    }

    data = new T[](size * 2);
    foreach(i, s; src) data[i + size] = s;
    foreach_reverse(b; 1..size) {
      data[b] = predFun(data[b * 2], data[b * 2 + 1]);
    }
  }

  void update(int index, T value) {
    int i = index + size;
    data[i] = value;
    while(i > 0) {
      i /= 2;
      data[i] = predFun(data[i * 2], data[i * 2 + 1]);
    }
  }

  T get(int index) {
    return data[index + size];
  }

  T sum(int a, int b, int k = 1, int l = 0, int r = -1) {
    if (r < 0) r = size;

    if (r <= a || b <= l) return monoid;
    if (a <= l && r <= b) return data[k];

    T leftValue = sum(a, b, 2*k, l, (l + r) / 2);
    T rightValue = sum(a, b, 2*k + 1, (l + r) / 2, r);
    return predFun(leftValue, rightValue);
  }
}

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

auto go (T) (T c)
{
	int [] s = [0];
	foreach (ref x; c)
	{
		s ~= s.back + (x ? +1 : -1);
	}
	return s;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto a = readln.strip.map !(q{a - '0'}).array;
		auto n = a.length.to !(int);
		auto s0 = [0];
		foreach (ref c; a)
		{
			s0 ~= s0.back + !c;
		}
		auto s1 = [0];
		foreach (ref c; a)
		{
			s1 ~= s1.back + c;
		}

		bool go (int limit)
		{
			int j = 0;
			int cur0 = 0;
			foreach (i; 0..n)
			{
				j = max (j, i);
				while (j < n && s0[j + 1] - s0[i] <= limit)
				{
					j += 1;
				}
				if (s1[i] - s1[0] + s1[n] - s1[j] <= limit)
				{
					return true;
                                }
			}
			return false;
		}

		int lo = 0;
		int hi = n;
		while (lo < hi)
		{
			int me = (lo + hi) / 2;
			if (go (me))
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}
		writeln (lo);
	}
}


You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $$$x$$$ that occurs in the array $$$2$$$ or more times. Take the first two occurrences of $$$x$$$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $$$2 \cdot x$$$).Determine how the array will look after described operations are performed.For example, consider the given array looks like $$$[3, 4, 1, 2, 2, 1, 1]$$$. It will be changed in the following way: $$$[3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1]$$$.If the given array is look like $$$[1, 1, 3, 1, 1]$$$ it will be changed in the following way: $$$[1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4]$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 150\,000$$$) — the number of elements in the array. The second line contains a sequence from $$$n$$$ elements $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{9}$$$) — the elements of the array.

In the first line print an integer $$$k$$$ — the number of elements in the array after all the performed operations. In the second line print $$$k$$$ integers — the elements of the array after all the performed operations.

NoteThe first two examples were considered in the statement.In the third example all integers in the given array are distinct, so it will not change.

import std.algorithm.iteration;
import std.algorithm.mutation;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.container.rbtree;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons : Tuple;

alias Lookup = Tuple!(ulong, "value", RedBlackTree!ulong, "indices");

// steps:
// - take smallest value of x that occurs 2 or more times
// - remove the first from the left
// - double the second

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

  auto arr = readln
    .stripRight
    .split
    .map!(a => a.parse!ulong)
    .array;
  auto counts = arr
    .enumerate
    .array
    .sort!("a.value < b.value", SwapStrategy.stable)
    .chunkBy!"a.value == b.value"
    .map!(a => Lookup(a.front.value, redBlackTree(a.map!"ulong(a.index)")))
    .redBlackTree!"a.value < b.value";

  // count number of values we've dropped
  auto dropped = 0;

  while (!counts.empty) {
    auto f = counts.front;
    if (f.indices.length < 2) {
      counts.removeKey(f);
      continue;
    }

    // first element would be dropped
    dropped++;

    // position of second element (to be doubled)
    // set first element to 0
    arr[to!uint(f.indices.front)] = 0;
    f.indices.removeFront();
    arr[to!uint(f.indices.front)] *= 2;
    auto pos = f.indices.front;
    f.indices.removeFront();

    counts.removeKey(f);
    counts.insert(f);

    // find element to insert
    auto newKey = Lookup(f.value * 2, redBlackTree(pos));
    auto r = counts.equalRange(newKey);
    if (!r.empty) {
      // insert new position into existing array
      auto l = r.front;
      // drop existing key
      counts.removeKey(l);
      // add new index in-place
      l.indices.insert(pos);
      // replace key
      newKey = l;
    }
    counts.insert(newKey);
  }

  writeln(n - dropped);
  // final array
  auto f = arr.filter!(a => a != 0);
  writeln(f.map!(a => a.to!string).joiner(" "));
}

import std.algorithm.iteration;
import std.algorithm.mutation;
import std.algorithm.searching;
import std.algorithm.sorting;
import std.container.dlist;
import std.container.rbtree;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons : Tuple;

alias Lookup = Tuple!(int, "value", ulong, "len", DList!ulong, "indices");

// steps:
// - take smallest value of x that occurs 2 or more times
// - remove the first from the left
// - double the second

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

  auto arr = readln
    .stripRight
    .split
    .map!(a => a.parse!int)
    .array;
  auto counts = arr
    .enumerate
    .array
    .sort!("a.value < b.value", SwapStrategy.stable)
    .chunkBy!"a.value == b.value"
    .map!(a => Lookup(a.front.value, a.array.length, DList!ulong(a.map!"a.index")))
    .redBlackTree!"a.value < b.value";

  // count number of values we've dropped
  auto dropped = 0;

  while (!counts.empty) {
    auto f = counts.front;
    if (f.len < 2) {
      counts.removeKey(f);
      continue;
    }

    // first element would be dropped
    dropped++;

    // position of second element (to be doubled)
    // set first element to 0
    arr[to!uint(f.indices.front)] = 0;
    f.indices.removeFront();
    arr[to!uint(f.indices.front)] *= 2;
    auto pos = f.indices.front;
    f.indices.removeFront();
    f.len -= 2;

    counts.removeKey(f);
    counts.insert(f);

    // find element to insert
    auto newKey = Lookup(f.value * 2, 1, DList!ulong(pos));
    auto r = counts.equalRange(newKey);
    if (!r.empty) {
      // insert new position into existing array
      auto l = r.front;
      // drop existing key
      counts.removeKey(l);
      // add new index in-place
      auto ir = l.indices[].find!"a > b"(pos);
      if (ir.empty) {
	l.indices.insert(pos);
      } else {
	l.indices.insertBefore(ir, pos);
      }

      // replace key
      l.len++;
      newKey = l;
    }
    counts.insert(newKey);
  }

  writeln(n - dropped);
  // final array
  auto f = arr.filter!(a => a != 0);
  writeln(f.map!(a => a.to!string).joiner(" "));
}


You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operations on it:  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(0 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j+x$$$ for all $$$(1 \le j \le i)$$$, which means add $$$x$$$ to all the elements in the prefix ending at $$$i$$$.  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(1 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j \% x$$$ for all $$$(1 \le j \le i)$$$, which means replace every element in the prefix ending at $$$i$$$ with the remainder after dividing it by $$$x$$$. Can you make the array strictly increasing in no more than $$$n+1$$$ operations?

The first line contains an integer $$$n$$$ $$$(1 \le n \le 2000)$$$, the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\dots$$$, $$$a_n$$$ $$$(0 \le a_i \le 10^5)$$$, the elements of the array $$$a$$$.

On the first line, print the number of operations you wish to perform. On the next lines, you should print the operations. To print an adding operation, use the format "$$$1$$$ $$$i$$$ $$$x$$$"; to print a modding operation, use the format "$$$2$$$ $$$i$$$ $$$x$$$". If $$$i$$$ or $$$x$$$ don't satisfy the limitations above, or you use more than $$$n+1$$$ operations, you'll get wrong answer verdict.

NoteIn the first sample, the array is already increasing so we don't need any operations.In the second sample:In the first step: the array becomes $$$[8,6,3]$$$.In the second step: the array becomes $$$[0,2,3]$$$.

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

void main() {
  int n = readln.strip.to!int;
  auto v = readln.splitter.map!(to!long).array;
  v.reverse;
  long md = 5000;
  writeln(n+1);
  //make v[i] = -i mod md.
  foreach(i,x;v) {
    //x + i + delta = k*md
    long target = (x+i+md)/md*md;
    long d = target - (x+i+1);
    v[i..$] += d;
    writefln!"1 %d %d" (n-i, d);
    debug {writeln(v);}
  }
  v.reverse;
  v[] %= md;
  debug {writeln(v);}
  writefln!"2 %d %d" (n, md);
}

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;

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

    auto ans = new long[](N);
    long a = 0;

    foreach_reverse (i; 0..N) {
        long m = (A[i] + a) % N;
        long b = ((i - m) % N + N) % N;
        ans[i] = b;
        a += b;
    }

    writeln(N+1);
    foreach (i; 0..N) {
        writeln(1, " ", N-i, " ", ans[N-i-1]);
    }
    writeln(2, " ", N, " ", N);
}

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;

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

    auto ans = new long[](N);
    long a = 0;

    foreach_reverse (i; 0..N) {
        long m = (A[i] + a) % N;
        long b = ((i - m) % N + N) % N;
        ans[i] = b;
        a += b;
    }

    writeln(N+1);
    foreach (i; 0..N) {
        writeln(1, " ", N-i, " ", ans[N-i-1]);
    }
    writeln(2, " ", 1, " ", N);
}


Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.

The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3.

Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.

NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right.

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

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

// import dkh.array, dkh.dungeon;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) sc.read!true;

    int h, w;
    sc.read(h, w);
    char[][] g = new char[][](h, w);
    foreach (r; 0..h) sc.read(g[r]);

    string _s;
    sc.read(_s);
    int[] s = _s.map!(c => c-'0').map!(to!int).array;

    int ans = 0;
    foreach (idx; iota(4).permutations) {
        int[2] sv = g.findFirst2D('S');
        int[2] tv = g.findFirst2D('E');
        auto dh = Dungeon(h, w);
        bool f = true;
        foreach (_d; s) {
            int d = idx[_d];
            sv = dh.move4(sv, d);
            if (!dh.isInside(sv)) {
                f = false;
                break;
            }
            if (g.at2D(sv) == '#') {
                f = false;
                break;
            }
            if (sv == tv) break;
        }
        if (!f) continue;
        if (sv != tv) continue;
        ans++;
    }
    writeln(ans);
    return 0;
}
/* IMPORT /Users/yosupo/Program/dunkelheit/source/dkh/array.d */
// module dkh.array;

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

int[2] findFirst2D(T, U)(in T mp, in U c) {
    import std.conv : to;
    int R = mp.length.to!int;
    int C = mp[0].length.to!int;
    foreach (i; 0..R) {
        foreach (j; 0..C) {
            if (mp[i][j] == c) return [i, j];
        }
    }
    assert(false);
}

auto ref at2D(T, U)(ref T mp, in U idx) {
    return mp[idx[0]][idx[1]];
}

/* IMPORT /Users/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 /Users/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 /Users/yosupo/Program/dunkelheit/source/dkh/dungeon.d */
// module dkh.dungeon;

immutable static int[2][4] direction4 = [
    [1, 0], [0, 1], [-1, 0], [0, -1],
];

immutable static int[2][8] direction8 = [
    [1, 0],
    [1, 1],
    [0, 1],
    [-1, 1],
    [-1, 0],
    [-1, -1],
    [0, -1],
    [1, -1],
];

static int[2] addInt2(in int[2] a, in int[2] b) {
    int[2] c;
    c[] = a[] + b[];
    return c;
}

struct Dungeon {

    static int[2] move4(int[2] p, int dir) {
        return addInt2(p, direction4[dir]);
    }

    static int[2] move8(int[2] p, int dir) {
        return addInt2(p, direction8[dir]);
    }

    immutable int R, C;

    this(int R, int C) {
        this.R = R;
        this.C = C;
    }

    bool isInside(int[2] p) const {
        int r = p[0], c = p[1];
        return 0 <= r && r < R && 0 <= c && c < C;
    }

    int getID(int[2] p) const {
        int r = p[0], c = p[1];
        return r*R+c;
    }
}

auto neighbors4(int[2] p) {
    static struct Rng {
        int[2] center;
        size_t i;
        bool empty() const { return i == 4;}
        int[2] front() const { return addInt2(center, direction4[i]); }
        void popFront() { i++; }
    }
    return Rng(p, 0);
}

auto neighbors4(int[2] p, in Dungeon dg) {
    static struct Rng {
        int[2] center;
        Dungeon dg;
        size_t i;
        this(in int[2] center, in Dungeon dg) {
            this.center = center;
            this.dg = dg;
            while (!empty() && !dg.isInside(front)) i++;
        }
        bool empty() const { return i == 4;}
        int[2] front() const { return addInt2(center, direction4[i]); }
        void popFront() {
            i++;
            while (!empty() && !dg.isInside(front)) i++;
        }
    }
    return Rng(p, dg);
}

/* IMPORT /Users/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(bool enforceEOF = false, T, Args...)(ref T x, auto ref Args args) {
        import std.exception;
        enforce(readSingle(x));
        static if (args.length == 0) {
            enforce(enforceEOF == false || !succ());
        } else {
            read!enforceEOF(args);
        }
    }
    void read(bool enforceEOF = false, Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length == 0) {
            enforce(enforceEOF == false || !succ());
        } else {
            enforce(readSingle(args[0]));
            read!enforceEOF(args);
        }
    }
}

/*
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 core.bitop;
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;

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		string [] a;
		foreach (row; 0..rows)
		{
			a ~= readln.strip;
		}
		int rowS, colS, rowF, colF;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (a[row][col] == 'S')
				{
					rowS = row;
					colS = col;
				}
				if (a[row][col] == 'E')
				{
					rowF = row;
					colF = col;
				}
			}
		}
		auto commands = readln.strip.map !(x => x - '0').array;

		int res = 0;
		auto p = dirs.iota.array;
		do
		{
			int row = rowS;
			int col = colS;
			foreach (dir; commands)
			{
				row += dRow[p[dir]];
				col += dCol[p[dir]];
				if (row < 0 || rows <= row ||
				    col < 0 || cols <= col)
				{
					break;
				}
				if (a[row][col] == '#')
				{
					break;
				}
				if (tuple (row, col) == tuple (rowF, colF))
				{
					break;
				}
			}
			res += (tuple (row, col) == tuple (rowF, colF));
		}
		while (nextPermutation (p));
		writeln (res);
	}
}

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

  int h, w; rd(h, w);
  auto c=new char[][](h);
  foreach(i; 0..h) c[i]=readln.chomp.to!(char[]);
  auto t=readln.chomp.to!(char[]);

  import std.typecons;
  alias P=Tuple!(int, "i", int, "j");
  P st, gl;
  foreach(i; 0..h)foreach(j; 0..w){
    if(c[i][j]=='S') st=P(i, j);
    if(c[i][j]=='E') gl=P(i, j);
  }
  auto dir=[[-1, 0], [0, 1], [1, 0], [0, -1]]; // LURD
  auto nums=[0, 1, 2, 3];
  int tot=0;
  do{
    auto cur=st;
    foreach(char ch; t){
      int x=ch-'0';
      auto d=dir[nums[x]];
      auto nex=P(cur.i+d[0], cur.j+d[1]);
      if(nex.i<0 || nex.i>=h || nex.j<0 || nex.j>=w) break;
      if(c[nex.i][nex.j]=='#') break;
      if(c[nex.i][nex.j]=='E'){tot++; break;}
      cur=nex;
    }
  }while(nextPermutation(nums));

  writeln(tot);
}

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));
  }
}
void wr(T...)(T x){
  import std.stdio;
  foreach(e; x) write(e, " ");
  writeln();
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const M = readInt();
      const N = readInt();
      auto A = new string[M];
      foreach (x; 0 .. M) {
        A[x] = readToken();
      }
      const S = readToken();

      int sx, sy;
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] == 'S') {
          sx = x;
          sy = y;
        }
      }

      int ans;
      auto perm = iota(4).array;
      do {
        bool ok;
        int x = sx, y = sy;
        foreach (s; S) {
          const dir = perm[s - '0'];
          const xx = x + [+1, 0, -1, 0][dir];
          const yy = y + [0, -1, 0, +1][dir];
          if (0 <= xx && xx < M && 0 <= yy && yy < N && A[xx][yy] != '#') {
            x = xx;
            y = yy;
            if (A[x][y] == 'E') {
              ok = true;
              break;
            }
          } else {
            break;
          }
        }
        if (ok) {
          ++ans;
        }
      } while (perm.nextPermutation);
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import core.bitop;
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;

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		string [] a;
		foreach (row; 0..rows)
		{
			a ~= readln.strip;
		}
		int rowS, colS, rowF, colF;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (a[row][col] == 'S')
				{
					rowS = row;
					colS = col;
				}
				if (a[row][col] == 'E')
				{
					rowF = row;
					colF = col;
				}
			}
		}
		auto commands = readln.strip.map !(x => x - '0').array;

		int res = 0;
		auto p = dirs.iota.array;
		do
		{
			int row = rowS;
			int col = colS;
			foreach (dir; commands)
			{
				row += dRow[p[dir]];
				col += dCol[p[dir]];
				if (row < 0 || rows <= row ||
				    col < 0 || cols <= col)
				{
					break;
				}
				if (tuple (row, col) == tuple (rowF, colF))
				{
					break;
				}
			}
			res += (tuple (row, col) == tuple (rowF, colF));
		}
		while (nextPermutation (p));
		writeln (res);
	}
}


Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.

The first line contains a single integer n (1 ≤ n ≤ 50). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values:  o — in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; x — in this case field (i, j) is attacked by some piece; . — in this case field (i, j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board.

If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n - 1) × (2n - 1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'.

NoteIn the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.

import std.math;
import std.conv;
import std.array;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio : scanf;
import std.algorithm;

struct S {
	int x, y;
}

void main() {
	auto n = readln.strip.to!int, k = 2 * n - 1;
	S[] ps;
	char[][] arr, r;

	r = uninitializedArray!(typeof(r))(k, k);
	foreach(p; r) p[] = '.';
	r[n - 1][n - 1] = 'o';

	foreach(y; 0..n) {
		arr ~= readln.strip.dup;
		foreach(x, c; arr.back) if(c == 'o') ps ~= S(cast(int)x, cast(int)y);
	}

	foreach(y, a; arr)
	foreach(x, ref c; a)
		if(c == 'x') {
			foreach(s; ps) {
				auto dx = x - s.x, dy = y - s.y;
				bool b;

				foreach(u; ps) {
					auto w = u.x + dx, e = u.y + dy;
					if(w >= 0 && w < n && e >= 0 && e < n && arr[e][w] == '.') b = true;
				}

				if(!b) {
					c = 0;

					foreach(u; ps) {
						auto w = u.x + dx, e = u.y + dy;
						if(w >= 0 && w < n && e >= 0 && e < n) arr[e][w] = 0;
					}

					r[n + dy - 1][n + dx - 1] = 'x';
				}
			}
		}

	if(arr.any!(a => a.canFind('x')))
		write(`NO`);
	else
		writef("YES\n%-(%s\n%)", r);
}

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

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

		bool isValid (int row, int col)
		{
			return 0 <= row && row < n &&
			    0 <= col && col < n;
		}

		auto t = '.'.repeat (n * 2 - 1).array
		    .repeat (n * 2 - 1).map!dup.array;

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				bool canHit = true;
				foreach (row; 0..n)
				{
					foreach (col; 0..n)
					{
						if (s[row][col] == 'o')
						{
							if (isValid (row +
							    drow, col + dcol)
							    && s[row + drow]
							    [col + dcol] ==
							    '.')
							{
								canHit = false;
							}
						}
					}
				}
				if (canHit)
				{
					t[drow + (n - 1)][dcol + (n - 1)] =
					    'x';
				}
			}
		}
		t[n - 1][n - 1] = 'o';
		debug {writefln ("%-(%s\n%)", t);}

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				if (t[drow + (n - 1)][dcol + (n - 1)] == 'x')
				{
					foreach (row; 0..n)
					{
						foreach (col; 0..n)
						{
							if (s[row][col] == 'o'
							    && isValid (row +
							    drow, col + dcol)
							    && s[row + drow]
							    [col + dcol] ==
							    'x')
							{
								s[row + drow]
								    [col +
								    dcol] =
								    '.';
							}
						}
					}
				}
			}
		}
		debug {writefln ("%-(%s\n%)", s);}

		bool ok = true;
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				ok &= (s[row][col] != 'x');
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln ("%-(%s\n%)", t);
		}
		else
		{
			writeln ("NO");
		}
	}
}

import std.math;
import std.conv;
import std.array;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio : scanf;
import std.algorithm;

struct S {
	int x, y;
}

void main() {
	auto n = readln.strip.to!int, k = 2 * n - 1;
	S[] ps;
	char[][] arr;

	foreach(y; 0..n) {
		arr ~= readln.strip.dup;
		foreach(x, c; arr.back) if(c == 'o') ps ~= S(cast(int)x, cast(int)y);
	}

	auto r = uninitializedArray!(char[][])(k, k);
	foreach(p; r) p[] = '.';
	r[n - 1][n - 1] = 'o';

	foreach(y, a; arr)
	loop: foreach(x, ref c; a)
		if(c == 'x') {
			foreach(s; ps) {
				auto dx = x - s.x, dy = y - s.y;
				bool b;

				foreach(u; ps) {
					auto w = u.x + dx, e = u.y + dy;
					if(w >= 0 && w < n && e >= 0 && e < n && arr[w][e] == '.') b = true;
				}

				if(!b) {
					c = 0;
					r[n + dx - 1][n + dy - 1] = 'x';
					continue loop;
				}
			}
		}

	if(arr.any!(a => a.canFind('x')))
		write(`NO`);
	else
		writef("YES\n%-(%s\n%)", r);
}

import std.math;
import std.conv;
import std.array;
import std.stdio;
import std.range;
import std.format;
import std.string;
import std.c.stdio : scanf;
import std.algorithm;

struct S {
	int x, y;
}

void main() {
	auto n = readln.strip.to!int, k = 2 * n - 1;
	S[] ps;
	string[] arr;

	foreach(y; 0..n) {
		arr ~= readln.strip;
		foreach(x, c; arr.back) if(c == 'o') ps ~= S(cast(int)x, cast(int)y);
	}

	auto r = uninitializedArray!(char[][])(k, k);
	foreach(p; r) p[] = '.';
	r[n - 1][n - 1] = 'o';

	foreach(y, a; arr)
	foreach(x, c; a)
		if(c == 'x') {
			foreach(s; ps) {
				auto dx = x - s.x, dy = y - s.y;

				foreach(u; ps) {
					auto w = u.x + dx, e = u.y + dy;
					if(w >= 0 && w < n && e >= 0 && e < n && arr[w][e] == '.') return write(`NO`);
				}

				r[n + dx - 1][n + dy - 1] = 'x';
			}
		}

	writef("YES\n%-(%s\n%)", r);
}

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

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

		bool isValid (int row, int col)
		{
			return 0 <= row && row < n &&
			    0 <= col && col < n;
		}

		auto t = '.'.repeat (n * 2 - 1).array
		    .repeat (n * 2 - 1).map!dup.array;

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				bool canHit = true;
				foreach (row; 0..n)
				{
					foreach (col; 0..n)
					{
						if (s[row][col] == 'o')
						{
							if (isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    '.')
							{
								canHit = false;
							}
						}
					}
				}
				if (canHit)
				{
					t[drow + (n - 1)][dcol + (n - 1)] =
					    'x';
				}
			}
		}
		t[n - 1][n - 1] = 'o';
		debug {writefln ("%-(%s\n%)", t);}

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				if (t[drow + (n - 1)][dcol + (n - 1)] == 'x')
				{
					foreach (row; 0..n)
					{
						foreach (col; 0..n)
						{
							if (s[row][col] == 'o'
							    && isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    'x')
							{
								s[row - drow]
								    [col -
								    dcol] =
								    '.';
							}
						}
					}
				}
			}
		}
		debug {writefln ("%-(%s\n%)", s);}

		bool ok = true;
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				ok &= (s[row][col] != 'x');
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln ("%-(%s\n%)", t);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

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

		bool isValid (int row, int col)
		{
			return 0 <= row && row < n &&
			    0 <= col && col < n;
		}

		auto t = '.'.repeat (n * 2 - 1).array
		    .repeat (n * 2 - 1).map!dup.array;

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				bool canHit = true;
				foreach (row; 0..n)
				{
					foreach (col; 0..n)
					{
						if (s[row][col] == 'o')
						{
							if (isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    '.')
							{
								canHit = false;
							}
						}
					}
				}
				if (canHit)
				{
					t[drow + (n - 1)][dcol + (n - 1)] =
					    'x';
				}
			}
		}
		t[n - 1][n - 1] = 'o';
		debug {writefln ("%-(%s\n%)", t);}

		bool ok = true;
		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				if (t[drow + (n - 1)][dcol + (n - 1)] == 'x')
				{
					foreach (row; 0..n)
					{
						foreach (col; 0..n)
						{
							if (s[row][col] == 'o'
							    && isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    '.')
							{
								ok = false;
							}
						}
					}
				}
			}
		}

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				if (t[drow + (n - 1)][dcol + (n - 1)] == 'x')
				{
					foreach (row; 0..n)
					{
						foreach (col; 0..n)
						{
							if (s[row][col] == 'o'
							    && isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    'x')
							{
								s[row - drow]
								    [col -
								    dcol] =
								    '.';
							}
						}
					}
				}
			}
		}
		debug {writefln ("%-(%s\n%)", s);}

		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				ok &= (s[row][col] != 'x');
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln ("%-(%s\n%)", t);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

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

		bool isValid (int row, int col)
		{
			return 0 <= row && row < n &&
			    0 <= col && col < n;
		}

		auto t = '.'.repeat (n * 2 - 1).array
		    .repeat (n * 2 - 1).map!dup.array;

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				bool canHit = true;
				foreach (row; 0..n)
				{
					foreach (col; 0..n)
					{
						if (s[row][col] == 'o')
						{
							if (isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    '.')
							{
								canHit = false;
							}
						}
					}
				}
				if (canHit)
				{
					t[drow + (n - 1)][dcol + (n - 1)] =
					    'x';
				}
			}
		}
		t[n - 1][n - 1] = 'o';

		foreach (drow; -(n - 1)..n)
		{
			foreach (dcol; -(n - 1)..n)
			{
				if (t[drow + (n - 1)][dcol + (n - 1)] == 'x')
				{
					foreach (row; 0..n)
					{
						foreach (col; 0..n)
						{
							if (isValid (row -
							    drow, col - dcol)
							    && s[row - drow]
							    [col - dcol] ==
							    'x')
							{
								s[row - drow]
								    [col -
								    dcol] =
								    '.';
							}
						}
					}
				}
			}
		}

		bool ok = true;
		foreach (row; 0..n)
		{
			foreach (col; 0..n)
			{
				ok &= (s[row][col] != 'x');
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln ("%-(%s\n%)", t);
		}
		else
		{
			writeln ("NO");
		}
	}
}


Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.

The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.

Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).

on  codeforces
beta round is running
   a rustling of keys

how many gallons
of edo s rain did you drink
                                cuckoo

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
immutable long hashmod=10L^^18+3;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (g==a[l])?l:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~'\n', ptrs)==ptrs.length;}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------
void main()
{
	/*int n;
	loop:while(read(&n))
	{

	}*/
	auto a=new int[3];
	foreach(i;0..3)
	{
		auto s=readln.strip;
		a[i]=count!q{a=='a' || a=='o' || a=='e' || a=='u' || a=='i'}(s);
	}
	if(a==[5,7,5])writeln("YES");
	else writeln("NO");
}

module cf_78A;

import std.stdio;

bool isVowel(char letter) {
    return letter == 'a' || letter == 'e' || letter == 'i' ||
           letter == 'o' || letter == 'u';
}

void main() {
    immutable MAX_ROWS = 3;
    immutable ROW_SYLLABLES = [ 5, 7, 5 ];

    string row;

    bool haiku = true;
    for (int i = 0; i < MAX_ROWS; ++i) {
        readf("%s\n", &row);

        int syllables = 0;
        for (int j = 0; j < row.length; ++j) {
            if (isVowel(row[j])) {
                ++syllables;
            }
        }
        if (syllables != ROW_SYLLABLES[i]) {
            haiku = false;
        }
    }

    writeln(haiku? "YES": "NO");
}


Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of USB flash drives. The second line contains positive integer m (1 ≤ m ≤ 105) — the size of Sean's file. Each of the next n lines contains positive integer ai (1 ≤ ai ≤ 1000) — the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.

Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.

NoteIn the first example Sean needs only two USB flash drives — the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive — the first or the second.

//ahamat
import std.stdio,std.string,std.math,std.algorithm,std.range,
    std.bigint,std.complex,std.array,std.container,std.conv,
    std.typecons,std.functional,std.range,std.numeric,
    std.bitmanip,std.random,core.stdc.stdio;

void main(){
    int n,m;
    scanf("%d%d",&n,&m);
    int[] a=new int[n];
    foreach(ref e;a) scanf("%d",&e);
    a.sort().reverse();
    int x=0;
    foreach(ref usb;a){
        if(m>0) m-=usb,x++;
        else break;
    }
    writeln(x);
}


A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.

For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.

NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.

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;

void solve() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    int pos = -1;
    foreach (i; 0..N) if (S[i] == '8') {
        pos = i;
        break;
    }
    if (pos == -1 || N - pos < 11) {
        writeln("NO");
    } else {
        writeln("YES");
    }
}

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

//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 n,t;
    t=readln.chomp.to!int;
    string s;
    while(t--){
        n=readln.chomp.to!int;
        s=readln.strip;
        long k=s.indexOf('8');
        if(k>=0 && n-k>=11)
            writeln("YES");
        else writeln("NO");
    }
}

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

void main() {
  int nt = readln.strip.to!int;
  foreach (tid; 0 .. nt) {
    int n = readln.strip.to!int;
    auto s = readln.take (n).array;
    auto res = "NO";
    foreach (i; 0 .. n) {
      if (s[i] == '8' && (n - 1) - i >= 10) {
        res = "YES";
        break;
      }
    }
    writeln (res);
  }
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	long t = read.to!long;
	foreach(q; 0 .. t){

		long n = read.to!long;
		string s = readln.chomp;

		bool f = 0;
		for(int i = 0; i < n - 10; i ++) if(s[i] == '8') f = 1;

		if(f) "YES".writeln;
		else "NO".writeln;

	}

}

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;
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;
	string[] ans;
	foreach (i; 0..T)
	{
		auto N = RD!int;
		auto s = RD!string;
		bool a;
		foreach (j; 0..N)
		{
			if (j > N - 11) break;

			if (s[j] == '8')
			{
				a = true;
				break;
			}
		}
		ans ~= a ? "YES" : "NO";
	}

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

module cf1167a;
import std.stdio;
import std.string : indexOf, strip;
import std.conv : to;
void main() {
	int n;
	char[] buf;
	readln(buf);
	n = buf.strip.to!int;
	debug writeln(n);
	foreach(i; 0..n) {
		int x;
		readln(buf);
		x = buf.strip.to!int;
		readln(buf);
		immutable eight = buf.indexOf('8');
		debug writeln(eight, " ", x);
		if (eight >= 0 && eight + 11 <= x) {
			writeln("YES");
		}else {
			writeln("NO");
		}
	}
}

//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 n,t;
    t=readln.chomp.to!int;
    string s;
    while(t--){
        n=readln.chomp.to!int;
        s=readln.strip;
        long k=s.indexOf('8');
        if(n>=11 && k>=0 && n-k+1>=10)
            writeln("YES");
        else writeln("NO");
    }
}

//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 n,t;
    t=readln.chomp.to!int;
    string s;
    while(t--){
        n=readln.chomp.to!int;
        s=readln.strip;
        long k=s.indexOf('8');
        if(n>=11 && k>=0 && n-k>=10)
            writeln("YES");
        else writeln("NO");
    }
}


Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition — determine the number of dangerous turns on the track.

The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track. The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≤ xi, yi ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1). It is guaranteed that:   the first straight section is directed to the north;  the southernmost (and if there are several, then the most western of among them) point of the track is the first point;  the last point coincides with the first one (i.e., the start position);  any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point);  no pair of points (except for the first and last one) is the same;  no two adjacent straight sections are directed in the same direction or in opposite directions.

Print a single integer — the number of dangerous turns on the track.

NoteThe first sample corresponds to the picture:  The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.

import std.stdio;
import std.typecons;

void main()
{
    int n;
    Tuple!(int, int)[] points;

    readf("%d", &n);
    points = new Tuple!(int, int)[n + 2];
    for (int i = 0; i < n + 1; i++) {
        readf(" %d %d", &points[i][0], &points[i][1]);
    }
    points[n + 1] = points[1];

    int result = 0;
    for (int i = 1; i <= n; i++) {
        Tuple!(int, int) d[2];

        d[0][0] = points[i][0] - points[i - 1][0];
        d[0][1] = points[i][1] - points[i - 1][1];
        d[1][0] = points[i + 1][0] - points[i][0];
        d[1][1] = points[i + 1][1] - points[i][1];

        if (d[0][0] * d[1][1] - d[1][0] * d[0][1] > 0) {
            result++;
        }
    }

    writef("%d\n", result);
}

import std.stdio;

void main()
{
    int curvas, curvasPerigosas;
    int[1001] x;
    int[1001] y;

    readf(" %s ", &curvas);
    for(int i = 0; i <= curvas; ++i)
    {
        readf(" %s %s", &x[i], &y[i]);
    }

    for (int i = 1; i < curvas; ++i)
    {
        if (y[i] - y[i - 1] > 0 && x[i + 1] - x[i] < 0
        || x[i] - x[i - 1] > 0 && y[i + 1] - y[i] > 0
        || y[i] - y[i - 1] < 0 && x[i + 1] - x[i] > 0
        || x[i] - x[i - 1] < 0 && y[i + 1] - y[i] < 0)
            ++curvasPerigosas;
    }

    writeln(curvasPerigosas);
}

import std.stdio;

void main()
{
    int curvas, curvasPerigosas;
    int[1001] x;
    int[1001] y;

    readf(" %s ", &curvas);
    readf(" %s %s", &x[0], &y[0]);
    for(int i = 1; i <= curvas; ++i)
    {
        readf(" %s %s", &x[i], &y[i]);
        if (y[i] - y[i - 1] > 0 && x[i + 1] - x[i] < 0
        || x[i] - x[i - 1] > 0 && y[i + 1] - y[i] > 0
        || y[i] - y[i - 1] < 0 && x[i + 1] - x[i] > 0
        || x[i] - x[i - 1] < 0 && y[i + 1] - y[i] < 0)
            ++curvasPerigosas;
    }

    writeln(curvasPerigosas);
}


On the board, Bob wrote $$$n$$$ positive integers in base $$$10$$$ with sum $$$s$$$ (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-$$$11$$$ integers and adds them up (in base $$$11$$$).What numbers should Bob write on the board, so Alice's sum is as large as possible?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains two integers $$$s$$$ and $$$n$$$ ($$$1 \leq s \leq 10^9$$$; $$$1 \leq n \leq \min(100, s)$$$) — the sum and amount of numbers on the board, respectively. Numbers $$$s$$$ and $$$n$$$ are given in decimal notation (base $$$10$$$).

For each test case, output $$$n$$$ positive integers — the numbers Bob should write on the board, so Alice's sum is as large as possible. If there are multiple answers, print any of them.

NoteIn the first test case, $$$70_{10} + 27_{10} = 97_{10}$$$, and Alice's sum is $$$$$$70_{11} + 27_{11} = 97_{11} = 9 \cdot 11 + 7 = 106_{10}.$$$$$$ (Here $$$x_b$$$ represents the number $$$x$$$ in base $$$b$$$.) It can be shown that it is impossible for Alice to get a larger sum than $$$106_{10}$$$.In the second test case, Bob can only write a single number on the board, so he must write $$$17$$$.In the third test case, $$$3_{10} + 4_{10} + 100_{10} + 4_{10} = 111_{10}$$$, and Alice's sum is $$$$$$3_{11} + 4_{11} + 100_{11} + 4_{11} = 110_{11} = 1 \cdot 11^2 + 1 \cdot 11 = 132_{10}.$$$$$$ It can be shown that it is impossible for Alice to get a larger sum than $$$132_{10}$$$.

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long s, n;
    readf!" %d %d "(s, n);
    long[] ans;
    auto numpool = redBlackTree!("a<b", true, long)();
    long mul = 1;
    while (s > 0) {
      long digit = s % 10;
      foreach (i ; 0 .. digit)
        numpool.insert(mul);
      s /= 10;
      mul *= 10;
    }
    while (true) {
      if (n == 1) {
        long final_num = 0;
        while (!numpool.empty) {
          final_num += numpool.front;
          numpool.removeFront;
        }
        ans ~= final_num;
        break;
      }
      if (n <= numpool.length || numpool.front == 1) {
        ans ~= numpool.front;
        numpool.removeFront;
        n--;
        continue;
      }
      long tmp = numpool.front;
      numpool.removeFront;
      assert(tmp > 0 && tmp % 10 == 0);
      foreach (i ; 0 .. 10)
        numpool.insert(tmp / 10);
    }
    writeln(ans.map!text.joiner(" "));
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto a = new int[](s.length);
		foreach (i; 0..s.length)
			a[i] = s[i]-'0';

		long cnt = a.sum;
		while (n > cnt)
		{
			int p = cast(int)a.length-2;
			while (a[p] == 0)
				--p;
			--a[p];
			a[p+1] += 10;
			cnt += 9;
		}

		(){
		foreach (i; 0..a.length)
		{
			foreach (j; 0..a[i])
			{
				ans[ti] ~= 10^^(a.length-i-1);
				--a[i];
				if (ans[ti].length == n) return;
			}
		}}();
		foreach (i; 0..a.length)
		{
			foreach (j; 0..a[i])
			{
				ans[ti][j%n] += 10^^(a.length-i-1);
			}
		}
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

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

bool solve(long s, long n, ref long[] a)
{
  long[] ans;
  foreach (i ; 0 .. n - 1) {
    ans ~= 1;
  }
  if (s - (n - 1) <= 0)
    return false;

  ans ~= s - (n - 1);
  if (ans.length > 1 && ans.back >= 10) {
    ans.front += ans.back % 10;
    ans.back -= ans.back % 10;
  }
  a = ans;
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long s, n;
    readf!" %d %d "(s, n);
    long[] best_a;
    long best_div = 1;
    solve(s, n, best_a);
    long div = 10;
    while (s / div * div == s) {
      long[] a;
      if (solve(s / div, n, a)) {
        best_a = a;
        best_div = div;
      }
      div *= 10;
    }
    writeln(best_a.map!(x => (x * best_div).text).joiner(" "));
/*
    long[] ans;
    foreach (i ; 0 .. n - 1) {
      ans ~= 1;
    }
    ans ~= s - (n - 1);
    if (ans.length > 1 && ans.back >= 10) {
      ans.front += ans.back % 10;
      ans.back -= ans.back % 10;
    }
    writeln(ans.map!text.joiner(" "));
*/
  }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long s, n;
    readf!" %d %d "(s, n);
    long[] ans;
    foreach (i ; 0 .. n - 1) {
      ans ~= 1;
    }
    ans ~= s - (n - 1);
    if (ans.length > 1 && ans.back >= 10) {
      ans.front += ans.back % 10;
      ans.back -= ans.back % 10;
    }
    writeln(ans.map!text.joiner(" "));
  }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long s, n;
    readf!" %d %d "(s, n);
    long[] ans;
    foreach (i ; 0 .. n - 1) {
      ans ~= 1;
    }
    ans ~= s - (n - 1);
    if (ans.length > 1) {
      ans.front += ans.back % 10;
      ans.back -= ans.back % 10;
    }
    writeln(ans.map!text.joiner(" "));
  }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long s, n;
    readf!" %d %d "(s, n);
    long[] ans;
    foreach (i ; 0 .. n - 1) {
      ans ~= 1;
    }
    ans ~= s - (n - 1);
    ans.front += ans.back % 10;
    ans.back -= ans.back % 10;
    writeln(ans.map!text.joiner(" "));
  }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long s, n;
    readf!" %d %d "(s, n);
    long[] ans;
    foreach (i ; 0 .. n - 1) {
      ans ~= 1;
    }
    ans ~= s - (n - 1);
    writeln(ans.map!text.joiner(" "));
  }
}