The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map. Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 100) — the number of rows and columns in the table, correspondingly. Each of the next n lines contains m characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".". It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.

Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

void main(){
  int n,m;
  size_t iig,jjg,ii,jj,jj2,ii2 = -1;
  int state = 0;
  readf("%s %s\n",&n,&m);
  for(int i = 0; i < n; i++){
    string line;
    readf("%s\n",&line);

    foreach(j,c;line){
      if(c == '*'){
        switch (state){
          case 0:
            iig = i;
            jjg = j;
            state++;
            break;
          case 1:
            // * .. *
            if(iig == i){
              jj2 = j;
            }
            // ... *
            // * ..
            if(iig != i && jjg != j){
              ii = iig;
              jj = j;
              writefln("%s %s",ii+1,jj+1);
              return;
            }

            // *..
            // *..
            if(jjg == j){
              ii2 = i;
            }
            state++;
            break;
          case 2:
            // *.....
            // * ....
            if(ii2 != -1){
              writefln("%s %s",iig+1,j+1);
            } else {
              if(j == jjg){
                writefln("%s %s",i+1,jj2+1);
              } else {
                writefln("%s %s",i+1,jjg+1);
              }
            }
            return;
          default:
            writefln("ERRO");
        }
      }
    }
  }
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

void main(){
  int n,m;
  readf("%s %s\n",&n,&m);
  for(int i = 0; i < n; i++){
    string line;
    readf("%s\n",&line);
    int cnt = 0;
    size_t jj = 0;
    foreach(j,c;line){
      if(c == '*'){
        cnt++;
        jj = j;
      }
    }
    size_t pos = jj;
    if(cnt == 1){
      if(jj < line.length/2){
        pos += line.length/2+1;
      } else {
        pos -= line.length/2;
      }
      writefln("%s %s",i+1,pos+1);
      return;
    }
  }
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

void main(){
  int n,m;
  size_t jj = -1;
  size_t ii = -1;
  readf("%s %s\n",&n,&m);
  for(int i = 0; i < n; i++){
    string line;
    readf("%s\n",&line);
    int cnt = 0;

    foreach(j,c;line){
      if(c == '*'){
        cnt++;
        if(cnt == 2){
          jj = j;
        }
      }
    }
    if(cnt == 1){
      ii = i;
    }
    if(ii != -1 && jj != -1){
      writefln("%s %s",ii+1,jj+1);
      return;
    }
  }
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

void main(){
  int n,m;
  readf("%s %s\n",&n,&m);
  for(int i = 0; i < n; i++){
    string line;
    readf("%s\n",&line);
    int cnt = 0;
    size_t jj = 0;
    foreach(j,c;line){
      if(c == '*'){
        cnt++;
        jj = j;
      }
    }
    size_t pos = jj;
    if(cnt == 1){
      if(jj < line.length/2){
        pos += line.length-jj-1;
      } else {
        pos -= line.length/2;
      }
      writefln("%s %s",i+1,pos+1);
      return;
    }
  }
}


One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length    The picture corresponds to the first example

The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109,  - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.

Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.

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

void main()
{
	int n;
	loop:while(read(&n))
	{
		writeln("YES");
		foreach(i;0..n)
		{
			int x,y,a,b;
			read(&x,&y,&a,&b);
			x=abs(x);y=abs(y);
			writeln(2*(x&1)+(y&1)+1);
		}
	}
}

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

void main()
{
	int n;
	loop:while(read(&n))
	{
		writeln("YES");
		foreach(i;0..n)
		{
			int x,y,a,b;
			read(&x,&y,&a,&b);
			x=abs(x);y=abs(y);
			writeln(2*(x&1)+(y&1));
		}
	}
}


Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

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

void main() {
    int n, m; readf("%d %d\n", &n, &m);
    bool[] kicked = new bool[n];
    bool[][] g = new bool[][n]; foreach(ref _; g) _ = new bool[n];
    for (int i = 0; i < m; i++) {
        int a, b; readf("%d %d\n", &a, &b); a--; b--;
        g[a][b] = g[b][a] = true;
    }
    int ans = 0;
    while (true) {
        bool f = false;
        bool[] kick = new bool[n];
        for (int i = 0; i < n; i++) {
            if (kicked[i]) continue;
            int c = 0;
            for (int j = 0; j < n; j++) {
                if (g[i][j] && !kicked[j]) {
                    c++;
                }
            }
            if (c == 1) {
                f = true;
                for (int j = 0; j < n; j++) {
                    if (g[i][j] && !kicked[j]) {
                        kick[i] = true;
                        break;
                    }
                }
            }
        }
        foreach (i; 0 .. n) {
            kicked[i] |= kick[i];
        }
        //writeln(kicked);
        if (f) { ans++; }
        else { break; }
    }
    writeln(ans);
}


The game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m ≥ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then k distinct numbers between 1 and m will be called at random (called uniformly among all available sets of k numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).Determine the expected value of the score. The expected score may be very large. If the expected score is larger than 1099, print 1099 instead (for example as "1e99" without the quotes).

Input will consist of three integers n, m, k (1 ≤ n ≤ 300; n2 ≤ m ≤ 100000; n ≤ k ≤ m).

Print the smaller of 1099 and the expected score. Your answer must be correct within an absolute or relative error of 10 - 9.

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

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

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

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

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

real[] logFac;
real[][] bn;

int N, M, K;

void main(string[] args) {
	logFac = new real[200005];
	logFac[0] = 0.0;
	foreach (i; 1 .. logFac.length) {
		logFac[i] = logFac[i - 1] + log(cast(real)(i));
	}
	bn = new real[][](605, 605);
	foreach (i; 0 .. bn.length) {
		bn[i][0] = bn[i][i] = 1.0;
		foreach (j; 1 .. i) {
			bn[i][j] = bn[i - 1][j - 1] + bn[i - 1][j];
		}
	}

	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		K = readInt;

		real[][] ps = new real[][](N + 1, N + 1);
		foreach (x; 0 .. N + 1) foreach (y; 0 .. N + 1) {
			const need = N * N - (N - x) * (N - y);
			if (K >= need) {
				//	C(M - need, K - need) / C(M, K)
				ps[x][y] = exp(logFac[M - need] - logFac[K - need] - logFac[M] + logFac[K]);
			} else {
				ps[x][y] = 0.0;
			}
		}
debug{
writeln("ps = ",ps);
}

		/*
		foreach_reverse (x; 0 .. N + 1) foreach (xx; x + 1 .. N + 1) {
			foreach (y; 0 .. N + 1) {
				ps[x][y] -= bn[N - x][N - xx] * ps[xx][y];
			}
		}
		foreach_reverse (y; 0 .. N + 1) foreach (yy; y + 1 .. N + 1) {
			foreach (x; 0 .. N + 1) {
				ps[x][y] -= bn[N - y][N - yy] * ps[x][yy];
			}
		}
debug{
writeln("ps = ",ps);
}
		*/
		real[] qs = new real[N * 2 + 1];
		qs[] = 0.0;
		foreach (x; 0 .. N + 1) foreach (y; 0 .. N + 1) {
			qs[x + y] += bn[N][x] * bn[N][y] * ps[x][y];
		}
debug{
writeln("qs = ",qs);
}
		real ans = 0.0;
		real val = 1.0;
		foreach (z; 0 .. N * 2 + 1) {
			ans += qs[z] * val;
			// val *= 2.0;
		}
		if (ans > 1e99) {
			writeln("1e99");
		} else {
			writefln("%.10f", ans);
		}
	}
	} catch (EOFException) {}
}

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

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

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

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

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

real[] logFac;
real[][] bn;

int N, M, K;

void main(string[] args) {
	logFac = new real[200005];
	logFac[0] = 0.0;
	foreach (i; 1 .. logFac.length) {
		logFac[i] = logFac[i - 1] + log(cast(real)(i));
	}
	bn = new real[][](605, 605);
	foreach (i; 0 .. bn.length) {
		bn[i][0] = bn[i][i] = 1.0;
		foreach (j; 1 .. i) {
			bn[i][j] = bn[i - 1][j - 1] + bn[i - 1][j];
		}
	}

	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		K = readInt;

		real[][] ps = new real[][](N + 1, N + 1);
		foreach (x; 0 .. N + 1) foreach (y; 0 .. N + 1) {
			const need = N * N - (N - x) * (N - y);
			if (K >= need) {
				//	C(M - need, K - need) / C(M, K)
				ps[x][y] = exp(logFac[M - need] - logFac[K - need] - logFac[M] + logFac[K]);
			} else {
				ps[x][y] = 0.0;
			}
		}
debug{
writeln("ps = ",ps);
}

		foreach_reverse (x; 0 .. N + 1) foreach (xx; x + 1 .. N + 1) {
			foreach (y; 0 .. N + 1) {
				ps[x][y] -= bn[N - x][N - xx] * ps[xx][y];
			}
		}
		foreach_reverse (y; 0 .. N + 1) foreach (yy; y + 1 .. N + 1) {
			foreach (x; 0 .. N + 1) {
				ps[x][y] -= bn[N - y][N - yy] * ps[x][yy];
			}
		}
debug{
writeln("ps = ",ps);
}
		real[] qs = new real[N * 2 + 1];
		qs[] = 0.0;
		foreach (x; 0 .. N + 1) foreach (y; 0 .. N + 1) {
			qs[x + y] += bn[N][x] * bn[N][y] * ps[x][y];
		}
debug{
writeln("qs = ",qs);
}
		real ans = 0.0;
		real val = 1.0;
		foreach (z; 0 .. N * 2 + 1) {
			ans += qs[z] * val;
			val *= 2.0;
		}
		if (ans > 1e99) {
			writeln("1e99");
		} else {
			writefln("%.10f\n", ans);
		}
	}
	} catch (EOFException) {}
}


