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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		auto b = readln.splitter.map !(to !(int)).array;
		b[] -= 1;

		auto p = new int [n];
		foreach (i; 0..n)
		{
			p[a[i]] = i;
		}
		auto q = new int [n];
		foreach (i; 0..n)
		{
			q[b[i]] = i;
		}
		auto c = new int [n];
		foreach (i; 0..n)
		{
			c[p[i]] = q[i];
		}

		long res = 0;
		int lo = 0;
		int hi = n - 1;
		foreach (i; 0..n)
		{
			if (c[i] != NA)
			{
				int len = 0;
				int x = i;
				while (c[x] != NA)
				{
					len += 1;
					int y = c[x];
					c[x] = NA;
					x = y;
				}
				len /= 2;
/*
				 5 4 3 4
				1 6 2 5 1
				+10 +6
*/
				foreach (step; 0..len)
				{
					res += hi - lo;
					lo += 1;
					hi -= 1;
				}
			}
		}
		writeln (res * 2);
	}
}

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

        auto uf = new int[N];
        uf[] = -1;
        foreach (i; 0 .. N) {
          uf.connect(A[i], B[i]);
        }

        int[] cs;
        foreach (r; 0 .. N) if (uf[r] < 0) {
          cs ~= -uf[r];
        }
        cs.sort.reverse;
        debug {
          writeln("cs = ", cs);
        }

        long ans;
        {
          int num;
          int l = 0, r = N - 1;
          int next() {
            return (num++ % 2 == 0) ? l++ : r--;
          }
          foreach (c; cs) {
            const cc = c / 2 * 2;
            if (cc <= 1) continue;
            const s = next();
            int u = s;
            foreach (_; 1 .. cc) {
              const v = next();
              ans += abs(u - v);
              u = v;
            }
            ans += abs(u - s);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

        auto uf = new int[N];
        uf[] = -1;
        foreach (i; 0 .. N) {
          uf.connect(A[i], B[i]);
        }

        int[] cs;
        foreach (r; 0 .. N) if (uf[r] < 0) {
          cs ~= -uf[r];
        }
        cs.sort.reverse;
        debug {
          writeln("cs = ", cs);
        }

        long ans;
        {
          int num;
          int l = 0, r = N - 1;
          int next() {
            return (num++ % 2 == 0) ? l++ : r--;
          }
          foreach (c; cs) {
            const s = next();
            int u = s;
            foreach (_; 1 .. c) {
              const v = next();
              ans += abs(u - v);
              u = v;
            }
            ans += abs(u - s);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

        auto uf = new int[N];
        uf[] = -1;
        foreach (i; 0 .. N) {
          uf.connect(A[i], B[i]);
        }

        int[] cs;
        foreach (r; 0 .. N) if (uf[r] < 0) {
          if (-uf[r] >= 2) {
            cs ~= -uf[r];
          }
        }
        cs.sort;
        debug {
          writeln("cs = ", cs);
        }

        long ans;
        {
          int num;
          int l = 0, r = N - 1;
          int next() {
            return (num++ % 2 == 0) ? l++ : r--;
          }
          foreach (c; cs) {
            const s = next();
            int u = s;
            foreach (_; 0 .. c - 1) {
              const v = next();
              ans += abs(u - v);
              u = v;
            }
            ans += abs(u - s);
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


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.stdio,std.variant,
	core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;immutable int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	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))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return 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 foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
/*loop:while(read(n,k))
	{*/
	read(n,k);
		int m;
		read(m);
		auto g=new pii[][n+1];
		foreach(i;0..m)
		{
			int u,v,c;
			read(u,v,c);
			g[u]~=mp(v,c);
			//g[v]~=mp(u,c);
		}
		auto dp=new int[81][81][81][81];
		int go(int v,int l,int r,int h)
		{
			if(h==k)return 0;
			if(dp[v][l][r][h])return dp[v][l][r][h];
			int ans=1000000;
			foreach(x; g[v]) {
				if(x.fi<l || x.fi>r)continue;
				if(x.fi<v)
				{
					ans=min(ans,x.se+go(x.fi,l,v-1,h+1));
				}
				else ans=min(ans,x.se+go(x.fi,v+1,r,h+1));
			}
			return dp[v][l][r][h]=ans;
		}
		int ans=1000000;
		foreach(i;1..n+1)
		{
			ans=min(ans,go(i,1,n,1));
		}
		if(ans>=1000000)writeln(-1);
		else writeln(ans);
	//}
}

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

immutable int infinity = int.max / 4;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		n += 2;
		int m;
		readf (" %s", &m);
		auto u = new int [m];
		auto v = new int [m];
		auto c = new int [m];
		auto d = new int [] [] (n, n);
		foreach (ref dLine; d)
		{
			dLine[] = infinity;
		}
		foreach (i; 0..m)
		{
			readf (" %s %s %s", &u[i], &v[i], &c[i]);
			d[u[i]][v[i]] = min (d[u[i]][v[i]], c[i]);
		}

		auto f = new int [2] [] [] [] (2, n, n);
		int b = 0;
		foreach (ref fLine; f[b])
		{
			fLine[] = [infinity, infinity];
		}
		foreach (i; 0..n)
		{
			f[b][0][i][1] = 0;
			f[b][i][n - 1][0] = 0;
		}

		foreach (step; 0..k - 1)
		{
			b ^= 1;
			foreach (ref fLine; f[b])
			{
				fLine[] = [infinity, infinity];
			}
			foreach (i; 0..n)
			{
				foreach (j; i..n)
				{
					// from [i* -- j]
					int cur0 = f[!b][i][j][0];
					// from [i -- *j]
					int cur1 = f[!b][i][j][1];
					debug {writeln (step, " ", i, " ",
					    j, ": ", cur0, " ", cur1);}
					if (cur0 != infinity)
					{
						foreach (p; i + 1..j)
						{
							// to [i -- *p]
							f[b][i][p][1] =
							    min (f[b][i][p][1],
							    cur0 + d[i][p]);
							// to [p* -- j]
							f[b][p][j][0] =
							    min (f[b][p][j][0],
							    cur0 + d[i][p]);
						}
					}
					if (cur1 != infinity)
					{
						foreach (p; i + 1..j)
						{
							// to [p* -- j]
							f[b][p][j][0] =
							    min (f[b][p][j][0],
							    cur1 + d[j][p]);
							// to [i -- *p]
							f[b][i][p][1] =
							    min (f[b][i][p][1],
							    cur1 + d[j][p]);
						}
	                        	}
				}
			}
		}

		int res = infinity;
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				res = min (res, f[b][i][j][0], f[b][i][j][1]);
			}
		}
		if (res == infinity)
		{
			res = -1;
		}
		writeln (res);
	}
}

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.stdio,std.variant,
	core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;immutable int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	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))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return 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 foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	auto dp=new int[81][81][81][81];
	int n,k;
