Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.

The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.  Each of the next n lines contains xi (0 ≤ xi ≤ m) — the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≤ yij ≤ m) — the numbers of these bulbs.

If it's possible to turn on all m bulbs print "YES", otherwise print "NO".

NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.

import std.algorithm, std.range, std.stdio;
void main () {
	int n, m;
	readf (" %s %s ", &n, &m);
	int [string] b;
	n.iota.each !(_ => readln.split.drop (1).each !(x => b[x]++));
	writeln (b.length == m ? "YES" : "NO");
}

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

void main ()
{
	int n, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		int [] [] a;
		foreach (i; 0..n)
		{
			a ~= readln.split.drop (1).map !(to !(int)).array;
		}
		writeln (m.iota.map !(q{a + 1})
		    .all !(x => a.any !(b => b.canFind (x))) ? "YES" : "NO");
	}
}

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

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    int[] bulbs = new int[m];
    foreach (i; 0..n) {
        int[] buttons = readln.chomp.split.map!(to!int).array;
        foreach (e; buttons[1..$]) {
            bulbs[e - 1]++;
        }
    }

    if (bulbs.all) {
        writeln("YES");
    } else {
        writeln("NO");
    }
}

import std.stdio;
int main()
{
	int a=0;
	int b=0;
	readf(" %d", &a);
	readf(" %d", &b);
	bool[] m = new bool[b];
	for (int i=0; i<b; i++)
	{
		m[i]=false;
	}
	for (int i=0; i<a; i++)
	{
		int c=0;
		readf(" %d", &c);
		for (int j=0; j<c; j++)
		{
		    int d=0;
			readf(" %d", &d);
			m[d-1]=true;
		}
	}
	int count=0;
	for (int i=0; i<b; i++)
	{
		if (m[i]==false)
		{
			count=count+1;
		}
	}
	if (count==0)
	{
		writeln("YES");
	}
	else
	{
		writeln("NO");
	}
	return 0;
}

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

void main ()
{
	int n, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		int [] [] a;
		foreach (i; 0..m)
		{
			a ~= readln.split.drop (1).map !(to !(int)).array;
		}
		writeln (n.iota.map !(q{a + 1})
		    .all !(x => a.any !(b => b.canFind (x))) ? "YES" : "NO");
	}
}

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

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    int[] bulbs = new int[m];
    foreach (i; 0..n) {
        int[] buttons = readln.chomp.split.map!(to!int).array;
        foreach (e; buttons) {
            bulbs[e - 1]++;
        }
    }

    if (bulbs.all) {
        writeln("YES");
    } else {
        writeln("NO");
    }
}


The presidential election is coming in Bearland next year! Everybody is so excited about this!So far, there are three candidates, Alice, Bob, and Charlie. There are n citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, each of n citizens will choose one of six orders of preference between Alice, Bob and Charlie uniformly at random, independently from other voters.The government of Bearland has devised a function to help determine the outcome of the election given the voters preferences. More specifically, the function is  (takes n boolean numbers and returns a boolean number). The function also obeys the following property: f(1 - x1, 1 - x2, ..., 1 - xn) = 1 - f(x1, x2, ..., xn).Three rounds will be run between each pair of candidates: Alice and Bob, Bob and Charlie, Charlie and Alice. In each round, xi will be equal to 1, if i-th citizen prefers the first candidate to second in this round, and 0 otherwise. After this, y = f(x1, x2, ..., xn) will be calculated. If y = 1, the first candidate will be declared as winner in this round. If y = 0, the second will be the winner, respectively.Define the probability that there is a candidate who won two rounds as p. p·6n is always an integer. Print the value of this integer modulo 109 + 7 = 1 000 000 007.

The first line contains one integer n (1 ≤ n ≤ 20). The next line contains a string of length 2n of zeros and ones, representing function f. Let bk(x) the k-th bit in binary representation of x, i-th (0-based) digit of this string shows the return value of f(b1(i), b2(i), ..., bn(i)). It is guaranteed that f(1 - x1, 1 - x2, ..., 1 - xn) = 1 - f(x1, x2, ..., xn) for any values of x1, x2, ldots, xn.

Output one integer — answer to the problem.

NoteIn first sample, result is always fully determined by the first voter. In other words, f(x1, x2, x3) = x1. Thus, any no matter what happens, there will be a candidate who won two rounds (more specifically, the candidate who is at the top of voter 1's preference list), so p = 1, and we print 1·63 = 216.

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const A = readToken();

      auto fs = new Mint[][](2, 1 << N);
      foreach (s; 0 .. 2) {
        foreach (h; 0 .. 1 << N) {
          if (A[h] - '0' == s) {
            fs[s][h] = 1;
          }
        }
        debug {
          writefln("fs[%s] = %s", s, fs[s]);
        }
      }

      foreach (s; 0 .. 2) {
        foreach (i; 0 .. N) {
          foreach (h; 0 .. 1 << N) {
            if (!(h & 1 << i)) {
              const tmp = fs[s][h] - fs[s][h | 1 << i];
              fs[s][h] += fs[s][h | 1 << i];
              fs[s][h | 1 << i] = tmp;
            }
          }
        }
      }
      auto gs = new Mint[1 << N];
      foreach (h; 0 .. 1 << N) {
        gs[h] = fs[0][h] * fs[1][h];
      }
      foreach (i; 0 .. N) {
        foreach (h; 0 .. 1 << N) {
          if (!(h & 1 << i)) {
            const tmp = gs[h] - gs[h | 1 << i];
            gs[h] += gs[h | 1 << i];
            gs[h | 1 << i] = tmp;
          }
        }
      }
      gs[] *= Mint(1 << N).inv;
      debug {
        writeln("gs = ", gs);
      }

      Mint ans;
      foreach (h; 0 .. 1 << N) {
        ans += gs[h] * (1 << popcnt(h));
      }
      ans *= 3;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

For each test case, output on a separate line:    "YES" if $$$n$$$ has an odd divisor, greater than one;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

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

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

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        long N; get(N);
        while (N % 2 == 0) N /= 2;
        writeln(N == 1 ? "NO" : "YES");
    }
}

// Vicfred
// https://codeforces.com/contest/1475/problem/A
// math
import std.stdio;

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

while(t--) {
    long n;
    readf("%s\n", &n);

    while(n % 2 == 0) {
        n /= 2;
    }

    if(n > 1)
        "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.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		while (n % 2 == 0)
		{
			n /= 2;
		}
		ans[ti] = n > 1;
	}

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

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

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


Tavas lives in Kansas. Kansas has n cities numbered from 1 to n connected with m bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities.Tavas invented a game and called it "Dashti". He wants to play Dashti with his girlfriends, Nafas.In this game, they assign an arbitrary integer value to each city of Kansas. The value of i-th city equals to pi.During the game, Tavas is in city s and Nafas is in city t. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer x and his/her score increases by the sum of values of all cities with (shortest) distance no more than x from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero.There is an additional rule: the player must choose x such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule.The game ends when nobody can make a move.A player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points.  If Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers.They're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends.