Given a string $$$s$$$ of length $$$n$$$ and integer $$$k$$$ ($$$1 \le k \le n$$$). The string $$$s$$$ has a level $$$x$$$, if $$$x$$$ is largest non-negative integer, such that it's possible to find in $$$s$$$:  $$$x$$$ non-intersecting (non-overlapping) substrings of length $$$k$$$,  all characters of these $$$x$$$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$), denoted as $$$s[i \dots j]$$$ = "$$$s_{i}s_{i+1} \dots s_{j}$$$".For example, if $$$k = 2$$$, then:  the string "aabb" has level $$$1$$$ (you can select substring "aa"),  the strings "zzzz" and "zzbzz" has level $$$2$$$ (you can select two non-intersecting substrings "zz" in each of them),  the strings "abed" and "aca" have level $$$0$$$ (you can't find at least one substring of the length $$$k=2$$$ containing the only distinct character). Zuhair gave you the integer $$$k$$$ and the string $$$s$$$ of length $$$n$$$. You need to find $$$x$$$, the level of the string $$$s$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the value of $$$k$$$. The second line contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.

Print a single integer $$$x$$$ — the level of the string.

NoteIn the first example, we can select $$$2$$$ non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is $$$2$$$.In the second example, we can select either substring "a" or "b" to get the answer $$$1$$$.

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

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

    for (char c = 'a'; c <= 'z'; ++c) {
        int tmp = 0;
        int v = 0;
        foreach (i; 0..N) {
            if (S[i] == c) {
                tmp += 1;
                if (tmp == K) {
                    v += 1;
                    tmp = 0;
                }
            } else {
                tmp = 0;
            }
        }
        ans = max(ans, v);
    }

    ans.writeln;
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math : abs;