loop:while(read(n,k))
	{
		int m;
		read(m);
		auto g=new pii[][n+1];
		foreach(i;0..m)
		{
			int u,v,c;
			read(u,v,c);
			g[u]~=mp(v,c);
			//g[v]~=mp(u,c);
		}

		int go(int v,int l,int r,int h)
		{
			if(h==k)return 0;
			if(dp[v][l][r][h])return dp[v][l][r][h];
			int ans=1000000;
			foreach(x; g[v]) {
				if(x.fi<l || x.fi>r)continue;
				if(x.fi<v)
				{
					ans=min(ans,x.se+go(x.fi,l,v-1,h+1));
				}
				else ans=min(ans,x.se+go(x.fi,v+1,r,h+1));
			}
			return dp[v][l][r][h]=ans;
		}
		int ans=1000000;
		foreach(i;1..n+1)
		{
			ans=min(ans,go(i,1,n,1));
		}
		if(ans>=1000000)writeln(-1);
		else writeln(ans);
	}
}

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.stdio,std.variant,
	core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;immutable int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	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))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return 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 foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	auto dp=new int[81][81][81][81];
	int n,k;
	auto g=new pii[][80+1];
loop:while(read(n,k))
	{
		int m;
		read(m);

		foreach(i;0..m)
		{
			int u,v,c;
			read(u,v,c);
			g[u]~=mp(v,c);
			//g[v]~=mp(u,c);
		}

		int go(int v,int l,int r,int h)
		{
			if(h==k)return 0;
			if(dp[v][l][r][h])return dp[v][l][r][h];
			int ans=1000000;
			foreach(x; g[v]) {
				if(x.fi<l || x.fi>r)continue;
				if(x.fi<v)
				{
					ans=min(ans,x.se+go(x.fi,l,v-1,h+1));
				}
				else ans=min(ans,x.se+go(x.fi,v+1,r,h+1));
			}
			return dp[v][l][r][h]=ans;
		}
		int ans=1000000;
		foreach(i;1..n+1)
		{
			ans=min(ans,go(i,1,n,1));
		}
		if(ans>=1000000)writeln(-1);
		else writeln(ans);
	}
}

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.stdio,std.variant,
	core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;immutable int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	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))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n=a.length,in size_t m=a.front.length)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return 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 foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
loop:while(read(n,k))
	{
		int m;
		read(m);
		auto g=new pii[][n+1];
		foreach(i;0..m)
		{
			int u,v,c;
			read(u,v,c);
			g[u]~=mp(v,c);
			g[v]~=mp(u,c);
		}
		auto dp=new int[80][80][80][80];
		int go(int v,int l,int r,int h)
		{
			if(h==k)return 0;
			if(dp[v][l][r][h])return dp[v][l][r][h];
			int ans=1000000;
			foreach(x; g[v]) {
				if(x.fi<l || x.fi>r)continue;
				if(x.fi<v)
				{
					ans=min(ans,x.se+go(x.fi,l,v-1,h+1));
				}
				else ans=min(ans,x.se+go(x.fi,v+1,r,h+1));
			}
			return dp[v][l][r][h]=ans;
		}
		int ans=1000000;
		foreach(i;1..n+1)
		{
			ans=min(ans,go(i,1,n,1));
		}
		if(ans>=1000000)writeln(-1);
		else writeln(ans);
	}
}

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

immutable int infinity = int.max / 4;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		n += 2;
		int m;
		readf (" %s", &m);
		auto u = new int [m];
		auto v = new int [m];
		auto c = new int [m];
		auto d = new int [] [] (n, n);
		foreach (ref dLine; d)
		{
			dLine[] = infinity;
		}
		foreach (i; 0..m)
		{
			readf (" %s %s %s", &u[i], &v[i], &c[i]);
			d[u[i]][v[i]] = min (d[u[i]][v[i]], c[i]);
		}

		auto f = new int [2] [] [] [] (2, n, n);
		int b = 0;
		foreach (ref fLine; f[b])
		{
			fLine[] = [infinity, infinity];
		}
		foreach (i; 0..n)
		{
			f[b][0][i][1] = 0;
			f[b][i][n - 1][0] = 0;
		}

		foreach (step; 0..k - 1)
		{
			b ^= 1;
			foreach (ref fLine; f[b])
			{
				fLine[] = [infinity, infinity];
			}
			foreach (i; 0..n)
			{
				foreach (j; i..n)
				{
					// from [i* -- j]
					int cur0 = f[!b][i][j][0];
					// from [i -- *j]
					int cur1 = f[!b][i][j][1];
					debug {writeln (step, " ", i, " ",
					    j, ": ", cur0, " ", cur1);}
					if (cur0 != infinity)
					{
						foreach (p; i + 1..j)
						{
							// to [i -- *p]
							f[b][i][p][1] =
							    min (f[b][i][p][1],
							    cur0 + d[i][p]);
						}
					}
					if (cur1 != infinity)
					{
						foreach (p; i + 1..j)
						{
							// to [p* -- j]
							f[b][p][j][0] =
							    min (f[b][p][j][0],
							    cur1 + d[j][p]);
						}
	                        	}
				}
			}
		}

		int res = infinity;
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				res = min (res, f[b][i][j][0], f[b][i][j][1]);
			}
		}
		if (res == infinity)
		{
			res = -1;
		}
		writeln (res);
	}
}


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 = single;
struct TestCase
{
  mixin prettyPrinting;