The first line of input contains two integers n and m (2 ≤ n ≤ 2000, n - 1 ≤ m ≤ 105). The second line of input contains two integers s and t (1 ≤ s, t ≤ n, s ≠ t). The next line contains n integers p1, p2, ..., pn separated by spaces (|pi| ≤ 109). The next m lines contain the roads. Each line contains three integers v, u, w and it means that there's an road with length w between cities v and u (1 ≤ u, v ≤ n and 0 ≤ w ≤ 109). The road may lead from the city to itself, there may be several roads between each pair of cities.

If Tavas wins, print "Break a heart". If Nafas wins print "Cry" and if nobody wins (i. e. the game ended with draw) print "Flowers".

// Code By H~$~C

module main;

import core.stdc.stdlib, core.stdc.string;
import std.stdio, std.array, std.string, std.math, std.uni;
import std.algorithm, std.range, std.random, std.container;
import std.conv, std.typecons, std.functional;

immutable Maxn = 4005;

int n, m, st, ed;
int[Maxn] p;
Tuple!(int, long)[][Maxn] g;
long[Maxn] dists, distt;
long[][Maxn] sum;
int[][Maxn] cnt;
long[][Maxn] dp1, dp2;
Tuple!(Tuple!(long, int), Tuple!(long, int))[Maxn] suf1, suf2;

void dijkstra(int st, ref long[Maxn] dist) {
  Tuple!(long, int)[] fucking = new Tuple!(long, int)[Maxn * 20];
  BinaryHeap!(Tuple!(long, int)[]) pq = BinaryHeap!(Tuple!(long, int)[])(fucking, 0);
  pq.insert(tuple(0L, st));
  dist[] = lnf;
  dist[st] = 0;
  while (!pq.empty) {
    auto pr = pq.front; pq.popFront;
    int u = pr[1];
    long d = -pr[0];
    if (d != dist[u]) continue;
    foreach(fuck; g[u]) {
      int v = fuck[0];
      long w = fuck[1];
      if (dist[v] > d + w) {
        dist[v] = d + w;
        pq.insert(tuple(-dist[v], v));
      }
    }
  }
}

// FIXME
void solve(in int testcase) {
  n.read, m.read, st.read, ed.read;
  p[1 .. n + 1] = readarray!int;
  foreach(i; 1 .. m + 1) {
    int u, v; long w;
    u.read, v.read, w.read;
    g[u] ~= tuple(v, w);
    g[v] ~= tuple(u, w);
  }
  dijkstra(st, dists);
  dijkstra(ed, distt);

  long[] vec;
  foreach(i; 1 .. n + 1)
    vec ~= [dists[i], distt[i]];
  vec = vec.sort.unique.array;
  int len = cast(int)vec.length + 1;
  foreach(i; 0 .. vec.length + 2)
    dp1[i].length = dp2[i].length = sum[i].length = cnt[i].length = len + 1;
  foreach(i; 1 .. n + 1) {
    dists[i] = vec.lower_bound(dists[i]);
    distt[i] = vec.lower_bound(distt[i]);
    cnt[cast(int)dists[i]][cast(int)distt[i]]++;
    sum[cast(int)dists[i]][cast(int)distt[i]] += p[i];
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      cnt[i][j] += cnt[i][j + 1] + cnt[i + 1][j] - cnt[i + 1][j + 1];
      sum[i][j] += sum[i][j + 1] + sum[i + 1][j] - sum[i + 1][j + 1];
    }
  }

  void update_answer(ref Tuple!(Tuple!(long, int), Tuple!(long, int)) x, Tuple!(long, int) y) {
    if (y < x[0]) swap(y, x[0]);
    if (y[1] == x[0][1]) return ;
    x[1] = min(x[1], y);
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      if (!cnt[i][j]) continue;
      dp1[i][j] = sum[i][j] - (cnt[i][j] != suf1[j][0][1] ? suf1[j][0] : suf1[j][1])[0];
      dp2[i][j] = sum[i][j] - (cnt[i][j] != suf2[i][0][1] ? suf2[i][0] : suf2[i][1])[0];
      update_answer(suf1[j], tuple(dp2[i][j], cnt[i][j]));
      update_answer(suf2[i], tuple(dp1[i][j], cnt[i][j]));
    }
  }

  long ans1 = dp1[0][0], ans2 = sum[0][0] - dp1[0][0];
  if (ans1 == ans2) "Flowers".writeln;
  else if (ans1 < ans2) "Cry".writeln;
  else "Break a heart".writeln;
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

// Code By H~$~C

module main;

import core.stdc.stdlib, core.stdc.string;
import std.stdio, std.array, std.string, std.math, std.uni;
import std.algorithm, std.range, std.random, std.container;
import std.conv, std.typecons, std.functional;

immutable Maxn = 4005;

int n, m, st, ed;
int[Maxn] p;
Tuple!(int, long)[][Maxn] g;
long[Maxn] dists, distt;
long[][Maxn] sum;
int[][Maxn] cnt;
long[][Maxn] dp1, dp2;
Tuple!(Tuple!(long, int), Tuple!(long, int))[Maxn] suf1, suf2;

void dijkstra(int st, ref long[Maxn] dist) {
  set!(Tuple!(long, int)) pq = Set(tuple!(long, int)(lnf, 0));
  pq.insert(tuple(0L, st));
  dist[] = lnf;
  dist[st] = 0;
  while (pq.length > 1) {
    auto pr = pq.front; pq.removeFront;
    int u = pr[1];
    long d = pr[0];
    if (d != dist[u]) continue;
    foreach(fuck; g[u]) {
      int v = fuck[0];
      long w = fuck[1];
      if (dist[v] > d + w) {
        dist[v] = d + w;
        pq.insert(tuple(dist[v], v));
      }
    }
  }
}

// FIXME
void solve(in int testcase) {
  n.read, m.read, st.read, ed.read;
  p[1 .. n + 1] = readarray!int;
  foreach(i; 1 .. m + 1) {
    int u, v; long w;
    u.read, v.read, w.read;
    g[u] ~= tuple(v, w);
    g[v] ~= tuple(u, w);
  }
  dijkstra(st, dists);
  dijkstra(ed, distt);

  long[] vec;
  foreach(i; 1 .. n + 1)
    vec ~= [dists[i], distt[i]];
  vec = vec.sort.unique.array;
  int len = cast(int)vec.length + 1;
  foreach(i; 0 .. vec.length + 2)
    dp1[i].length = dp2[i].length = sum[i].length = cnt[i].length = len + 1;
  foreach(i; 1 .. n + 1) {
    dists[i] = vec.lower_bound(dists[i]);
    distt[i] = vec.lower_bound(distt[i]);
    cnt[cast(int)dists[i]][cast(int)distt[i]]++;
    sum[cast(int)dists[i]][cast(int)distt[i]] += p[i];
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      cnt[i][j] += cnt[i][j + 1] + cnt[i + 1][j] - cnt[i + 1][j + 1];
      sum[i][j] += sum[i][j + 1] + sum[i + 1][j] - sum[i + 1][j + 1];
    }
  }

  void update_answer(ref Tuple!(Tuple!(long, int), Tuple!(long, int)) x, Tuple!(long, int) y) {
    if (y < x[0]) swap(y, x[0]);
    if (y[1] == x[0][1]) return ;
    x[1] = min(x[1], y);
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      if (!cnt[i][j]) continue;
      dp1[i][j] = sum[i][j] - (cnt[i][j] != suf1[j][0][1] ? suf1[j][0] : suf1[j][1])[0];
      dp2[i][j] = sum[i][j] - (cnt[i][j] != suf2[i][0][1] ? suf2[i][0] : suf2[i][1])[0];
      update_answer(suf1[j], tuple(dp2[i][j], cnt[i][j]));
      update_answer(suf2[i], tuple(dp1[i][j], cnt[i][j]));
    }
  }

  long ans1 = dp1[0][0], ans2 = sum[0][0] - dp1[0][0];
  if (ans1 == ans2) "Flowers".writeln;
  else if (ans1 < ans2) "Cry".writeln;
  else "Break a heart".writeln;
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;
alias set = RedBlackTree;
alias Set = redBlackTree;
alias priority_queue(T, alias less = "a < b") = BinaryHeap!(T[], less);
alias min_heap(T) = priority_queue!(T, "a > b");
alias max_heap(T) = priority_queue!(T, "a < b");

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