alias Tree = RBT!int;

void main() {
  GC.disable();

  long n, k;
  readf(" %s %s\n", n, k);
  auto s = readln().strip.dup;

  int ans = -1;
  foreach(c; iota(0,27)) {
      auto cc = 'a' + c;
      int count= 0;
      int tt = 0;

    foreach(e; s){
        if (e == cc) {
        count++;
      }  else {
      tt += count / k;
      count = 0;
      }
    }

    tt += count/k;

    ans = max(tt, ans);
  }

  writeln(ans);

}


One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.

The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.

Print a single integer — the number of problems the friends will implement on the contest.

NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.

import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.array;
//-----------------------

void main(){
  auto n = readln.chomp.to!int;
  int[][] matrix;
  foreach(i; 0..n){ matrix ~= readln.chomp.split(" ").map!(to!int).array; }
  matrix.map!(sum).filter!((e) => e >= 2).array.length.writeln;
}

import std.stdio;
import std.format;

void main()
{
    readln; //discard first line

    uint numChallenges;

    byte a, b, c;

    foreach(line; stdin.byLine)
    {
        formattedRead(line, "%s %s %s", &a, &b, &c);

        if ((a + b + c) > 1) ++numChallenges;
    }

    numChallenges.writeln;
}

import std.stdio;

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

    int implement = 0;
    for (int i = 0; i < n; ++i) {
        int p, v, t;
        readf("%d %d %d\n", &p, &v, &t);

        if (p+v+t >= 2) {
            implement++;
        }
    }

    writefln("%d", implement);
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n;
	int a, b, c;
	scanf("%d", &n);
	int noproblems = 0;
	for (int i = 0; i < n; i++)
	{
		scanf("%d %d %d", &a, &b, &c);
		noproblems += (a + b + c) > 1 ? 1 : 0;
	}
	printf("%d", noproblems);
    return 0;
}

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

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

	for(int i=0; i<n; i++) {
		if(readln.chomp.split(" ").map!(to!int).filter!(x => x==1).count >= 2) {
			problems++;
		}
	}

	problems.writeln;
}

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

void main() {
	int n = readln.chomp.to!int;
	int problems = 0;

	for(int i=0; i<n; i++) {
		int[3] a = readln.chomp.split(" ").map!(to!int).array;
		int sure = 0;

		foreach(item; a) {
			if(item) {
				sure++;
			}
		}

		if(sure>=2) {
			problems++;
		}
	}

	problems.writeln;
}

// https://codeforces.com/problemset/problem/231/A
// implementation, simulation
import std.conv;
import std.range;
import std.stdio;
import std.algorithm;

void main() {
    int answer = 0;
    foreach(line; stdin.byLine.dropOne)
        answer += (line.split.map!(to!int).sum > 1);
    answer.writeln;
}

// https://codeforces.com/problemset/problem/231/A
import std.conv;
import std.range;
import std.stdio;
import std.algorithm;

void main() {
    int answer = 0;
    foreach(line; stdin.byLine.dropOne) {
        if(line.split.map!(to!int).count!(x => x == 1) >= 2)
            answer += 1;
    }
    answer.writeln;
}

import std.stdio;
void main()
{
    int n;
    readf("%s\n", &n);
    int ans = 0;
    for(int i = 0; i < n; ++i){
        int a,b,c;
        readf("%s %s %s\n",&a,&b,&c);
        ans += (a+b+c)>=2;
    }
    writeln(ans);
}

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;
import std.array;
import std.container;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