  long n, m;
  @("n") string[] str;

  void solve(long tc = -1)
  {
    auto pairs = appender!(Tuple!(long, long)[])();
    string pal = "";
  fori:foreach(i; 0 .. n)
      {
      forj:foreach(j; i + 1 .. n)
          {
            if (iota(0, m).all!(k => str.at(i).at(k) == str.at(j).at(m - 1 - k)))
              {
                pairs.put(tuple(i, j));
                continue fori;
              }
          }
        if (iota(0, m).all!(k => str.at(i).at(k) == str.at(i).at(m - 1 - k)))
          pal = str.at(i);
      }
    auto res = pairs[].fold!((curr, pair) => str.at(pair[0]) ~ curr ~ str.at(pair[1]))(pal).array.toUTF8;
    writeln(res.length);
    writeln(res);
  }
}

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 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, string))
              {
                static assert(isDynamicArray!(typeOfField)
                              , " A field with dimension initialization UDA must be a dynamic array.");
                enum uda = getUDAs!(fieldSymbol, string)[0];
                mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda, q{)});
              }
            else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
              {
                pragma(msg, "Warning: You probably want to add dimension to input ", 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.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(){
	int n = rint, m = rint;

	bool[string] sz;
	string[] us;
	string v;
	foreach(i; 0 .. n){
		string s = readln.chomp;
		string t = "";
		foreach_reverse(c; s) t ~= c;
		if(t in sz) us ~= s;
		else if(s == t) v = s;
		sz[s] = 1;
	}

	string ans;
	foreach(u; us) ans ~= u;
	ans ~= v;
	foreach_reverse(u; us) foreach_reverse(c; u) ans ~= c;

	(us.length * 2 * m + v.length).writeln;
	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; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto s = new string[](n);
	int[string] set, set2;
	string ans1, ans2;
	foreach (i; 0..n)
	{
		s[i] = RD!string;
		auto tt = s[i].dup;
		tt.reverse;
		auto t = tt.idup;
		if (set.get(s[i], 0))
		{
			ans1 ~= s[i];
			ans2 = (t ~ ans2).idup;
			--set[s[i]];
		}
		else
		{
			bool ok = true;
			foreach (j; 0..m/2)
			{
				if (s[i][j] != s[i][$-j-1])
					ok = false;
			}
			if (ok)
				++set2[s[i]];
			else
				++set[t];
		}
	}

	string bestKey;
	long cnt;
	foreach (key; set2.keys)
	{
		if (set2[key] > cnt)
		{
			cnt = set2[key];
			bestKey = key;
		}
	}
	auto ans = ans1;
	foreach (i; 0..cnt)
	{
		ans ~= bestKey;
	}
	ans ~= ans2;
	writeln(ans.length);
	writeln(ans);
	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(){
	int n = rint, m = rint;

	bool[string] sz;
	string[] us;
	string v;
	foreach(i; 0 .. n){
		string s = readln.chomp;
		string t = "";
		foreach_reverse(c; s) t ~= c;
		if(t in sz) us ~= s;
		else if(s == t) v = s;
		sz[s] = 1;
	}

	string ans;
	foreach(u; us) ans ~= u;
	ans ~= v;
	foreach(u; us) foreach_reverse(c; u) ans ~= c;

	(us.length * 2 * m + v.length).writeln;
	ans.writeln;

}


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

alias Path = Tuple!(int, "to", bool, "c");

Path[][10^^5] GP;

void main()
{
    auto N = readln.chomp.to!int;
    int root;
    foreach (int i; 0..N) {
        auto pc = readln.split.to!(int[]);
        if (pc[0] == -1) {
            root = i;
        } else {
            GP[pc[0]-1] ~= Path(i, pc[1] == 1);
        }
    }

    auto ss = [Path(root, false)];
    int[] rs;
    while (!ss.empty) {
        auto head = ss[0];
        ss = ss[1..$];
        if (head.c) {
            bool del = true;
            foreach (path; GP[head.to]) {
                if (!path.c) del = false;
                ss ~= path;
            }
            if (del) rs ~= head.to + 1;
        } else {
            ss ~= GP[head.to];
        }
    }
    sort(rs);
    writeln(rs.empty ? "-1" : rs.to!(string[]).join(" "));
}

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!uint;
  auto p = new int[n+1];
  auto c = new int[n+1];
  auto good = new bool[n+1];
  debug stderr.writeln (n);
  foreach (i; 1 .. n+1) {
    p[i] = r.next!int;
    c[i] = r.next!uint;
    debug stderr.writeln (p[i], ' ', c[i]);
    if (!c[i]) {
      if (p[i] >= 0) {
        good[p[i]] = true;
      }
    }
  }
  int[] z;
  foreach (i; 1 .. n + 1) {
    if (!good[i] && c[i]) {
      z ~= i;
    }
  }
  if (z.empty) writeln (-1);
  else writefln ("%(%s %)", z);
}

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

alias Path = Tuple!(int, "to", bool, "c");

Path[][10^^5] GP;

void main()
{
    auto N = readln.chomp.to!int;
    int root;
    foreach (int i; 0..N) {
        auto pc = readln.split.to!(int[]);
        if (pc[0] == -1) {
            root = i;
        } else {
            GP[pc[0]-1] ~= Path(i, pc[1] == 1);
        }
    }

    auto ss = [Path(root, false)];
    int[] rs;
    while (!ss.empty) {
        auto head = ss[0];
        ss = ss[1..$];
        if (head.c) {
            bool del = true;
            foreach (path; GP[head.to]) {
                if (!path.c) del = false;
                ss ~= path;
            }
            if (del) rs ~= head.to + 1;
        } else {
            ss ~= GP[head.to];
        }
    }
    writeln(rs.empty ? "-1" : rs.to!(string[]).join(" "));
}


import std.algorithm, std.stdio;

long merge (int [] a, int [] b, int [] c)
{
	long res;
	foreach (ref x; c)
	{
		if (a.length && (!b.length || a[0] <= b[0]))
		{
			x = a[0];
			a = a[1..$];
		}
		else
		{
			res += a.length;
			x = b[0];
			b = b[1..$];
		}
	}
	return res;
}

void main ()
{
	int n;
	readf (" %s", &n);
	int m = 1 << n;
	auto a = new int [m];
	auto b = new int [m];
	foreach (ref x; a)
		readf (" %s", &x);

	auto s = new long [2] [n + 1];
	long res;
	foreach (i; 0..n)
	{
		int p = 1 << i;
		int lo, me, hi;
		for (lo = 0; lo < m; lo = hi)
		{
			me = lo + p;
			hi = me + p;
			s[i + 1][0] += merge (a[lo..me], a[me..hi], b[lo..hi]);
			s[i + 1][1] += merge (a[me..hi], a[lo..me], b[lo..hi]);
			a[lo..hi] = b[lo..hi];
		}
		res += s[i + 1][0];
	}

	int q;
	readf (" %s", &q);
	foreach (r; 0..q)
	{
		int x;
		for (readf (" %s", &x); x; x--)
		{
			res -= s[x][0];
			swap (s[x][0], s[x][1]);
			res += s[x][0];
                }
		writeln (res);
	}
}

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;

long merge (int [] a, int [] b, int [] c)
{
	long res = 0;
	foreach (p; 0..c.length)
	{
		if (a.length > 0 && (b.length == 0 || a[0] <= b[0]))
		{
			c[p] = a[0];
			a = a[1..$];
		}
		else
		{
			res += cast (long) (a.length);
			c[p] = b[0];
			b = b[1..$];
		}
		p++;
	}
	return res;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int m = 1 << n;
		auto a = new int [m];
		auto b = new int [m];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}

		long [2] [] s = new long [2] [n + 1];
		s[] = [0, 0];
		long res = s[0][0];
		foreach (i; 0..n)
		{
			int p = 1 << i;
			for (int k = 0; k < m; k += p * 2)
			{
				s[i + 1][0] += merge (a[k..k + p],
				                      a[k + p..k + p * 2],
				                      b[k..k + p * 2]);
				s[i + 1][1] += merge (a[k + p..k + p * 2],
				                      a[k..k + p],
				                      b[k..k + p * 2]);
				a[k..k + p * 2] = b[k..k + p * 2];
			}
			res += s[i + 1][0];
			debug {writeln (s[i + 1]);}
			debug {writeln (a);}
		}

		int q;
		readf (" %s", &q);
		foreach (r; 0..q)
		{
			int x;
			readf (" %s", &x);
			for ( ; x >= 0; x--)
			{
				res -= s[x][0];
				swap (s[x][0], s[x][1]);
				res += s[x][0];
	                }
			writeln (res);
		}
	}
}