// Code By H~$~C

module main;

import core.stdc.stdlib, core.stdc.string;
import std.stdio, std.array, std.string, std.math, std.uni;
import std.algorithm, std.range, std.random, std.container;
import std.conv, std.typecons, std.functional;

immutable Maxn = 4005;

int n, m, st, ed;
int[Maxn] p;
Tuple!(int, long)[][Maxn] g;
long[Maxn] dists, distt;
long[][Maxn] sum;
int[][Maxn] cnt;
long[][Maxn] dp1, dp2;
Tuple!(Tuple!(long, int), Tuple!(long, int))[Maxn] suf1, suf2;

void dijkstra(int st, ref long[Maxn] dist) {
  set!(Tuple!(long, int)) pq = Set(tuple!(long, int)(-lnf - 1, 0));
  pq.insert(tuple(0L, st));
  dist[] = lnf;
  dist[st] = 0;
  while (pq.length > 1) {
    auto pr = pq.front; pq.removeFront;
    int u = pr[1];
    long d = pr[0];
    if (d != dist[u]) continue;
    foreach(fuck; g[u]) {
      int v = fuck[0];
      long w = fuck[1];
      if (dist[v] > d + w) {
        dist[v] = d + w;
        pq.insert(tuple(dist[v], v));
      }
    }
  }
}

// FIXME
void solve(in int testcase) {
  n.read, m.read, st.read, ed.read;
  p[1 .. n + 1] = readarray!int;
  foreach(i; 1 .. m + 1) {
    int u, v; long w;
    u.read, v.read, w.read;
    g[u] ~= tuple(v, w);
    g[v] ~= tuple(u, w);
  }
  dijkstra(st, dists);
  dijkstra(ed, distt);

  long[] vec;
  foreach(i; 1 .. n + 1)
    vec ~= [dists[i], distt[i]];
  vec = vec.sort.unique.array;
  int len = cast(int)vec.length + 1;
  foreach(i; 0 .. vec.length + 2)
    dp1[i].length = dp2[i].length = sum[i].length = cnt[i].length = len + 1;
  foreach(i; 1 .. n + 1) {
    dists[i] = vec.lower_bound(dists[i]);
    distt[i] = vec.lower_bound(distt[i]);
    cnt[cast(int)dists[i]][cast(int)distt[i]]++;
    sum[cast(int)dists[i]][cast(int)distt[i]] += p[i];
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      cnt[i][j] += cnt[i][j + 1] + cnt[i + 1][j] - cnt[i + 1][j + 1];
      sum[i][j] += sum[i][j + 1] + sum[i + 1][j] - sum[i + 1][j + 1];
    }
  }

  void update_answer(ref Tuple!(Tuple!(long, int), Tuple!(long, int)) x, Tuple!(long, int) y) {
    if (y < x[0]) swap(y, x[0]);
    if (y[1] == x[0][1]) return ;
    x[1] = min(x[1], y);
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      if (!cnt[i][j]) continue;
      dp1[i][j] = sum[i][j] - (cnt[i][j] != suf1[j][0][1] ? suf1[j][0] : suf1[j][1])[0];
      dp2[i][j] = sum[i][j] - (cnt[i][j] != suf2[i][0][1] ? suf2[i][0] : suf2[i][1])[0];
      update_answer(suf1[j], tuple(dp2[i][j], cnt[i][j]));
      update_answer(suf2[i], tuple(dp1[i][j], cnt[i][j]));
    }
  }

  long ans1 = dp1[0][0], ans2 = sum[0][0] - dp1[0][0];
  if (ans1 == ans2) "Flowers".writeln;
  else if (ans1 < ans2) "Cry".writeln;
  else "Break a heart".writeln;
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;
alias set = RedBlackTree;
alias Set = redBlackTree;
alias priority_queue(T, alias less = "a < b") = BinaryHeap!(T[], less);
alias min_heap(T) = priority_queue!(T, "a > b");
alias max_heap(T) = priority_queue!(T, "a < b");

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

// Code By H~$~C

module main;

import core.stdc.stdlib, core.stdc.string;
import std.stdio, std.array, std.string, std.math, std.uni;
import std.algorithm, std.range, std.random, std.container;
import std.conv, std.typecons, std.functional;

immutable Maxn = 4005;

int n, m, st, ed;
int[Maxn] p;
Tuple!(int, long)[][Maxn] g;
long[Maxn] dists, distt;
long[][Maxn] sum;
int[][Maxn] cnt;
long[][Maxn] dp1, dp2;
Tuple!(Tuple!(long, int), Tuple!(long, int))[Maxn] suf1, suf2;

void dijkstra(int st, ref long[Maxn] dist) {
  set!(Tuple!(long, int)) pq = Set(tuple!(long, int)(-1, 0));
  pq.insert(tuple(0L, st));
  dist[] = lnf;
  dist[st] = 0;
  while (pq.length > 1) {
    auto pr = pq.front; pq.removeFront;
    int u = pr[1];
    long d = pr[0];
    if (d != dist[u]) continue;
    foreach(fuck; g[u]) {
      int v = fuck[0];
      long w = fuck[1];
      if (dist[v] > d + w) {
        dist[v] = d + w;
        pq.insert(tuple(dist[v], v));
      }
    }
  }
}