double nd()
{
    sb();
    double res = 0;
    while ((curc != '.') & (32 < curc))
    {
        res = res * 10 + cast(int)(curc - '0');
        curc = getchar();
    }
    if (curc == '.')
    {
        curc = getchar();
        double exp = 10;
        while (32 < curc)
        {
            res += cast(double)(curc - '0') / exp;
            exp *= 10;
            curc = getchar();
        }
    }
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CF143A()
{
    int cnt, n = ni();
    for (int i = 0; i < n; ++i)
        if (ni() + ni() + ni() >= 2) ++cnt;
    writeln(cnt);
}

void main()
{
    CF143A();
}

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

void main() {
  readln;

  int ans = 0;
  foreach (string s; stdin.lines) {
    if (s.countchars("1") >= 2) ans++;
  }

  ans.writeln;
}

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

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

    int ans;

    foreach(i ; 0 .. n){
        auto a = readln.split.to!(int[]).sum;
        ans += (a > 1);
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

import std.stdio;

void main()
{
    readln; //discard first line

    uint numChallenges;

    byte a, b, c;

    while(!stdin.eof)
    {
        readf("%s %s %s\n", &a, &b, &c);
        if (stdin.eof) break;
        writeln(a,b,c);

        if ((a + b + c) > 1) ++numChallenges;

    }

    numChallenges.writeln;
}

import std.stdio;

void main()
{
    readln; //discard first line

    uint numChallenges;

    byte a, b, c;

    while(!stdin.eof)
    {
        readf("%s %s %s\n", &a, &b, &c);

        if ((a + b + c) > 1) ++numChallenges;
    }

    numChallenges.writeln;
}

import std.stdio;

void main()
{
    readln; //discard first line

    uint numChallenges;

    byte a, b, c;

    while(!stdin.eof)
    {
        readf("%s %s %s\n", &a, &b, &c);

        if (a + b + c > 1) ++numChallenges;
    }

    numChallenges.writeln;
}

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

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

	for(int i=0; i<n; i++) {
		if(readln.chomp.split(" ").map!(to!int).filter!(x => x==1).count >= 2) {
			problems++;
		}
	}
}

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;
import std.array;
import std.container;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

double nd()
{
    sb();
    double res = 0;
    while ((curc != '.') & (32 < curc))
    {
        res = res * 10 + cast(int)(curc - '0');
        curc = getchar();
    }
    if (curc == '.')
    {
        curc = getchar();
        double exp = 10;
        while (32 < curc)
        {
            res += cast(double)(curc - '0') / exp;
            exp *= 10;
            curc = getchar();
        }
    }
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CF143A()
{
    int cnt;
    for (int i = 0; i < ni(); ++i)
        if (ni() + ni() + ni() >= 2) ++cnt;
    writeln(cnt);
}

void main()
{
    CF143A();
}


Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.

The first line contains three integers: n, s, t (1 ≤ n ≤ 105; 1 ≤ s, t ≤ n) — the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1, p2, ..., pn (1 ≤ pi ≤ n) — the shuffling operation parameters. It is guaranteed that all pi's are distinct. Note that s can equal t.

If the marble can move from position s to position t, then print on a single line a non-negative integer — the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.

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

int[] p;
bool[] e;

int next(int s) {
    if (e[s - 1]) {
        return -1;
    }
    return p[s - 1];
}

void main() {
    int n, s, t; readf("%d %d %d\n", &n, &s, &t);
    p = stdin.readln.chomp.split.map!(to!int).array;
    e = new bool[n];
    int x = s;
    int i = 0;
    while (true) {
        if (x == t) {
            writeln(i);
            break;
        }
        i++;
        x = next(x);
        if (i == n) {
            writeln(-1);
            break;
        }
    }
}

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

int[] p;

int next(int s) {
    return p[s - 1];
}

void main() {
    int n, s, t; readf("%d %d %d\n", &n, &s, &t);
    p = stdin.readln.chomp.split.map!(to!int).array;
    int x = s;
    int i = 0;
    while (true) {
        if (x == t) {
            writeln(i);
            break;
        }
        i++;
        x = next(x);
        if (i == n) {
            writeln(-1);
            break;
        }
    }
}

import std.stdio;

void main ()
{
	int n, s, t;
	while (readf (" %s %s %s", &n, &s, &t) > 0)
	{
		s--;
		t--;
		auto p = new int [n + 1];
		foreach (i; 0..n)
		{
			readf (" %s", &p[i]);
		}
		int res = -1;
		p[] -= 1;
		foreach (i; 0..n)
		{
			if (s == t)
			{
				res = i;
				break;
			}
			s = p[s];
		}
		writeln (res);
	}
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n, s, t;
main_loop:
	while (readf (" %s %s %s", &n, &s, &t) > 0)
	{
		s--;
		t--;
		auto p = new int [n + 1];
		foreach (i; 0..n)
		{
			readf (" %s", &p[i]);
		}
		p[] -= 1;
		foreach (i; 0..n)
		{
			if (s == t)
			{
				writeln (i);
				continue main_loop;
			}
			s = p[s];
		}
		writeln (-1);
	}
}

import std.stdio;

void main() {
  int n, s, t;
  scanf("%d %d %d", &n, &s, &t);
  int[] p = new int[n+1];
  for (int i = 1 ; i <= n ; ++i) {
    scanf("%d", &p[i]);
  }
  int ans = 0, flg = 1;
  bool[int] set;
  for ( ; s != t ; ++ans) {
    if (s in set) {flg = 0; break;}
    set[s] = true;
    s = p[s];
  }
  if (!flg) writeln("-1");
  else writeln(ans);
}

module sigod.codeforces.p285B;

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

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

	if (s == t) {
		stdout.write("0");
		return;
	}

	stdin.readln();
	int[] p = read_array!(int)();

	--s;
	--t;

	int result = 0;
	int position = s;

	while (position != t && p[position] != -1) {
		auto tmp = position;
		position = p[position] - 1;

		p[tmp] = -1;

		++result;
	}

	if (position != t) result = -1;

	stdout.write(result);
}

private
T[] read_array(T)() {
	auto input = stdin.readln().strip().split();

	T[] result = new T[input.length];

	foreach (index, ref element; input) {
		result[index] = element.to!T();
	}

	return result;
}


Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed.    Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally:   if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$);  if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots:   1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.

For each test case print:   YES if there is a sequence of shots leading to a given matrix;  NO if such a sequence does not exist.  The letters in the words YES and NO can be printed in any case.

NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") string[] mat;

  void solve(long tc = -1)
  {
    foreach(i; 0 .. n)
      {
        foreach(j; 0 .. n)
          {
            if (mat.at(i).at(j) == '1')
              {
                if (i + 1 >= n || mat.at(i + 1).at(j) == '1' ||
                    j + 1 >= n || mat.at(i).at(j + 1) == '1')
                  {

                  }
                else
                  {
                    writeln("NO");
                    return;
                  }
              }
          }
      }
    writeln("YES");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

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

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

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

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

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

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

    }
}

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

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = true;
		foreach (i; 0..n-1)
		{
			foreach (j; 0..n-1)
			{
				if (s[i][j] == '0') continue;
				if (s[i][j+1] == '0' && s[i+1][j] == '0')
					ans[ti] = false;
			}
		}
	}

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


Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.

The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.

If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).

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

immutable int LET = 26;
immutable char START = 'a';
immutable int MAX_N = 100_005;
immutable int NA = -1;

struct Node
{
	int [LET] next = NA;
}

Node [MAX_N] t;
int m;
bool cur_outcome;

bool play (int v)
{
	assert (v != NA);

	bool ok = false;
	foreach (d; 0..LET)
	{
		if (t[v].next[d] != NA)
		{
			ok = true;
			if (!play (t[v].next[d]))
			{
				return true;
			}
		}
	}
	if (!ok)
	{
		return cur_outcome;
	}
	return false;
}