import std.algorithm;
import std.stdio;

long merge (int [] a, int [] b, int [] c)
{
	long res = 0;
	foreach (p; 0..c.length)
	{
		if (a.length > 0 && (b.length == 0 || a[0] <= b[0]))
		{
			c[p] = a[0];
			a = a[1..$];
		}
		else
		{
			res += cast (long) (a.length);
			c[p] = b[0];
			b = b[1..$];
		}
		p++;
	}
	return res;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int m = 1 << n;
		auto a = new int [m];
		auto b = new int [m];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}

		long [2] [] s = new long [2] [n + 1];
		s[] = [0, 0];
		long res = s[0][0];
		foreach (i; 0..n)
		{
			int p = 1 << i;
			for (int k = 0; k < m; k += p * 2)
			{
				s[i + 1][0] += merge (a[k..k + p], a[k + p..k + p * 2], b[k..k + p * 2]);
				s[i + 1][1] += merge (a[k + p..k + p * 2], a[k..k + p], b[k..k + p * 2]);
				a[k..k + p * 2] = b[k..k + p * 2];
			}
			res += s[i + 1][0];
		}

		int q;
		readf (" %s", &q);
		foreach (r; 0..q)
		{
			int x;
			readf (" %s", &x);
			for ( ; x >= 0; x--)
			{
				res -= s[x][0];
				swap (s[x][0], s[x][1]);
				res += s[x][0];
	                }
			writeln (res);
		}
	}
}

import std.algorithm, std.stdio;

long merge (int [] a, int [] b, int [] c)
{
	long res;
	foreach (ref x; c)
	{
		if (a.length && (!b.length || a[0] <= b[0]))
		{
			x = a[0];
			a = a[1..$];
		}
		else
		{
			res += a.length;
			x = b[0];
			b = b[1..$];
		}
	}
	return res;
}