// FIXME
void solve(in int testcase) {
  n.read, m.read, st.read, ed.read;
  p[1 .. n + 1] = readarray!int;
  foreach(i; 1 .. m + 1) {
    int u, v; long w;
    u.read, v.read, w.read;
    g[u] ~= tuple(v, w);
    g[v] ~= tuple(u, w);
  }
  dijkstra(st, dists);
  dijkstra(ed, distt);

  long[] vec;
  foreach(i; 1 .. n + 1)
    vec ~= [dists[i], distt[i]];
  vec = vec.sort.unique.array;
  int len = cast(int)vec.length + 1;
  foreach(i; 0 .. vec.length + 2)
    dp1[i].length = dp2[i].length = sum[i].length = cnt[i].length = len + 1;
  foreach(i; 1 .. n + 1) {
    dists[i] = vec.lower_bound(dists[i]);
    distt[i] = vec.lower_bound(distt[i]);
    cnt[cast(int)dists[i]][cast(int)distt[i]]++;
    sum[cast(int)dists[i]][cast(int)distt[i]] += p[i];
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      cnt[i][j] += cnt[i][j + 1] + cnt[i + 1][j] - cnt[i + 1][j + 1];
      sum[i][j] += sum[i][j + 1] + sum[i + 1][j] - sum[i + 1][j + 1];
    }
  }

  void update_answer(ref Tuple!(Tuple!(long, int), Tuple!(long, int)) x, Tuple!(long, int) y) {
    if (y < x[0]) swap(y, x[0]);
    if (y[1] == x[0][1]) return ;
    x[1] = min(x[1], y);
  }
  for (int i = len - 1; i >= 0; --i) {
    for (int j = len - 1; j >= 0; --j) {
      if (!cnt[i][j]) continue;
      dp1[i][j] = sum[i][j] - (cnt[i][j] != suf1[j][0][1] ? suf1[j][0] : suf1[j][1])[0];
      dp2[i][j] = sum[i][j] - (cnt[i][j] != suf2[i][0][1] ? suf2[i][0] : suf2[i][1])[0];
      update_answer(suf1[j], tuple(dp2[i][j], cnt[i][j]));
      update_answer(suf2[i], tuple(dp1[i][j], cnt[i][j]));
    }
  }

  long ans1 = dp1[0][0], ans2 = sum[0][0] - dp1[0][0];
  if (ans1 == ans2) "Flowers".writeln;
  else if (ans1 < ans2) "Cry".writeln;
  else "Break a heart".writeln;
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;
alias set = RedBlackTree;
alias Set = redBlackTree;
alias priority_queue(T, alias less = "a < b") = BinaryHeap!(T[], less);
alias min_heap(T) = priority_queue!(T, "a > b");
alias max_heap(T) = priority_queue!(T, "a < b");

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}


There are $$$n$$$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.We want to plan a trip for every evening of $$$m$$$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:   Either this person does not go on the trip,  Or at least $$$k$$$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $$$a$$$ and $$$b$$$ are friends and $$$b$$$ and $$$c$$$ are friends, it does not necessarily imply that $$$a$$$ and $$$c$$$ are friends.For each day, find the maximum number of people that can go on the trip on that day.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$$$, $$$1 \le k < n$$$) — the number of people, the number of days and the number of friends each person on the trip should have in the group. The $$$i$$$-th ($$$1 \leq i \leq m$$$) of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1\leq x, y\leq n$$$, $$$x\ne y$$$), meaning that persons $$$x$$$ and $$$y$$$ become friends on the morning of day $$$i$$$. It is guaranteed that $$$x$$$ and $$$y$$$ were not friends before.

Print exactly $$$m$$$ lines, where the $$$i$$$-th of them ($$$1\leq i\leq m$$$) contains the maximum number of people that can go on the trip on the evening of the day $$$i$$$.

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, std.bitmanip;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto K = s[2];
    auto G = new bool[int][](N);
    auto D = new int[](N);
    auto Q = new Tuple!(int, int)[](M);
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        G[s[0]-1][s[1]-1] = true;
        G[s[1]-1][s[0]-1] = true;
        D[s[0]-1] += 1;
        D[s[1]-1] += 1;
        Q[i] = tuple(s[0]-1, s[1]-1);
    }

    int sm = N;
    auto valid = new bool[](N);
    fill(valid, true);

    void dfs(int n) {
        if (!valid[n]) return;
        valid[n] = false;
        sm -= 1;
        foreach (m; G[n].keys) {
            if (!G[n][m]) continue;
            D[m] -= 1;
            G[n][m] = false;
            G[m][n] = false;
            if (valid[m] && D[m] < K) {
                dfs(m);
            }
        }
    }

    foreach (i; 0..N) {
        if (D[i] < K) dfs(i);
    }

    int[] ans;
    foreach_reverse (q; Q) {
        ans ~= sm;
        int u = q[0];
        int v = q[1];
        if (!valid[u] || !valid[v]) continue;
        D[u] -= 1;
        D[v] -= 1;
        G[u][v] = false;
        G[v][u] = false;
        if (valid[u] && D[u] < K) dfs(u);
        if (valid[v] && D[v] < K) dfs(v);
    }

    ans.reverse();
    ans.each!writeln;
}

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		alias Edge = Tuple !(int, q{u}, int, q{v});
		auto e = new Edge [m];
		auto d = new int [n];
		auto a = new bool [int] [n];
		foreach (ref edge; e)
		{
			readf (" %s %s", &edge.u, &edge.v);
			edge.u -= 1;
			edge.v -= 1;
			d[edge.u] += 1;
			d[edge.v] += 1;
			a[edge.u][edge.v] = true;
			a[edge.v][edge.u] = true;
		}
		debug {writeln (a);}
		debug {writeln (d);}
		debug {writeln (e);}

		alias Record = Tuple !(int, q{deg}, int, q{num});
		auto t = redBlackTree !(Record);
		foreach (i; 0..n)
		{
			t.insert (Record (d[i], i));
		}

		void changeDegree (int v, int delta)
		{
			auto cur = Record (d[v], v);
			auto r = t.equalRange (cur);
			if (r.empty)
			{
				d[v] += delta;
			}
			else
			{
				t.removeKey (cur);
				d[v] += delta;
				cur.deg = d[v];
				t.insert (cur);
			}
		}

		void removeVertex (int v)
		{
			debug {writeln (v, ": ", a[v].length, " ", d[v]);}
			assert (a[v].length == d[v]);
			foreach (u, _; a[v])
			{
				changeDegree (u, -1);
				a[u].remove (v);
			}
			a[v] = null;
			t.removeKey (Record (d[v], v));
			changeDegree (v, -d[v]);
		}

		auto ans = new int [m];
		foreach_reverse (int j, ref edge; e)
		{
			while (!t.empty && t.front.deg < k)
			{
				debug {writeln ("step ", j, ": ", t);}
				removeVertex (t.front.num);
			}
			debug {writeln ("step ", j, ": ", t);}
			ans[j] = t.length.to !(int);
			if (edge.v in a[edge.u])
			{
				changeDegree (edge.u, -1);
				changeDegree (edge.v, -1);
				a[edge.u].remove (edge.v);
				a[edge.v].remove (edge.u);
				debug {writeln ("step ", j, ": ", t);}
			}
		}

		foreach (ref c; ans)
		{
			writeln (c);
		}
	}
}


You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column.You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to:  (i - 1, j + 1) — only if i > 1,  (i, j + 1), or  (i + 1, j + 1) — only if i < 3. However, there are n obstacles blocking your path. k-th obstacle is denoted by three integers ak, lk and rk, and it forbids entering any cell (ak, j) such that lk ≤ j ≤ rk.You have to calculate the number of different paths from (2, 1) to (2, m), and print it modulo 109 + 7.