void build (const string [] s)
{
	debug {writeln (s);}
	t[] = Node.init;
	m = 1;
	foreach (cur; s)
	{
		int v = 0;
		foreach (let; cur)
		{
			debug {writeln (v, ' ', let - START);}
			if (t[v].next[let - START] == NA)
			{
				t[v].next[let - START] = m;
				m++;
			}
			v = t[v].next[let - START];
		}
	}
}

bool win (bool outcome)
{
	cur_outcome = outcome;
	return play (0);
}

bool solve (const string [] s, int k)
{
	build (s);

	bool can_win = win (false);
	bool can_lose = win (true);
	debug {writeln (can_win, ' ', can_lose);}

	if (can_win && !can_lose)
	{
		return k & 1;
	}

	if (!can_win && can_lose)
	{
		return false;
	}

	if (can_win && can_lose)
	{
		return true;
	}

	if (!can_win && !can_lose)
	{
		return false;
	}

	assert (false);
}

void main ()
{
	int n;
	int k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto s = new string [n];
		foreach (ref x; s)
		{
			x = readln ().strip ();
		}

		writeln (solve (s, k) ? "First" : "Second");
	}
}

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

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

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

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

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

immutable LIM = 100_005;
immutable E = 26;

int N, K;
string[] A;

int V;
int[][] g;
int newNode() {
	g[V][] = -1;
	return V++;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		A = new string[N];
		foreach (i; 0 .. N) {
			A[i] = readToken;
		}

		V = 0;
		g = new int[][](LIM, E);
		newNode;
		foreach (i; 0 .. N) {
			int u = 0;
			foreach (c; A[i]) {
				const e = c - 'a';
				if (g[u][e] == -1) {
					g[u][e] = newNode;
				}
				u = g[u][e];
			}
		}

		int[] rts = new int[2];
		foreach (lf; 0 .. 2) {
			int[] dp = new int[V];
			foreach_reverse (u; 0 .. V) {
				bool isLeaf = true;
				dp[u] = 0;
				foreach (e; 0 .. E) {
					const v = g[u][e];
					if (v != -1) {
						isLeaf = false;
						if (!dp[v]) {
							dp[u] = 1;
						}
					}
				}
				if (isLeaf && lf) {
					dp[u] = 1;
				}
			}
debug{
writeln("dp = ",dp);
}
			rts[lf] = dp[0];
		}

		int k = K;
		if (k >= 100) {
			k -= (k - 100) / 2 * 2;
		}

		int r = 0;
		foreach (_; 0 .. k) {
			r = rts[r];
		}
		writeln(r ? "First" : "Second");

	}
	} catch (EOFException) {}
}

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

class Stack(T) {
	private Appender!(T[], T) app;
	private size_t size = 0;

	this() {
		app = appender(new T[0]);
	}

	void push(T value) {
		if (app.data().length > size) {
			app.data[size] = value;
		} else {
			app.put(value);
		}
		++size;
	}

	T get(size_t i) {
		return app.data[i];
	}

	T pop() {
		if (size == 0) {
			throw new RangeError();
		}
		return app.data[--size];
	}

	bool empty() {
		return size == 0;
	}

	size_t length() {
		return size;
	}
}

enum WinCond {
	unknown,
	W1, // first player can enforce a win
	W2  // second player can enforce a win
}
enum LoseCond {
	unknown,
	L1, // first player can enforce a lose
	L2 // second player can enforce a lose
}

class StringNode {
	public StringNode[char.max] edges = null;
	WinCond win_cond;
	LoseCond lose_cond;
}

void addString(StringNode root, string str) {
	foreach (ch; str) {
		if (root.edges[ch] is null) {
			root.edges[ch] = new StringNode;
		}
		root = root.edges[ch];
	}
}

void calculateWinLoseState(StringNode root) {
	// alias ReturnType = Tuple!(WinCond, LoseCond);
	auto stack = new Stack!StringNode;
	stack.push(root);

	for (size_t i = 0; i != stack.length(); ++i) {
		foreach (edge; stack.get(i).edges) {
			if (edge !is null) {
				stack.push(edge);
			}
		}
	}

	while (!stack.empty()) {
		auto node = stack.pop();
		assert(node.win_cond == WinCond.unknown);
		assert(node.lose_cond == LoseCond.unknown);
		bool no_edges = true;
		foreach (i, edge; node.edges) {
			if (edge !is null) {
				//write(cast(char)i, ", ");
				no_edges = false;
				assert(edge.win_cond != WinCond.unknown);
				assert(edge.lose_cond != LoseCond.unknown);
				if (edge.win_cond == WinCond.W2) {
					node.win_cond = WinCond.W1;
				}
				if (edge.lose_cond == LoseCond.L2) {
					node.lose_cond = LoseCond.L1;
				}
			}
		}
		if (node.win_cond == WinCond.unknown) {
			node.win_cond = WinCond.W2;
		}
		if (no_edges) {
			node.lose_cond = LoseCond.L1;
		} else if (node.lose_cond == LoseCond.unknown) {
			node.lose_cond = LoseCond.L2;
		}
		//writeln(": ", node.win_cond, " ", node.lose_cond);
	}
}

void main() {
	int n, k;
	readf("%s %s\n", &n, &k);
	auto root = new StringNode;
	foreach (_; 0..n) {
		string line;
		while (line.empty)
			line = readln().strip;
		addString(root, line);
	}
	calculateWinLoseState(root);
	enum first = "First";
	enum second = "Second";
	switch (root.win_cond) {
	default:
		assert(false);
	case WinCond.W1:
		switch(root.lose_cond) {
		default:
			assert(false);
		case LoseCond.L1:
			writeln(first);
			break;
		case LoseCond.L2:
			writeln(k % 2 == 0 ? second : first);
		}
		break;
	case WinCond.W2:
		writeln(second);
	}
}

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