void main ()
{
	int n;
	readf (" %s", &n);
	int m = 1 << n;
	auto a = new int [m];
	auto b = new int [m];
	foreach (ref x; a)
		readf (" %s", &x);

	long [2] [] s = new long [2] [n + 1];
	long res;
	foreach (i; 0..n)
	{
		int p = 1 << i;
		int lo, me, hi;
		for (lo = 0; lo < m; lo = hi)
		{
			me = lo + p;
			hi = me + p;
			s[i + 1][0] += merge (a[lo..me], a[me..hi], b[lo..hi]);
			s[i + 1][1] += merge (a[me..hi], a[lo..me], b[lo..hi]);
			a[lo..hi] = b[lo..hi];
		}
		res += s[i + 1][0];
	}

	int q;
	readf (" %s", &q);
	foreach (r; 0..q)
	{
		int x;
		for (readf (" %s", &x); x; x--)
		{
			res -= s[x][0];
			swap (s[x][0], s[x][1]);
			res += s[x][0];
                }
		writeln (res);
	}
}


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 bool[](t);
	foreach (ti; 0..t)
	{
		auto p = RD!string;
		auto h = RD!string;
		auto cnt1 = new int[](26);
		foreach (c; p)
			++cnt1[c-'a'];

		auto cnt2 = new int[][](h.length+1, 26);
		foreach (i, c; h)
		{
			cnt2[i+1] = cnt2[i].dup;
			++cnt2[i+1][c-'a'];
		}
		foreach (i; p.length..h.length+1)
		{
			bool ok = true;
			foreach (j; 0..26)
			{
				if (cnt2[i][j] - cnt2[i-p.length][j] != cnt1[j])
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				ans[ti] = true;
				break;
			}
		}
	}

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

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

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

    auto A = new int[](26);
    auto B = new int[](26);

    bool ok() {
        return 26.iota.map!(i => A[i] >= B[i]).all;
    }

    while (T--) {
        A[] = 0;
        B[] = 0;
        auto P = readln.chomp;
        auto S = readln.chomp;
        if (P.length > S.length) {
            writeln("NO");
            continue;
        }
        foreach (p; P) A[p-'a'] += 1;
        foreach (i; 0..P.length) B[S[i]-'a'] += 1;
        if (ok) {
            writeln("YES");
            continue;
        }
        bool hoge = false;
        foreach (i; P.length..S.length) {
            B[S[i]-'a'] += 1;
            B[S[i-P.length.to!int]-'a'] -= 1;
            if (ok) {
                writeln("YES");
                hoge = true;
                break;
            }
        }
        if (!hoge) {
            writeln("NO");
        }
    }
}


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

alias Pair = Tuple!(int, q{a}, int, q{b});

void main() {
  int n, m;
  readf(" %s %s", &n, &m);
  Pair[] edges;
  foreach (i; 0..m) {
    int u, v;
    readf(" %s %s", &u, &v);
    u--; v--;
    edges ~= Pair(u, v);
  }

  bool can(int x) {
    auto adj = new int[][](n);
    auto inDegree = new int[n];
    foreach (i; 0..x) {
      adj[edges[i].a] ~= edges[i].b;
      inDegree[edges[i].b]++;
    }

    int cur = -1;
    int visited = 0;
    foreach (i; 0..n) {
      if (inDegree[i] == 0) {
        if (cur != -1) {
          return false;
        }
        cur = i;
      }
    }

    while (visited < n && cur != -1) {
      int next = -1;
      foreach (v; adj[cur]) {
        inDegree[v]--;
        if (inDegree[v] == 0) {
          if (next != -1) {
            return false;
          }
          next = v;
        }
      }
      visited++;
      cur = next;
    }

    return visited == n;
  }

  int lo = -1, hi = m + 1;
  while (lo + 1 < hi) {
    int mid = (lo + hi) >> 1;
    if (can(mid)) hi = mid;
    else lo = mid;
  }

  writeln(hi == m + 1 ? -1 : hi);
}

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

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

		auto b = new bool [n];
		b[] = false;
		int [] order;
		int cur = 0;

		void recur (int u)
		{
			if (b[u])
			{
				return;
			}
			b[u] = true;
			foreach (k, v; a[u])
			{
				recur (k);
			}
			order ~= u;
		}

		foreach (i; 0..n)
		{
			recur (i);
		}

		assert (order.length == n);
		int res = 0;
		foreach (i; 1..n)
		{
			auto t = order[i - 1] in a[order[i]];
			if (t is null)
			{
				res = m + 1;
			}
			else
			{
				res = max (res, (*t) + 1);
			}
		}

		if (res > m)
		{
			res = -1;
		}
		writeln (res);
	}
}


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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok;
		foreach (i; 1..n)
		{
			auto d = a[i] - a[i-1];
			if (d.abs > 1)
				ok = true;
		}
		if (ok) continue;

		bool[long] used;
		foreach (i; 0..n)
			used[a[i]] = true;
		if (used.length == 1)
			ans[ti] = min(v * 2, u + v);
		else
			ans[ti] = min(u, v);
	}

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

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

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

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

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

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

        bool bad = true;
        bool same = true;
        foreach (i; 0 .. N - 1) {
          bad = bad && (abs(A[i + 1] - A[i]) <= 1);
          same = same && (abs(A[i + 1] - A[i]) <= 0);
        }
        long ans;
        if (bad) {
          if (same) {
            ans = min(V + V, V + U);
          } else {
            ans = min(V, U);
          }
        } else {
          ans = 0;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, u, v;
		readf !(" %s %s %s") (n, u, v);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto d = 0;
		foreach (i; 1..n)
		{
			d = max (d, abs (a[i] - a[i - 1]));
		}
		int res = 0;
		if (d <= 0)
		{
			res += v;
		}
		if (d <= 1)
		{
			res += min (u, v);
		}
		writeln (res);
	}
}


import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		readf(" %d", &a);
		readf(" %d", &b);
		writeln(a+b);
	}
	return 0;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.splitter.map !(to !(int)).sum.writeln;
	}
}

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

void main() {
    int t; scan(t);
    foreach (_; 0..t) {
        int a, b; scan(a, b);
        writeln(a + b);
    }
}

void scan(T...)(ref T a) {
    string[] ss = readln.split;
    foreach (i, t; T) a[i] = ss[i].to!t;
}
T read(T=string)() { return readln.chomp.to!T; }
T[] reads(T)() { return readln.split.to!(T[]); }
alias readints = reads!int;

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

void main() {

}


import std;

uint
query (size_t index) {
    writefln("? %s", index + 1);
    stdout.flush;

    uint response;
    readf(" %s", response);
    return response - 1;
}

void
print(in uint[] p) {
    writefln("! %(%s %)\n", p);
    stdout.flush;
}

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = () { uint n; readf!" %s"(n); return n; }();

        uint[] p = new uint[n];

        uint steps = 0;
        foreach (i, val; p)
            if (val == 0) {
                uint[] vec;
                uint start = query(i);
                ++ steps;
                do {
                    vec ~= query(i);
                    ++ steps;
                } while(vec.back != start);

                immutable needToShift = (steps - 1) % vec.length;
                //stderr.writeln("LOG:", vec, " -- ", needToShift);

                vec = vec[$ - needToShift .. $] ~ vec[0 .. $ - needToShift];
                //stderr.writeln("LOG:", vec, " -- ", needToShift);

                do {
                    p[i] = vec.front + 1;
                    i = vec.front;
                    vec.popFront;
                } while (!vec.empty);
            }
        print(p);
    }
}
// ""

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

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