The first line contains two integers n and m (1 ≤ n ≤ 104, 3 ≤ m ≤ 1018) — the number of obstacles and the number of columns in the matrix, respectively. Then n lines follow, each containing three integers ak, lk and rk (1 ≤ ak ≤ 3, 2 ≤ lk ≤ rk ≤ m - 1) denoting an obstacle blocking every cell (ak, j) such that lk ≤ j ≤ rk. Some cells may be blocked by multiple obstacles.

Print the number of different paths from (2, 1) to (2, m), taken modulo 109 + 7. If it is impossible to get from (2, 1) to (2, m), then the number of paths is 0.

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
alias matrix = long[3][3];
long[3] mult(long[3] a, matrix b)
{
	long[3] res;
	foreach (j; 0 .. 3)
	{
		foreach (k; 0 .. 3)
		{
			res[j] = (res[j] + a[k] * b[k][j]) % mod;
		}
	}
	return res;
}

matrix mult(matrix a, matrix b)
{
	matrix res;
	foreach (i; 0 .. 3)
	{
		foreach (j; 0 .. 3)
		{
			foreach (k; 0 .. 3)
			{
				res[i][j] = (res[i][j] + a[i][k] * b[k][j]) % mod;
			}
		}
	}
	return res;
}

matrix binpow(matrix b, long e)
{
	matrix res;
	foreach (i; 0 .. 3)
	{
		res[i][i] = 1;
	}
	while (e)
	{
		if (e & 1)
			res = mult(res, b);
		b = mult(b, b);
		e /= 2;
	}
	return res;
}

void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	long m;
	read(n, m);
	Tuple!(long, bool, int)[] v;
	foreach (i; 0 .. n)
	{
		int a;
		long l, r;
		read(a, l, r);
		a--;
		v ~= tuple(l, true, a);
		v ~= tuple(r + 1, false, a);
	}
	sort(v);
	v ~= tuple(m , false, 1);
	matrix base;
	int[3] z;
	foreach (i; 0 .. 3)
	{
		foreach (j; 0 .. 3)
		{
			base[i][j] = 1;
		}
	}
	base[0][2] = base[2][0] = 0;
	long[3] a;
	a[1] = 1;
	long pr = 1;
	int p = 0;
	matrix r = base;
	while (p < sz(v))
	{
		long cur = v[p][0];
		a = mult(a, binpow(r, cur  - pr));
		pr = cur ;
		while (p < sz(v) && v[p][0] == cur)
		{
			if (v[p][1])
				z[v[p][2]]++;
			else
				z[v[p][2]]--;
			p++;
		}
		foreach (i; 0 .. 3)
		{
			foreach (j; 0 .. 3)
			{
				if (z[i] > 0)
					r[i][j] = 0;
				else
					r[i][j] = base[i][j];
			}
		}
		debug writeln(a[1], ' ', z, ' ', a);
	}
	writeln(a[1]);
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
alias matrix = long[3][3];
long[3] mult(long[3] a, matrix b)
{
	long[3] res;
	foreach (j; 0 .. 3)
	{
		foreach (k; 0 .. 3)
		{
			res[j] = (res[j] + a[k] * b[k][j]) % mod;
		}
	}
	return res;
}

matrix mult(matrix a, matrix b)
{
	matrix res;
	foreach (i; 0 .. 3)
	{
		foreach (j; 0 .. 3)
		{
			foreach (k; 0 .. 3)
			{
				res[i][j] = (res[i][j] + a[i][k] * b[k][j]) % mod;
			}
		}
	}
	return res;
}

matrix binpow(matrix b, long e)
{
	matrix res;
	foreach (i; 0 .. 3)
	{
		res[i][i] = 1;
	}
	while (e)
	{
		if (e & 1)
			res = mult(res, b);
		b = mult(b, b);
		e /= 2;
	}
	return res;
}

void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	long m;
	read(n, m);
	Tuple!(long, bool, int)[] v;
	foreach (i; 0 .. n)
	{
		int a;
		long l, r;
		read(a, l, r);
		v ~= tuple(l, true, a);
		v ~= tuple(r + 1, false, a);
	}
	sort(v);
	v ~= tuple(m + 1, false, 1);
	matrix base;
	int[3] z;
	foreach (i; 0 .. 3)
	{
		foreach (j; 0 .. 3)
		{
			base[i][j] = 1;
		}
	}
	base[0][2] = base[2][0] = 0;
	long[3] a;
	a[1] = 1;
	long pr = 1;
	int p = 0;
	matrix r = base;
	while (p < sz(v))
	{
		long cur = v[p][0];
		a = mult(a, binpow(r, cur - 1 - pr));
		pr = cur - 1;
		while (p < sz(v) && v[p][0] == cur)
		{
			if (v[p][1])
				z[v[p][2]]++;
			else
				z[v[p][2]]--;
			p++;
		}
		foreach (i; 0 .. 3)
		{
			foreach (j; 0 .. 3)
			{
				if (z[i] > 0)
					r[i][j] = 0;
				else
					r[i][j] = base[i][j];
			}
		}
	}
	writeln(a[1]);
}


We start with a permutation $$$a_1, a_2, \ldots, a_n$$$ and with an empty array $$$b$$$. We apply the following operation $$$k$$$ times.On the $$$i$$$-th iteration, we select an index $$$t_i$$$ ($$$1 \le t_i \le n-i+1$$$), remove $$$a_{t_i}$$$ from the array, and append one of the numbers $$$a_{t_i-1}$$$ or $$$a_{t_i+1}$$$ (if $$$t_i-1$$$ or $$$t_i+1$$$ are within the array bounds) to the right end of the array $$$b$$$. Then we move elements $$$a_{t_i+1}, \ldots, a_n$$$ to the left in order to fill in the empty space.You are given the initial permutation $$$a_1, a_2, \ldots, a_n$$$ and the resulting array $$$b_1, b_2, \ldots, b_k$$$. All elements of an array $$$b$$$ are distinct. Calculate the number of possible sequences of indices $$$t_1, t_2, \ldots, t_k$$$ modulo $$$998\,244\,353$$$.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100\,000$$$), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers $$$n, k$$$ ($$$1 \le k < n \le 200\,000$$$): sizes of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$): elements of $$$a$$$. All elements of $$$a$$$ are distinct. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, \ldots, b_k$$$ ($$$1 \le b_i \le n$$$): elements of $$$b$$$. All elements of $$$b$$$ are distinct. The sum of all $$$n$$$ among all test cases is guaranteed to not exceed $$$200\,000$$$.

For each test case print one integer: the number of possible sequences modulo $$$998\,244\,353$$$.

Note$$$\require{cancel}$$$Let's denote as $$$a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$$$ an operation over an element with index $$$i$$$: removal of element $$$a_i$$$ from array $$$a$$$ and appending element $$$a_{i+1}$$$ to array $$$b$$$.In the first example test, the following two options can be used to produce the given array $$$b$$$:  $$$1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$$$; $$$(t_1, t_2, t_3) = (4, 3, 2)$$$;  $$$1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$$$; $$$(t_1, t_2, t_3) = (4, 1, 2)$$$. In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $$$4$$$, namely number $$$3$$$, which means that it couldn't be added to array $$$b$$$ on the second step.In the third example test, there are four options to achieve the given array $$$b$$$:  $$$1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$$$; $$$1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$$$; $$$1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$$$; $$$1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$$$;

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