const int MAX = 100005;
string[MAX] s;
int n, k;

struct Node {
    char c;
    Node*[char] children;
}

void main() {
    readf(" %s %s", n, k);
    readln();
    foreach(i; 0..n) s[i] = readln().chomp();

    auto root = new Node();
    foreach(i; 0..n) {
        auto cur = root;
        foreach(c; s[i]) {
            if (c !in cur.children) {
                auto node = new Node();
                node.c = c;
                cur.children[c] = node;
            }
            cur = cur.children[c];
        }
    }

    auto canWinMatch = root.children.values.any!(node => can(node, true));
    auto canLossMatch = root.children.values.any!(node => can(node, false));
    bool firstWin;
    if (!canWinMatch) {
        firstWin = false;
    } else if (canLossMatch) {
        firstWin = true;
    } else {
        firstWin = (k % 2 == 1);
    }
    writeln(firstWin ? "First" : "Second");
}

bool can(Node* node, bool win) {
    if (node.children.empty) {
        return win;
    }
    auto result = true;
    foreach(c; node.children.keys) {
        result &= (can(node.children[c], win) == false);
    }
    return result;
}

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

immutable int LET = 26;
immutable char START = 'a';
immutable int MAX_N = 100_005;
immutable int NA = -1;

struct Node
{
	int [LET] next = NA;
}

Node [MAX_N] t;
int m;
bool cur_outcome;

bool play (int v)
{
	assert (v != NA);

	bool ok = false;
	foreach (d; 0..LET)
	{
		if (t[v].next[d] != NA)
		{
			ok = true;
			if (!play (t[v].next[d]))
			{
				return true;
			}
		}
	}
	if (!ok)
	{
		return cur_outcome;
	}
	return false;
}

void build (const string [] s)
{
	debug {writeln (s);}
	t[] = Node.init;
	m = 1;
	foreach (cur; s)
	{
		int v = 0;
		foreach (let; cur)
		{
			debug {writeln (v, ' ', let - START);}
			if (t[v].next[let - START] == NA)
			{
				t[v].next[let - START] = m;
				m++;
			}
			v = t[v].next[let - START];
		}
	}
}

bool win (bool outcome)
{
	cur_outcome = outcome;
	return play (0);
}

bool solve (const string [] s, int k)
{
	build (s);

	bool can_win = win (false);
	bool can_lose = win (true);

	if (can_win && !can_lose)
	{
		return k & 1;
	}

	if (!can_win && can_lose)
	{
		return false;
	}

	return true;
}

void main ()
{
	int n;
	int k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto s = new string [n];
		foreach (ref x; s)
		{
			x = readln ().strip ();
		}

		writeln (solve (s, k) ? "First" : "Second");
	}
}

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

class Stack(T) {
	private Appender!(T[], T) app;
	private size_t size = 0;

	this() {
		app = appender(new T[0]);
	}

	void push(T value) {
		if (app.data().length > size) {
			app.data[size] = value;
		} else {
			app.put(value);
		}
		++size;
	}

	T get(size_t i) {
		return app.data[i];
	}

	T pop() {
		if (size == 0) {
			throw new RangeError();
		}
		return app.data[--size];
	}

	bool empty() {
		return size == 0;
	}

	size_t length() {
		return size;
	}
}

enum WinCond {
	unknown,
	W1, // first player can enforce a win
	W2  // second player can enforce a win
}
enum LoseCond {
	unknown,
	L1, // first player can enforce a lose
	L2 // second player can enforce a lose
}

class StringNode {
	public StringNode[char.max] edges = null;
	WinCond win_cond;
	LoseCond lose_cond;
}

void addString(StringNode root, string str) {
	foreach (ch; str) {
		if (root.edges[ch] is null) {
			root.edges[ch] = new StringNode;
		}
		root = root.edges[ch];
	}
}

void calculateWinLoseState(StringNode root) {
	// alias ReturnType = Tuple!(WinCond, LoseCond);
	auto stack = new Stack!StringNode;
	stack.push(root);

	for (size_t i = 0; i != stack.length(); ++i) {
		foreach (edge; stack.get(i).edges) {
			if (edge !is null) {
				stack.push(edge);
			}
		}
	}

	while (!stack.empty()) {
		auto node = stack.pop();
		assert(node.win_cond == WinCond.unknown);
		assert(node.lose_cond == LoseCond.unknown);
		bool no_edges = true;
		foreach (edge; node.edges) {
			if (edge !is null) {
				no_edges = false;
				assert(edge.win_cond != WinCond.unknown);
				assert(edge.lose_cond != LoseCond.unknown);
				if (edge.win_cond == WinCond.W2) {
					node.win_cond = WinCond.W1;
				}
				if (edge.lose_cond == LoseCond.L2) {
					node.lose_cond = LoseCond.L1;
				}
			}
		}
		if (node.win_cond == WinCond.unknown) {
			node.win_cond = WinCond.W2;
		}
		if (no_edges) {
			node.lose_cond = LoseCond.L1;
		} else {
			node.lose_cond = LoseCond.L2;
		}
	}
}

void main() {
	int n, k;
	readf(" %s %s ", &n, &k);
	auto root = new StringNode;
	foreach (_; 0..n) {
		string line;
		readf(" %s ", &line);
		addString(root, line.strip);
	}
	calculateWinLoseState(root);
	enum first = "First";
	enum second = "Second";
	switch (root.win_cond) {
	default:
		assert(false);
	case WinCond.W1:
		switch(root.lose_cond) {
		default:
			assert(false);
		case LoseCond.L1:
			writeln(first);
			break;
		case LoseCond.L2:
			writeln(k % 2 == 0 ? second : first);
		}
		break;
	case WinCond.W2:
		switch(root.lose_cond) {
		default:
			assert(false);
		case LoseCond.L1:
			writeln(k % 2 == 0 ? first : second);
			break;
		case LoseCond.L2:
			writeln(second);
		}
	}
}

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