int ask(int i) {
    writefln("? %s", i);
    stdout.flush;
    int x = read!int;
    return x;
}

void solve() {
    int N = read!int;
    int count = 0;
    auto known = new bool[N+1];
    auto cycles = new int[][0];
    int c = 1;
    int[] ks;
    int[] cs;
    int nasked = 0;
    for (int k = 0; count < N; k++) {
        while (known[c]) c++;
        cycles ~= new int[0];
        ks ~= nasked;
        cs ~= c;
        while (true) {
            int x = ask(c);
            nasked++;
            cycles[k] ~= x;
            if (known[x]) {
                break;
            }
            known[x] = true;
            count++;
        }
    }

    int[] P = new int[N + 1]; P[] = -1;
    foreach (i, cycle; cycles) {
        //writeln("cycle: ", cycle);
        int n = cast(int)(cycle.length) - 1;
        int k = ks[i];
        //writeln("k: ", k);
        int s = (N*n + n - k) % n + 1;
        //writeln("s: ", s);
        c = cs[i];
        for (int j = 0; j < n; j++) {
            P[c] = cycle[s];
            //writeln("--> ", [c, cycle[s]]);
            c = cycle[s];
            s = (s == n ? 1 : s + 1);
        }
    }
    //writeln(cycles);
    //writeln(ks);
    writefln("! %(%s %)", P[1 .. $]);
    stdout.flush;
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];

		int ask (int pos)
		{
			writeln ("? ", pos + 1);
			stdout.flush ();
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				foreach (j; 0..q.length - 1)
				{
					auto u = q[j];
					auto v = q[j + 1];
					p[u] = v;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];

		int ask (int pos)
		{
			writeln ("? ", pos + 1);
			stdout.flush ();
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				foreach (j; 0..q.length - 1)
				{
					auto u = q[j];
					auto v = q[j + 1];
					p[v] = u;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				foreach (j; 0..q.length)
				{
					auto u = q[j];
					auto v = q[(j + 1) % $];
					p[v] = u;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k + 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j; 0..q.length)
				{
					auto u = q[j];
					auto v = q[(j + 1) % $];
					p[u] = v;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k + 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j, c; q)
				{
					p[(j + k) % q.length] = c;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
		stdout.flush ();
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k + 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j, c; q)
				{
					p[(j + k) % q.length] = c;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = new bool [n];
		auto p = new int [n];
		int step = 0;

		int ask (int pos)
		{
			writeln (pos + 1);
			stdout.flush ();
			step += 1;
			auto res = readln.strip.to !(int);
			return res - 1;
		}

		foreach (i; 0..n)
		{
			if (!b[i])
			{
				int k = step;
				int [] q;
				do
				{
					q ~= ask (i);
					b[q.back] = true;
				}
				while (q.length < 2 || q.back != q.front);
				q.popBack ();
				k = (-k - 1) % q.length.to !(int);
				k = (k + q.length) % q.length.to !(int);
				foreach (j, c; q)
				{
					p[(j + k) % q.length] = c;
				}
			}
		}
		writefln !("!%( %s%)") (p.map !(q{a + 1}));
	}
}

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

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

int ask(int i) {
    writefln("? %s", i);
    stdout.flush;
    int x = read!int;
    return x;
}

void solve() {
    int N = read!int;
    int count = 0;
    auto known = new bool[N+1];
    auto cycles = new int[][0];
    int c = 1;
    int[] ks;
    int[] cs;
    int nasked = 0;
    for (int k = 0; count < N; k++) {
        while (known[c]) c++;
        cycles ~= new int[0];
        ks ~= nasked;
        cs ~= c;
        while (true) {
            int x = ask(c);
            nasked++;
            cycles[k] ~= x;
            if (known[x]) {
                break;
            }
            known[x] = true;
            count++;
        }
    }

    int[] P = new int[N + 1]; P[] = -1;
    foreach (i, cycle; cycles) {
        //writeln("cycle: ", cycle);
        int n = cast(int)(cycle.length) - 1;
        int k = ks[i];
        int s = (1 + k) % n;
        c = cs[i];
        for (int j = 0; j < n; j++) {
            P[c] = cycle[s];
            //writeln("--> ", [c, cycle[s]]);
            c = cycle[s];
            s = (s + 1) % n;
        }
        //writeln("P: ", P);
    }
    //writeln(cycles);
    //writeln(ks);
    writefln("! %(%s %)", P[1 .. $]);
    stdout.flush;
}

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

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

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

int ask(int i) {
    writefln("? %s", i);
    stdout.flush;
    int x = read!int;
    return x;
}

void solve() {
    int N = read!int;
    int count = 0;
    auto known = new bool[N+1];
    auto cycles = new int[][0];
    int c = 1;
    int[] ks;
    int[] cs;
    int nasked = 0;
    for (int k = 0; count < N; k++) {
        while (known[c]) c++;
        cycles ~= new int[0];
        ks ~= nasked;
        cs ~= c;
        while (true) {
            int x = ask(c);
            nasked++;
            cycles[k] ~= x;
            if (known[x]) {
                break;
            }
            known[x] = true;
            count++;
        }
    }

    int[] P = new int[N + 1]; P[] = -1;
    foreach (i, cycle; cycles) {
        //writeln("cycle: ", cycle);
        int n = cast(int)(cycle.length) - 1;
        int k = ks[i];
        int s = (1 + k) % n;
        c = cs[i];
        for (int j = 0; j < n; j++) {
            P[c] = cycle[s];
            //writeln("--> ", [c, cycle[s]]);
            c = cycle[s];
            s = (s + 1) % n;
        }
        //writeln("P: ", P);
    }
    //writeln(cycles);
    //writeln(ks);
    writefln("%(%s %)", P[1 .. $]);
    stdout.flush;
}

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


import std.algorithm;
import std.conv;
import std.format;
import std.range;
import std.stdio;
import std.typecons;
import std.outbuffer;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

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

int readInt()
{
    return readToken.to!int;
}

void main()
{
    int n = readInt;
    string s = readToken;
    int[] dp = new int[n];
    int[] maxdp = new int[26];
    for (int i = 0; i < n; ++i)
    {
        int c = s[i] - 'a';
        dp[i] = 1;
        for (int j = c + 1; j < 26; ++j)
        {
            dp[i] = max(dp[i], maxdp[j] + 1);
        }
        maxdp[c] = max(maxdp[c], dp[i]);
    }
    writeln(dp.maxElement);
    auto buf = new OutBuffer();
    for (int i = 0; i < n; ++i)
    {
        buf.write(format("%d", dp[i]));
        if (i + 1 < n)
        {
            buf.write(' ');
        }
    }
    writeln(buf.toString());
}

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

DList!string _words;

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

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

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

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

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

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

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

    }
}

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

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 main()
{
  auto n = next!int;
  auto s = next!string;
  int[] lastChar;
  auto color = new long[n.ind];
  foreach(i, c; s)
    {
      auto rng = assumeSorted(lastChar.retro).lowerBound(c + 1);
      if (rng.empty)
        {
          lastChar ~= c;
          color[i] = lastChar.length - 1;
        }
      else
        {
          lastChar[$ - rng.length] = c;
          color[i] = lastChar.length - rng.length;
        }
    }
  writeln(color.fold!((a, b) => max(a, b))(long.min) + 1);
  foreach(b; color)
    write(b + 1, " ");
  writeln;
}


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