immutable int mod = 998_244_353;
immutable int NA = -1;

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

		auto a = readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		auto next = new int [n];
		next[] = NA;
		auto prev = new int [n];
		prev[] = NA;
		foreach (i; 0..n - 1)
		{
			prev[a[i + 1]] = a[i];
			next[a[i]] = a[i + 1];
		}

		auto b = readln.splitter.map !(to !(int)).array;
		b[] -= 1;
		auto used = new bool [n];
		foreach (ref cur; b)
		{
			used[cur] = true;
		}

		int res = 1;
		foreach (i; 0..k)
		{
			int mult = 0;
			if (prev[b[i]] != NA && !used[prev[b[i]]])
			{
				mult += 1;
			}
			if (next[b[i]] != NA && !used[next[b[i]]])
			{
				mult += 1;
			}
			res = (res * mult) % mod;
			if (next[b[i]] != NA)
			{
				prev[next[b[i]]] = prev[b[i]];
			}
			if (prev[b[i]] != NA)
			{
				next[prev[b[i]]] = next[b[i]];
			}
			used[b[i]] = false;
		}
		writeln (res);
	}
}

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 MO = 998244353;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const K = readInt();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }
        auto B = new int[K];
        foreach (k; 0 .. K) {
          B[k] = readInt();
        }

        auto lef = new int[N + 1];
        auto rig = new int[N + 1];
        rig[0] = A[0];
        lef[A[0]] = 0;
        foreach (i; 0 .. N - 1) {
          rig[A[i]] = A[i + 1];
          lef[A[i + 1]] = A[i];
        }
        rig[A[N - 1]] = 0;
        lef[0] = A[N - 1];

        auto del = new bool[N + 1];
        del[0] = true;
        foreach (k; 0 .. K) {
          del[B[k]] = true;
        }

        long ans = 1;
        foreach (k; 0 .. K) {
          const l = lef[B[k]];
          const r = rig[B[k]];
          rig[l] = r;
          lef[r] = l;
          int num;
          if (!del[l]) ++num;
          if (!del[r]) ++num;
          (ans *= num) %= MO;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDA(-1);
		auto b = RDA(-1);

		auto need = new bool[](n);
		foreach (e; b)
		{
			need[e] = true;
		}

		auto pos = new int[](n);
		auto link = new int[][](n);
		foreach (int i; 0..n)
		{
			pos[a[i]] = i;
			link[i] = [i-1, i+1];
		}

		long tmp = 1;
		foreach (e; b)
		{
			auto p = pos[e];
			auto l = link[p][0];
			auto r = link[p][1];
			int cnt;
			if (l != -1)
			{
				if (!need[a[l]])
					++cnt;
				link[l][1] = r;
			}
			if (r != n)
			{
				if (!need[a[r]])
					++cnt;
				link[r][0] = l;
			}
			tmp.modm(cnt);
			need[e] = false;
		}
		ans[ti] = tmp;
	}

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


Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w":   "vvvv"  "vvvv"  "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows:  "vvvovvv"  "vvvovvv"  "vvvovvv"  "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov".

The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$.

Output a single integer, the wow factor of $$$s$$$.

NoteThe first example is explained in the legend.

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

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

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

    auto li = s.group.array;

    debug writeln(li);

    long ans = 0;
    auto m = li.length;
    long[] cnt = new long[m + 1];
    long lsm = 0, rsm = 0;
    foreach (tok; li) {
        if (tok[0] == 'v') {
            rsm += tok[1] - 1;
        }
    }
    foreach (tok; li) {
        if (tok[0] == 'v') {
            lsm += tok[1] - 1;
            rsm -= tok[1] - 1;
        }
        if (tok[0] == 'o') {
            ans += lsm * tok[1] * rsm;
        }
    }

    writeln(ans);
    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

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

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /home/yosupo/Programs/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;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private 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) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

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

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

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

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

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

int N;
string S;