const int MAX = 100005;
string[MAX] s;
int n, k;

struct Node {
    char c;
    Node*[char] children;
}

void main() {
    readf(" %s %s", n, k);
    readln();
    foreach(i; 0..n) s[i] = readln().chomp();

    auto root = new Node();
    foreach(i; 0..n) {
        auto cur = root;
        foreach(c; s[i]) {
            if (c !in cur.children) {
                auto node = new Node();
                node.c = c;
                cur.children[c] = node;
            }
            cur = cur.children[c];
        }
    }

    auto canWinMatch = root.children.values.any!(node => can(node, true));
    auto canLossMatch = root.children.values.any!(node => can(node, false));
    auto canWin = canWinMatch;
    foreach(i; 0..k-1) {
        canWin = (canLossMatch && canWin) || (canWinMatch && !canWin);
    }
    writeln(canWin ? "First" : "Second");
}

bool can(Node* node, bool win) {
    if (node.children.empty) {
        return win;
    }
    auto result = false;
    foreach(c; node.children.keys) {
        result &= (can(node.children[c], win) == false);
    }
    return result;
}

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

const int MAX = 100005;
string[MAX] s;
int n, k;

struct Node {
    char c;
    Node*[char] children;
}

void main() {
    readf(" %s %s", n, k);
    readln();
    foreach(i; 0..n) s[i] = readln().chomp();

    auto root = new Node();
    foreach(i; 0..n) {
        auto cur = root;
        foreach(c; s[i]) {
            if (c !in cur.children) {
                auto node = new Node();
                node.c = c;
                cur.children[c] = node;
            }
            cur = cur.children[c];
        }
    }

    auto canWinMatch = root.children.values.any!(node => can(node, true));
    auto canLossMatch = root.children.values.any!(node => can(node, false));
    auto canWin = canWinMatch;
    foreach(i; 0..k-1) {
        canWin = (canLossMatch && canWin) || (canWinMatch && !canWin);
    }
    writeln(canWin ? "First" : "Second");
}

bool can(Node* node, bool win) {
    if (node.children.empty) {
        return win;
    }
    auto result = false;
    foreach(c; node.children.keys) {
        result |= (can(node.children[c], win) == false);
    }
    return result;
}

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

const int MAX = 100005;
string[MAX] s;
int n, k;

struct Node {
    char c;
    Node*[char] children;
}

void main() {
    readf(" %s %s", n, k);
    readln();
    foreach(i; 0..n) s[i] = readln().chomp();

    auto root = new Node();
    foreach(i; 0..n) {
        auto cur = root;
        foreach(c; s[i]) {
            if (c !in cur.children) {
                auto node = new Node();
                node.c = c;
                cur.children[c] = node;
            }
            cur = cur.children[c];
        }
    }

    bool firstCanWin = root.children.values.any!(node => canWin(node));
    if (firstCanWin) {
        writeln(k % 2 == 0 ? "SECOND" : "FIRST");
    } else {
        writeln("SECOND");
    }
}

bool canWin(Node* node) {
    if (node.children.empty) {
        return true;
    }
    auto result = false;
    foreach(c; node.children.keys) {
        result |= (canWin(node.children[c]) == false);
    }
    return result;
}

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

const int MAX = 100005;
string[MAX] s;
int n, k;

struct Node {
    char c;
    Node*[char] children;
}

void main() {
    readf(" %s %s", n, k);
    readln();
    foreach(i; 0..n) s[i] = readln().chomp();

    auto root = new Node();
    foreach(i; 0..n) {
        auto cur = root;
        foreach(c; s[i]) {
            if (c !in cur.children) {
                auto node = new Node();
                node.c = c;
                cur.children[c] = node;
            }
            cur = cur.children[c];
        }
    }

    bool firstCanWin = root.children.values.any!(node => canWin(node));
    if (firstCanWin) {
        writeln(k % 2 == 0 ? "Second" : "First");
    } else {
        writeln("Second");
    }
}

bool canWin(Node* node) {
    if (node.children.empty) {
        return true;
    }
    auto result = false;
    foreach(c; node.children.keys) {
        result |= (canWin(node.children[c]) == false);
    }
    return result;
}


Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.  It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.

import std.math;
import std.stdio;

int n;

int main ()
{
	while ((readf (" %d", &n) >= 0) && !stdin.eof ())
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %d", &a[i]);
		}

		auto r = new bool [n];
		r[] = true;
		auto s = a[n - 1];
		for (auto i = n - 2; i >= 0; i--)
		{
			if (s > 0)
			{
				r[i] = false;
				s -= a[i];
			}
			else
			{
				r[i] = true;
				s += a[i];
			}
			assert (abs (s) <= a[i]);
		}

		if (s < 0)
		{
			r[] = r[] ^ 1;
		}

		foreach (i; 0..n)
		{
			writef ("%s", r[i] ? '+' : '-');
		}
		writef ("\n");
	}
	return 0;
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto a = next!int(n);
  auto df = new byte[](n);
  df[n - 1] = 0;
  int sum = a[n - 1];
  foreach_reverse(i; 0 .. n - 1)
    {
      auto ai = a[i];
      assert(sum >= 0 && sum <= a[i + 1]);
      if (sum >= ai) {df[i] = 1; df[i + 1] ^= 1; sum = sum - ai;}
      else {df[i] = 0; df[i + 1] ^= 1; sum = ai - sum;}
    }
  auto f = new byte[](n);
  f[0] = df[0];
  foreach(i; 1 .. n)
    f[i] = f[i - 1] ^ df[i];
  f.map!(fi => fi == 0? '+' : '-').each!write, writeln;
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.