void main() {
    int n;
    scan(n);
    auto a = readln.split.to!(int[]);

    auto f = a.sort().group;

    int ans = 0;

    foreach (fi ; f) {
        ans = max(ans, fi[1]);
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
/// struct vector as c++ vector
struct Vec(T)
{
	private Array!T buf;
	alias buf this;
	this(this)
	{
		buf = buf.dup;
	}
	/// construct from length
	this(U)(U length)
			if (is(U == int) || is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint))
	{
		buf.length = length;
	}
	/// construct from length and default value
	this(U, X)(U length, X val)
			if (isImplicitlyConvertible!(X, T) || (is(U == int)
				|| is(U == size_t) || is(U == long) || is(U == ulong) || is(U == uint)))
	{
		buf.length = length;
		foreach (ref x; buf[])
		{
			x = val;
		}
	}
	/// construct from other array
	this(U)(U[] values...) if (isImplicitlyConvertible!(U, T))
	{
		buf = Array!(T)(values);
	}
	/// construct from other range
	this(Range)(Range r)
			if (isInputRange!Range && isImplicitlyConvertible!(ElementType!Range,
				T) && !is(Range == T[]))
	{
		buf = Array!(T)(r);
	}
	/// integer length
	int size() @property const
	{
		return cast(int) buf.length;
	}
}
///mmulo
enum mm = 10 ^^ 9 + 7, mm2 = mm + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt biggcd(BigInt a, BigInt b)
		{
			BigInt res = 1;
			while (b)
			{
				if ((a & 1) && (b & 1))
				{
					a -= b;
					a >>= 1;
				}
				else if (a & 1)
				{
					b >>= 1;
				}
				else if (b & 1)
				{
					a >>= 1;
				}
				else
				{
					res <<= 1;
					a >>= 1;
					b >>= 1;
				}
				if (a < b)
					swap(a, b);
			}
			return res * a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
	{
		return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
	}
	///readln without format
	bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
	{
		return readf!(replicate(" %s", ptrs.length) ~ '\n')(ptrs) == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	int n;
	read(n);
	int[int] q;
	foreach (ii; 0 .. n)
	{
		int x;
		input(x);
		q[x]++;
	}
	int ans;
	foreach (k, v; q)
	{
		ans = max(ans, v);
	}
	writeln(ans);
}

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

void main() {
    readln;
    readln.split.to!(int[]).sort().group.map!(a => a[1]).reduce!max.writeln;
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


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

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

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

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

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

      auto rs = new long[N + 1];
      rs[N] = 0;
      foreach_reverse (i; 0 .. N) {
        rs[i] = max(A[i], rs[i + 1] - 1);
      }
      debug {
        writeln("rs = ", rs);
      }

      long now;
      long ans;
      foreach (i; 0 .. N) {
        chmax(now, rs[i]);
        ans += now - A[i];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

    int n; long[] m;
    sc.read(n, m);
    long[] x = m.dup;
    foreach (i; 0..n-1) {
        x[i+1] = max(x[i+1], x[i]);
    }
    foreach_reverse (i; 0..n-1) {
        x[i] = max(x[i], x[i+1]-1);
    }

    writeln(x.sum - m.sum);

    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

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

// module dkh.foundation;

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

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

// import dkh.container.stackpayload;

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

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

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

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

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

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!T;r.popFront;}}

void main()
{
  int n; readV(n);
  long[] m; readA(n, m);

  auto t = new long[](n);
  t[0] = 1;
  foreach (i; 1..n) t[i] = max(t[i-1], m[i]+1);

  auto c = t[$-1];
  foreach_reverse (i; 0..n-1) {
    --c;
    c = t[i] = max(c, t[i]);
  }

  writeln(t.sum - n - m.sum);
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!T;r.popFront;}}

void main()
{
  int n; readV(n);
  int[] m; readA(n, m);

  auto t = new int[](n);
  t[0] = 1;
  foreach (i; 1..n) t[i] = max(t[i-1], m[i]+1);

  auto c = t[$-1];
  foreach_reverse (i; 0..n-1) {
    --c;
    c = t[i] = max(c, t[i]);
  }

  writeln(t.sum - n - m.sum);
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!T;r.popFront;}}