void main() {
  try {
    for (; ; ) {
      S = readToken();
      N = cast(int)(S.length);

      auto sum = new long[N];
      foreach (i; 0 .. N - 1) {
        sum[i + 1] = sum[i] + ((S[i .. i + 2] == "vv") ? 1 : 0);
      }
      long ans;
      foreach (i; 0 .. N) {
        if (S[i] == 'o') {
          ans += sum[max(i - 1, 0)] * (sum[$ - 1] - sum[min(i + 1, $ - 1)]);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

int N;
string S;

void main() {
  try {
    for (; ; ) {
      S = readToken();
      N = cast(int)(S.length);

      auto sum = new long[N];
      foreach (i; 0 .. N - 1) {
        sum[i + 1] = sum[i] + ((S[i .. i + 2] == "vv") ? 1 : 0);
      }
      long ans;
      foreach (i; 0 .. N) {
        if (S[i] == 'o') {
          ans += sum[i - 1] * (sum[$ - 1] - sum[i + 1]);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given a grid, consisting of $$$2$$$ rows and $$$n$$$ columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells $$$A$$$ and $$$B$$$ belong to the same component if they are neighbours, or if there is a neighbour of $$$A$$$ that belongs to the same component with $$$B$$$.Let's call some bicoloring beautiful if it has exactly $$$k$$$ components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $$$998244353$$$.

The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1000$$$, $$$1 \le k \le 2n$$$) — the number of columns in a grid and the number of components required.

Print a single integer — the number of beautiful bicolorings modulo $$$998244353$$$.

NoteOne of possible bicolorings in sample $$$1$$$:

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

int saiki(int idx, int cnt, int s, int n, int k, int[][] c, int[][][] dp)
{
    if (cnt > k)
    {
        return 0;
    }
    if (dp[idx][cnt][s] != -1)
    {
        return dp[idx][cnt][s];
    }
    if (idx == n)
    {
        dp[idx][cnt][s] = (cnt == k) ? 1 : 0;
        return dp[idx][cnt][s];
    }
    const static int mod = 998244353;
    auto res = 0;
    foreach (i; 0 .. 4)
    {
        auto ret = saiki(idx + 1, cnt + c[s][i], i, n, k, c, dp);
        res = (res + ret) % mod;
    }
    dp[idx][cnt][s] = res;
    return res;
}

void solve(int n, int k)
{
    auto c = new int[][](4, 4);
    foreach (i; 0 .. 4) fill(c[i], 0);
    foreach (i; 1 .. 4) c[0][i] = 1;
    foreach (i; 0 .. 3) c[3][i] = 1;
    c[1][2] = c[2][1] = 2;
    auto dp = new int[][][](n + 1, k + 1, 4);
    foreach (i; 0 .. n + 1)
    {
        foreach (j; 0 .. k + 1)
        {
            fill(dp[i][j], -1);
        }
    }
    const static int mod = 998244353;
    auto res = 0;
    res = (res + saiki(1, 1, 0, n, k, c, dp)) % mod;
    res = (res + saiki(1, 2, 1, n, k, c, dp)) % mod;
    res = (res + saiki(1, 2, 2, n, k, c, dp)) % mod;
    res = (res + saiki(1, 1, 3, n, k, c, dp)) % mod;
    writeln(res);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        solve(n, k);
    }
    return 0;
}

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

immutable int MD = 998244353;

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

    auto dp = new uint[][][] (n+1, 2*k+1, 4);
    dp[1][1][0] = dp[1][1][1] = dp[1][2][2] = dp[1][2][3] = 1;
    foreach (i; 2 .. n+1) {
        foreach (j; 1 .. 2*k+1) {
            dp[i][j][0] = dp[i-1][j][0] + dp[i-1][j-1][1] + dp[i-1][j][2] + dp[i-1][j][3];
            dp[i][j][1] = dp[i-1][j-1][0] + dp[i-1][j][1] + dp[i-1][j][2] + dp[i-1][j][3];

            dp[i][j][2] = dp[i-1][j-1][0] + dp[i-1][j-1][1] + dp[i-1][j][2];
            if (j > 1) dp[i][j][2] += dp[i-1][j-2][3];

            dp[i][j][3] = dp[i-1][j-1][0] + dp[i-1][j-1][1] + dp[i-1][j][3];
            if (j > 1) dp[i][j][3] += dp[i-1][j-2][2];

            dp[i][j][] %= MD;
            debug { writeln(i, ' ', j, ' ', dp[i][j]); }
        }
    }

    auto ans = dp[n][k].sum() % MD;
    ans.writeln;
}

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

immutable int MD = 998244353;

int add(int a, int b) {
    a += b;
    if (a > MD) a -= MD;
    return a;
}

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

    auto dp = new int[][][] (n+1, 2*k+10, 4);
    dp[1][1][0] = dp[1][1][1] = dp[1][2][2] = dp[1][2][3] = 1;
    foreach (i; 2 .. n+1) {
        foreach (j; 1 .. 2*k+1) {
            dp[i][j][0] = add(dp[i-1][j][0], add(dp[i-1][j-1][1], add(dp[i-1][j][2], dp[i-1][j][3])));
            dp[i][j][1] = add(dp[i-1][j-1][0], add(dp[i-1][j][1], add(dp[i-1][j][2], dp[i-1][j][3])));

            dp[i][j][2] = add(dp[i-1][j-1][0], add(dp[i-1][j-1][1], dp[i-1][j][2]));
            if (j > 1) dp[i][j][2] = add(dp[i][j][2], dp[i-1][j-2][3]);

            dp[i][j][3] = add(dp[i-1][j-1][0], add(dp[i-1][j-1][1], dp[i-1][j][3]));
            if (j > 1) dp[i][j][3] = add(dp[i][j][3], dp[i-1][j-2][2]);

            debug { writeln(i, ' ', j, ' ', dp[i][j]); }
        }
    }

    auto ans = dp[n][k].fold!((a, b) => add(a, b));
    ans.writeln;
}

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

  int n, k; rd(n, k);

  auto dp=new int[][](4, k+10);
  const int mod=998244353;

  void add(ref int x, int y){
    x+=y;
    if(x>=mod) x-=mod;
  }
  dp[0][1]=dp[3][1]=1;
  dp[1][2]=dp[2][2]=1;
  for(int i=1; i<n; i++){
    auto nex=new int[][](4, k+10);
    foreach(s; 0..(1<<2)){
      for(int j=1; j<=k; j++){
        foreach(t; 0..(1<<2)){
          if(s==t){
            add(nex[t][j], dp[s][j]);
          }else if((s^t)==((1<<2)-1)){
            if(s==0 || s==3){
              if(j+1<=k){
                add(nex[t][j+1], dp[s][j]);
              }
            }else{
              if(j+2<=k){
                add(nex[t][j+2], dp[s][j]);
              }
            }
          }else if((s==0 || s==3) && (t==1 || t==2)){
            if(j+1<=k){
              add(nex[t][j+1], dp[s][j]);
            }
          }else{
            add(nex[t][j], dp[s][j]);
          }
        }
      }
    }
    dp.swap(nex);
  }
  int tot=0;
  foreach(i; 0..(1<<2)) (tot+=dp[i][k])%=mod;
  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));
}


You are given an array $$$a[0 \ldots n - 1] = [a_0, a_1, \ldots, a_{n - 1}]$$$ of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.In one step, the array $$$a$$$ is replaced by another array of length $$$n$$$ according to the following rules:   First, a new array $$$a^{\rightarrow d}$$$ is defined as a cyclic shift of the array $$$a$$$ to the right by $$$d$$$ cells. The elements of this array can be defined as $$$a^{\rightarrow d}_i = a_{(i + n - d) \bmod n}$$$, where $$$(i + n - d) \bmod n$$$ is the remainder of integer division of $$$i + n - d$$$ by $$$n$$$.  It means that the whole array $$$a^{\rightarrow d}$$$ can be represented as a sequence $$$$$$a^{\rightarrow d} = [a_{n - d}, a_{n - d + 1}, \ldots, a_{n - 1}, a_0, a_1, \ldots, a_{n - d - 1}]$$$$$$  Then each element of the array $$$a_i$$$ is replaced by $$$a_i \,\&\, a^{\rightarrow d}_i$$$, where $$$\&$$$ is a logical "AND" operator. For example, if $$$a = [0, 0, 1, 1]$$$ and $$$d = 1$$$, then $$$a^{\rightarrow d} = [1, 0, 0, 1]$$$ and the value of $$$a$$$ after the first step will be $$$[0 \,\&\, 1, 0 \,\&\, 0, 1 \,\&\, 0, 1 \,\&\, 1]$$$, that is $$$[0, 0, 0, 1]$$$.The process ends when the array stops changing. For a given array $$$a$$$, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains two integers: $$$n$$$ ($$$1 \le n \le 10^6$$$) — array size and $$$d$$$ ($$$1 \le d \le n$$$) — cyclic shift offset. The second line of the description contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$0 \le a_i \le 1$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the number of steps after which the array will contain only zeros for the first time. If there are still elements equal to $$$1$$$ in the array after the end of the process, print -1.

NoteIn the third sample test case the array will change as follows:   At the beginning $$$a = [1, 1, 0, 1, 0]$$$, and $$$a^{\rightarrow 2} = [1, 0, 1, 1, 0]$$$. Their element-by-element "AND" is equal to $$$$$$[1 \,\&\, 1, 1 \,\&\, 0, 0 \,\&\, 1, 1 \,\&\, 1, 0 \,\&\, 0] = [1, 0, 0, 1, 0]$$$$$$  Now $$$a = [1, 0, 0, 1, 0]$$$, then $$$a^{\rightarrow 2} = [1, 0, 1, 0, 0]$$$. Their element-by-element "AND" equals to $$$$$$[1 \,\&\, 1, 0 \,\&\, 0, 0 \,\&\, 1, 1 \,\&\, 0, 0 \,\&\, 0] = [1, 0, 0, 0, 0]$$$$$$  And finally, when $$$a = [1, 0, 0, 0, 0]$$$ we get $$$a^{\rightarrow 2} = [0, 0, 1, 0, 0]$$$. Their element-by-element "AND" equals to $$$$$$[1 \,\&\, 0, 0 \,\&\, 0, 0 \,\&\, 1, 0 \,\&\, 0, 0 \,\&\, 0] = [0, 0, 0, 0, 0]$$$$$$  Thus, the answer is $$$3$$$ steps.In the fourth sample test case, the array will not change as it shifts by $$$2$$$ to the right, so each element will be calculated as $$$0 \,\&\, 0$$$ or $$$1 \,\&\, 1$$$ thus not changing its value. So the answer is -1, the array will never contain only zeros.

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

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

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

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

        auto vis = new bool[] (n);
        vis[] = false;

        int ans = -1;
        foreach (i; 0 .. n) {
            if (vis[i]) { continue; }

            int[] tmp;
            int p = i;
            while (!vis[p]) {
                vis[p] = true;
                tmp ~= arr[p];
                p = (p + d) % n;
            }

            tmp = tmp ~ tmp;

            int longest = 0;
            int cur = 0;
            foreach (e; tmp) {
                if (e == 0) { cur = 0; }
                else { cur += 1; }

                longest = max(longest, cur);
            }

            if (longest == tmp.length) {
                ans = -1;
                break;
            }

            ans = max(ans, longest);
        }

        ans.writeln;
    }

}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto d = readInt!int;
	auto a = ma(n, readInt!int);
	auto inCycle = new bool[](n);
	int steps = 0;
	bool processCycle(int[] cycle)
	{
		debug writeln("processing cycle ", cycle);
		if (cycle.length == 0) return false;
		auto isBad = true;
		foreach(i; cycle)
			if (a[i] == 0)
				isBad = false;
		if (isBad) { return isBad; }
		auto doubleCycle = cycle ~ cycle;
		int last0 = -1;
		foreach(i, ci; doubleCycle)
		{
			if (a[ci] == 0) last0 = cast(int)i;
			if (i >= cycle.length)
			{
				steps = max(steps, cast(int)i - last0);
			}
		}
		return isBad;
	}
	auto bad = false;
	foreach(i; 0 .. n)
	{
		int[] cycle;
		while (!inCycle[i])
		{
			inCycle[i] = true;
			cycle ~= i;
			i = (i+d)%n;
		}
		bad = bad || processCycle(cycle);
	}
	if (!bad) steps.writeln; else (-1).writeln;
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

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

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

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.Roger Waters has a square grid of size $$$n\times n$$$ and he wants to traverse his grid from the upper left ($$$1,1$$$) corner to the lower right corner ($$$n,n$$$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($$$1,1$$$) and ($$$n,n$$$) every cell has a value $$$0$$$ or $$$1$$$ in it.Before starting his traversal he will pick either a $$$0$$$ or a $$$1$$$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($$$1,1$$$) and ($$$n,n$$$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($$$1,1$$$) takes value the letter 'S' and the cell ($$$n,n$$$) takes value the letter 'F'.For example, in the first example test case, he can go from ($$$1, 1$$$) to ($$$n, n$$$) by using the zeroes on this path: ($$$1, 1$$$), ($$$2, 1$$$), ($$$2, 2$$$), ($$$2, 3$$$), ($$$3, 3$$$), ($$$3, 4$$$), ($$$4, 4$$$)The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from $$$0$$$ to $$$1$$$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells.  Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.We can show that there always exists a solution for the given constraints.Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($$$n,n$$$) no matter what digit he picks.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 50$$$). Description of the test cases follows. The first line of each test case contains one integers $$$n$$$ ($$$3 \le n \le 200$$$). The following $$$n$$$ lines of each test case contain the binary grid, square ($$$1, 1$$$) being colored in 'S' and square ($$$n, n$$$) being colored in 'F'. The sum of values of $$$n$$$ doesn't exceed $$$200$$$.

For each test case output on the first line an integer $$$c$$$ ($$$0 \le c \le 2$$$)  — the number of inverted cells. In $$$i$$$-th of the following $$$c$$$ lines, print the coordinates of the $$$i$$$-th cell you inverted. You may not invert the same cell twice.  Note that you cannot invert cells $$$(1, 1)$$$ and $$$(n, n)$$$.

NoteFor the first test case, after inverting the cell, we get the following grid:S01000011001111F

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (s[0][1] == s[1][0])
		{
			if (s[n-1][n-2] == s[0][1])
				ans[ti] ~= [n, n-1];
			if (s[n-2][n-1] == s[0][1])
				ans[ti] ~= [n-1, n];
		}
		else if (s[n-1][n-2] == s[n-2][n-1])
		{
			if (s[0][1] == s[n-1][n-2])
				ans[ti] ~= [1, 2];
			if (s[1][0] == s[n-1][n-2])
				ans[ti] ~= [2, 1];
		}
		else
		{
			if (s[0][1] == '1')
				ans[ti] ~= [1, 2];
			if (s[1][0] == '1')
				ans[ti] ~= [2, 1];
			if (s[n-1][n-2] == '0')
				ans[ti] ~= [n, n-1];
			if (s[n-2][n-1] == '0')
				ans[ti] ~= [n-1, n];
		}
	}

	foreach (e; ans)
	{
		writeln(e.length);
		foreach (ee; e)
			writeln(ee[0], " ", ee[1]);
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (s[0][1] == s[1][0])
		{
			if (s[n-1][n-2] == s[0][1])
				ans[ti] ~= [n, n-1];
			if (s[n-2][n-1] == s[0][1])
				ans[ti] ~= [n-1, n];
		}
		else if (s[n-1][n-2] == s[n-2][n-1])
		{
			if (s[0][1] == s[n-1][n-2])
				ans[ti] ~= [1, 2];
			if (s[1][2] == s[n-1][n-2])
				ans[ti] ~= [2, 1];
		}
		else
		{
			if (s[0][1] == '1')
				ans[ti] ~= [1, 2];
			if (s[1][2] == '1')
				ans[ti] ~= [2, 1];
			if (s[n-1][n-2] == '0')
				ans[ti] ~= [n, n-1];
			if (s[n-2][n-1] == '0')
				ans[ti] ~= [n-1, n];
		}
	}

	foreach (e; ans)
	{
		writeln(e.length);
		foreach (ee; e)
			writeln(ee[0], " ", ee[1]);
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (s[0][1] == s[1][0])
		{
			if (s[n-1][n-2] == s[0][1])
				ans[ti] ~= [n, n-1];
			if (s[n-2][n-1] == s[0][1])
				ans[ti] ~= [n-1, n];
		}
		else
		{
			if (s[0][1] == '1')
				ans[ti] ~= [1, 2];
			if (s[1][2] == '1')
				ans[ti] ~= [2, 1];
			if (s[n-1][n-2] == '0')
				ans[ti] ~= [n, n-1];
			if (s[n-2][n-1] == '0')
				ans[ti] ~= [n-1, n];
		}
	}

	foreach (e; ans)
	{
		writeln(e.length);
		foreach (ee; e)
			writeln(ee[0], " ", ee[1]);
	}
	stdout.flush;
	debug readln;
}