The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).

The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
@property pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow @property X binpow(X,Y)(X base,Y exp)
if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @property auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
@property void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
	}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p) if(is(A:X) && is(B:Y))
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(A,B)(in pair!(A,B) s_) const pure nothrow @safe if(is(typeof(s_.fi<fi)==bool) && is(typeof(s_.se<se)==bool))
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;
	while(input(&n))
	{
		if(n&1)
		{
			writeln((n-3)/2+1);
			write(3,' ');
			foreach(i;0..(n-3)/2)write(2,' ');
		}
		else
		{
			writeln(n/2);
			foreach(i;0..n/2)write(2,' ');
		}
	}
	debug system("pause");
}

import std.stdio;
import std.string;

int main()
{
	int a=0;
	readf(" %d", &a);
	if (a%2==0)
	{
		writeln(a/2);
		for (int i=0; i<a/2; i++)
		{
			writeln(2);
		}
	}
	else
	{
		writeln(a/2);
		for (int i=0; i<a/2-1; i++)
		{
			writeln(2);
		}
		writeln(3);
	}
	return 0;
}


Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) — the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) — the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) — the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.

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

void solve() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(x => x.to!int-1).array;
    auto B = readln.split.map!(x => x.to!int-1).array;
    auto C = new int[](N);
    foreach (i; 0..N) C[A[i]] = i;
    long ans = 0;
    int mx = -1;
    long cnt = 0;

    foreach (b; B) {
        if (C[b] < mx) {
            ans += 1;
        } else {
            mx = C[b];
            ans += (C[b] - cnt) * 2 + 1;
        }
        cnt += 1;
    }

    ans.writeln;
}

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

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  auto nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    immutable m = r.next!uint;
    auto a = r.nextA!uint (n);
    auto b = r.nextA!uint (m);
    a[] -= 1;
    b[] -= 1;
    auto rank = new uint[n];
    foreach (i; 0 .. n) {
      rank[a[i]] = i;
    }
    long res = m;
    int e;
    int cur;
    foreach (i; 0 .. m) {
      if (rank[b[i]] > cur) {
        cur = rank[b[i]];
        res += 2 * (rank[b[i]] + e);
      }
      --e;
    }
    writeln (res);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint, m = rint;
		long[] as = rlong(n).map!(x => x - 1).array;
		long[] bs = rlong(m).map!(x => x - 1).array;
		log("as:", as);
		log("bs:", bs);

		long[long] az;
		foreach(i, a; as) az[a] = i.to!long;
		log("az:", az);

		long[] us = bs.map!(x => az[x]).array;
		log("us:", us);

		long ans;
		long umax = 0;
		foreach(i, u; us){
			if(u < umax) ans += 1;
			else{
				ans += (u - i) *2 + 1;
				umax = u;
			}
			log("i:", i, "u:", u, "umax:", umax, "ans:", ans);
		}
		ans.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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA!int;
		auto b = RDA!int;
		bool[int] set;
		long cnt;
		foreach (i; 0..m)
		{
			if (set.get(b[i], false))
			{
				++cnt;
				set.remove(b[i]);
				continue;
			}
			cnt += set.length*2;
			while (a.front != b[i])
			{
				set[a.front] = true;
				a.popFront;
				cnt += 2;
			}
			a.popFront;
			++cnt;
			debug writeln("cnt:", cnt);
		}
		ans[ti] = cnt;
	}

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

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint, m = rint;
		int[] as = rint(n).map!(x => x - 1).array;
		int[] bs = rint(m).map!(x => x - 1).array;
		log("as:", as);
		log("bs:", bs);

		int[] az = new int[](n);
		foreach(int i, a; as) az[a] = i;
		log("az:", az);

		int[] us = bs.map!(x => az[x]).array;
		log("us:", us);

		int ans;
		int umax = 0;
		foreach(int i, u; us){
			if(u < umax) ans += 1;
			else{
				ans += (u - i) *2 + 1;
				umax = u;
			}
			log("i:", i, "u:", u, "umax:", umax, "ans:", ans);
		}
		ans.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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA!int;
		auto b = RDA!int;
		bool[int] set;
		int cnt;
		foreach (i; 0..m)
		{
			if (set.get(b[i], false))
			{
				++cnt;
				set.remove(b[i]);
				continue;
			}
			cnt += set.length*2;
			while (a.front != b[i])
			{
				set[a.front] = true;
				a.popFront;
				cnt += 2;
			}
			a.popFront;
			++cnt;
			debug writeln("cnt:", cnt);
		}
		ans[ti] = cnt;
	}

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


You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).

For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.

NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$  $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$  $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$

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 m = RD!int;
		auto a = new int[][](min(n, m));
		foreach (i; 0..n)
		{
			if (n <= m)
				a[i] = RDA!int;
			else
			{
				auto tmp = RDA!int;
				foreach (j; 0..m)
				{
					a[j] ~= tmp[j];
				}
			}
		}
		if (m < n)
			swap(n, m);

		debug writeln(a);
		foreach (i; 0..(n+m-1)/2)
		{
			int cnt, loop;
			foreach (j; 0..min(i+1, n))
			{
				cnt += a[j][i-j];
				cnt += a[n-j-1][m-i-1+j];
				++loop;
			}
			loop *= 2;
			ans[ti] += min(cnt, loop-cnt);
			debug writeln("i:", i, " cnt:", cnt, " loop:", loop, " ans[ti]:", ans[ti]);
		}
	}

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