void main()
{
  int n; readV(n);
  int[] m; readA(n, m);

  auto t = new long[](n);
  t[0] = 1;
  foreach (i; 1..n) t[i] = max(t[i-1], m[i]+1);

  auto c = t[$-1];
  foreach_reverse (i; 0..n-1) {
    --c;
    c = t[i] = max(c, t[i]);
  }

  writeln(t.sum - n - m.sum);
}


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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto C = new long[N];
      foreach (i; 0 .. N) {
        C[i] = readLong();
      }

      alias Entry = Tuple!(long, "c", int, "i");
      BinaryHeap!(Array!Entry) que;
      auto ans = new int[N];
      foreach (i; 0 .. N + K) {
        if (i < N) {
          que.insert(Entry(C[i], i));
        }
        if (i >= K) {
          ans[que.front.i] = i;
          que.removeFront;
        }
      }

      long cost;
      foreach (i; 0 .. N) {
        cost += C[i] * (ans[i] - i);
      }
      writeln(cost);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i] + 1);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1].to!long;
    auto C = readln.split.map!(to!long).array;
    const long INF = 10L^^50;

    auto A = N.iota.map!(i => tuple(-C[i], i)).array;
    A.sort();

    int p = 0;
    auto B = new int[](N);
    auto used = new bool[](N);
    fill(B, -1);

    foreach (a; A) {
        if (a[1] > K) {
            B[max(a[1] - K, p).to!int] = a[1];
        } else {
            B[p] = a[1];
        }

        while (p < N && B[p] != -1)
            p++;
    }

    auto D = new int[](N);
    foreach (i; 0..N) {
        D[B[i]] = i + K.to!int + 1;
    }
    N.iota.map!(i => (D[i] - i - 1) * C[i]).sum.writeln;
    D.map!(to!string).join(" ").writeln;
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1].to!long;
    auto C = readln.split.map!(to!long).array;
    const long INF = 10L^^50;
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		alias Edge = Tuple !(int, q{u}, int, q{v}, int, q{w});
		auto e = new Edge [m];
		auto a = new int [] [n];
		foreach (int i, ref s; e)
		{
			readf !(" %s %s %s") (s.u, s.v, s.w);
			s.u -= 1;
			s.v -= 1;
			a[s.u] ~= i;
			a[s.v] ~= i;
		}

		auto d = new int [] [] (n, n);
		foreach (ref line; d)
		{
			line[] = int.max / 2;
		}
		foreach (i; 0..n)
		{
			d[i][i] = 0;
		}
		foreach (ref s; e)
		{
			d[s.u][s.v] = 1;
			d[s.v][s.u] = 1;
		}
		foreach (k; 0..n)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..n)
				{
					d[i][j] = min (d[i][j],
					    d[i][k] + d[k][j]);
				}
			}
		}

		auto res = long.max;
		foreach (ref s; e)
		{
			foreach (i; 0..n)
			{
				res = min (res,
				    s.w * (2L + d[i][s.u] +
				        d[i][0] + d[i][n - 1]));
				res = min (res,
				    s.w * (2L + d[i][s.v] +
				        d[i][0] + d[i][n - 1]));
			}
			res = min (res, s.w * (1L +
			    d[0][s.u] + d[n - 1][s.v]));
			res = min (res, s.w * (1L +
			    d[0][s.v] + d[n - 1][s.u]));
		}
		writeln (res);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		alias Edge = Tuple !(int, q{u}, int, q{v}, int, q{w});
		auto e = new Edge [m];
		auto a = new int [] [n];
		foreach (int i, ref s; e)
		{
			readf !(" %s %s %s") (s.u, s.v, s.w);
			s.u -= 1;
			s.v -= 1;
			a[s.u] ~= i;
			a[s.v] ~= i;
		}

		auto d = new int [] [] (n, n);
		foreach (ref line; d)
		{
			line[] = int.max / 2;
		}
		foreach (i; 0..n)
		{
			d[i][i] = 0;
		}
		foreach (ref s; e)
		{
			d[s.u][s.v] = 1;
			d[s.v][s.u] = 1;
		}
		foreach (k; 0..n)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..n)
				{
					d[i][j] = min (d[i][j],
					    d[i][k] + d[k][j]);
				}
			}
		}

		auto res = long.max;
		foreach (ref s; e)
		{
			foreach (i; 0..n)
			{
				res = min (res,
				    s.w * (2L + d[s.u][i] +
				        d[0][i] + d[n - 1][i]));
				res = min (res,
				    s.w * (2L + d[s.v][i] +
				        d[0][i] + d[n - 1][i]));
			}
			res = min (res, s.w * (1L +
			    d[0][s.u] + d[n - 1][s.v]));
			res = min (res, s.w * (1L +
			    d[0][s.v] + d[n - 1][s.u]));
		}
		writeln (res);
	}
}


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

struct DayMeatPrice
{
	public int kg, price;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	DayMeatPrice[] dmp; dmp.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d %d", &dmp[i].kg, &dmp[i].price);
	}
	int min = int.max;
	int money = 0;
	foreach (int i; 0..n)
	{
		if (dmp[i].price < min) min = dmp[i].price;
		money += dmp[i].kg * min;
	}
	printf("%d", money);
	return 0;
}

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

void main() {
    int n = readln.chomp.to!int;
    int price = 0;
    int[][] apList;
    for (int i = 0; i < n; i++) {
        auto ap = readln.chomp.split.map!(to!int);
        int a = ap[0];
        int p = ap[1];
        apList ~= [a, p];
    }

    for (int i = 1; i < n; i++) {
        if (apList[i - 1][1] < apList[i][1]) {
            apList[i][1] = apList[i - 1][1];
        }
    }

    int answer = 0;
    foreach (e; apList) {
        answer += e[0] * e[1];
    }

    writeln(answer);
}

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

void main() {
    int n;
    scan(n);

    int pmin = 1000;
    int ans;

    foreach (i ; 0 .. n) {
        int a, p;
        scan(a, p);
        pmin = min(p, pmin);
        ans += a * pmin;
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}