Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.

The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit. The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis. The next m lines contain information about the lanes. The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.

In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.

NoteIn the first example Oleg visiting banks by path 1 → 6 → 2 → 4.Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.In the second example Oleg can visit banks by path 4 → 1 → 3.

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))
	{*/
	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));
	}
	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);
	}
}


Sasha reaches the work by car. It takes exactly k minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the i-th song Sasha gets a pleasure which equals ai. The i-th song lasts for ti minutes. Before the beginning of his way Sasha turns on some song x and then he listens to the songs one by one: at first, the song x, then the song (x + 1), then the song number (x + 2), and so on. He listens to songs until he reaches the work or until he listens to the last song in his playlist. Sasha can listen to each song to the end or partly.In the second case he listens to the song for integer number of minutes, at least half of the song's length. Formally, if the length of the song equals d minutes, Sasha listens to it for no less than  minutes, then he immediately switches it to the next song (if there is such). For example, if the length of the song which Sasha wants to partly listen to, equals 5 minutes, then he should listen to it for at least 3 minutes, if the length of the song equals 8 minutes, then he should listen to it for at least 4 minutes.It takes no time to switch a song.Sasha wants to listen partly no more than w songs. If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs. It is not allowed to skip songs. A pleasure from a song does not depend on the listening mode, for the i-th song this value equals ai.Help Sasha to choose such x and no more than w songs for partial listening to get the maximum pleasure. Write a program to find the maximum pleasure Sasha can get from the listening to the songs on his way to the work.

The first line contains three integers n, w and k (1 ≤ w ≤ n ≤ 2·105, 1 ≤ k ≤ 2·109) — the number of songs in the playlist, the number of songs Sasha can listen to partly and time in minutes which Sasha needs to reach work.  The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 104), where ai equals the pleasure Sasha gets after listening to the i-th song. The third line contains n positive integers t1, t2, ..., tn (2 ≤ ti ≤ 104), where ti equals the length of the i-th song in minutes.

Print the maximum pleasure Sasha can get after listening to the songs on the way to work.

NoteIn the first example Sasha needs to start listening from the song number 2. He should listen to it partly (for 4 minutes), then listen to the song number 3 to the end (for 3 minutes) and then partly listen to the song number 4 (for 3 minutes). After listening to these songs Sasha will get pleasure which equals 4 + 3 + 5 = 12. Sasha will not have time to listen to the song number 5 because he will spend 4 + 3 + 3 = 10 minutes listening to songs number 2, 3 and 4 and only 1 minute is left after that.

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Audio {
    int delight, dur;
    bool used = false;
}

int n, halfCount, totalTime;
Audio[200_000] _audios;
Audio[ ] audios;

void main() {
    while (read(&n, &halfCount, &totalTime)) {
        audios = _audios[0 .. n];
        foreach (ref a; audios) {
            read(&a.delight);
            version (LocalProject)
                a.used = false;
        }
        foreach (ref a; audios)
            read(&a.dur);

        auto used = redBlackTree!(`a.dur != b.dur? a.dur < b.dur : a < b`, Audio*);
        auto unused = redBlackTree!(`a.dur != b.dur? a.dur < b.dur : a < b`, Audio*);
        long available = totalTime, spent = 0, delight = 0;
        int y = n;
        long result = 0;
        foreach_reverse (x, ref a; audios) {
            spent += a.dur;
            delight += a.delight;
            if (used.length < halfCount) {
                a.used = true;
                used.insert(&a);
                available += a.dur >> 1;
            } else if (a.dur > used.front.dur) {
                a.used = true;
                available -= used.front.dur >> 1;
                used.front.used = false;
                unused.insert(used.front);
                used.removeFront();
                used.insert(&a);
                available += a.dur >> 1;
            } else {
                a.used = false;
                unused.insert(&a);
            }

            while (y && spent > available) {
                y--;
                spent -= audios[y].dur;
                delight -= audios[y].delight;
                if (!audios[y].used)
                    unused.removeKey(&audios[y]);
                else {
                    available -= audios[y].dur >> 1;
                    used.removeKey(&audios[y]);
                    if (!unused.empty) {
                        used.insert(unused.back);
                        unused.back.used = true;
                        available += unused.back.dur >> 1;
                        unused.removeBack();
                    }
                }
            }

            debug writefln("y = %s, delight = %s, spent = %s, available = %s",
                y, delight, spent, available);
            result = max(result, delight);
        }
        writeln(result);
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Audio {
    int delight, dur;
    bool used = false;
}

int n, halfCount, totalTime;
Audio[200_000] _audios;
Audio[ ] audios;

void main() {
    while (read(&n, &halfCount, &totalTime)) {
        audios = _audios[0 .. n];
        foreach (ref a; audios) {
            read(&a.delight);
            version (LocalProject)
                a.used = false;
        }
        foreach (ref a; audios)
            read(&a.dur);

        auto used = redBlackTree!(`a.dur < b.dur`, true, Audio*);
        auto unused = redBlackTree!(`a.dur < b.dur`, true, Audio*);
        long available = totalTime, spent = 0, delight = 0;
        int y = n;
        long result = 0;
        foreach_reverse (x, ref a; audios) {
            spent += a.dur;
            delight += a.delight;
            if (used.length < halfCount) {
                a.used = true;
                used.insert(&a);
                available += a.dur >> 1;
            } else if (a.dur > used.front.dur) {
                a.used = true;
                available -= used.front.dur >> 1;
                unused.insert(used.front);
                used.removeFront();
                used.insert(&a);
                available += a.dur >> 1;
            } else {
                a.used = false;
                unused.insert(&a);
            }

            while (y && spent > available) {
                y--;
                spent -= audios[y].dur;
                delight -= audios[y].delight;
                if (!audios[y].used)
                    unused.removeKey(&audios[y]);
                else {
                    available -= audios[y].dur >> 1;
                    used.removeKey(&audios[y]);
                    if (!unused.empty) {
                        used.insert(unused.back);
                        available += unused.back.dur >> 1;
                        unused.removeBack();
                    }
                }
            }

            long t = delight;
            debug writefln("t = %s, y = %s, delight = %s, spent = %s, available = %s",
                t, y, delight, spent, available);
            result = max(result, t);
        }
        writeln(result);
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Audio {
    int delight, dur;
    bool used = false;
}

int n, halfCount, totalTime;
Audio[200_000] _audios;
Audio[ ] audios;

void main() {
    while (read(&n, &halfCount, &totalTime)) {
        audios = _audios[0 .. n];
        foreach (ref a; audios) {
            read(&a.delight);
            version (LocalProject)
                a.used = false;
        }
        foreach (ref a; audios)
            read(&a.dur);

        auto used = redBlackTree!(`a.dur < b.dur? a.dur < b.dur : a < b`, true, Audio*);
        auto unused = redBlackTree!(`a.dur < b.dur? a.dur < b.dur : a < b`, true, Audio*);
        long available = totalTime, spent = 0, delight = 0;
        int y = n;
        long result = 0;
        foreach_reverse (x, ref a; audios) {
            spent += a.dur;
            delight += a.delight;
            if (used.length < halfCount) {
                a.used = true;
                used.insert(&a);
                available += a.dur >> 1;
            } else if (a.dur > used.front.dur) {
                a.used = true;
                available -= used.front.dur >> 1;
                unused.insert(used.front);
                used.removeFront();
                used.insert(&a);
                available += a.dur >> 1;
            } else {
                a.used = false;
                unused.insert(&a);
            }

            while (y && spent > available) {
                y--;
                spent -= audios[y].dur;
                delight -= audios[y].delight;
                if (!audios[y].used)
                    unused.removeKey(&audios[y]);
                else {
                    available -= audios[y].dur >> 1;
                    used.removeKey(&audios[y]);
                    if (!unused.empty) {
                        used.insert(unused.back);
                        unused.back.used = true;
                        available += unused.back.dur >> 1;
                        unused.removeBack();
                    }
                }
            }

            long t = delight;
            debug writefln("t = %s, y = %s, delight = %s, spent = %s, available = %s",
                t, y, delight, spent, available);
            result = max(result, t);
        }
        writeln(result);
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Audio {
    int delight, dur;
    bool used = false;
}

int n, halfCount, totalTime;
Audio[200_000] _audios;
Audio[ ] audios;

void main() {
    while (read(&n, &halfCount, &totalTime)) {
        audios = _audios[0 .. n];
        foreach (ref a; audios) {
            read(&a.delight);
            version (LocalProject)
                a.used = false;
        }
        foreach (ref a; audios)
            read(&a.dur);

        auto used = redBlackTree!(`a.dur < b.dur? a.dur < b.dur : a < b`, true, Audio*);
        auto unused = redBlackTree!(`a.dur < b.dur? a.dur < b.dur : a < b`, true, Audio*);
        long available = totalTime, spent = 0, delight = 0;
        int y = n;
        long result = 0;
        foreach_reverse (x, ref a; audios) {
            spent += a.dur;
            delight += a.delight;
            if (used.length < halfCount) {
                a.used = true;
                used.insert(&a);
                available += a.dur >> 1;
            } else if (a.dur > used.front.dur) {
                a.used = true;
                available -= used.front.dur >> 1;
                unused.insert(used.front);
                used.removeFront();
                used.insert(&a);
                available += a.dur >> 1;
            } else {
                a.used = false;
                unused.insert(&a);
            }

            while (y && spent > available) {
                y--;
                spent -= audios[y].dur;
                delight -= audios[y].delight;
                if (!audios[y].used)
                    unused.removeKey(&audios[y]);
                else {
                    available -= audios[y].dur >> 1;
                    used.removeKey(&audios[y]);
                    if (!unused.empty) {
                        used.insert(unused.back);
                        available += unused.back.dur >> 1;
                        unused.removeBack();
                    }
                }
            }

            long t = delight;
            debug writefln("t = %s, y = %s, delight = %s, spent = %s, available = %s",
                t, y, delight, spent, available);
            result = max(result, t);
        }
        writeln(result);
        debug writeln();
    }
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Audio {
    int delight, dur;
    bool used = false;
}

int n, halfCount, totalTime;
Audio[200_000] _audios;
Audio[ ] audios;

void main() {
    while (read(&n, &halfCount, &totalTime)) {
        audios = _audios[0 .. n];
        foreach (ref a; audios) {
            read(&a.delight);
            version (LocalProject)
                a.used = false;
        }
        foreach (ref a; audios)
            read(&a.dur);

        auto used = redBlackTree!(`a.dur < b.dur? a.dur < b.dur : a < b`, Audio*);
        auto unused = redBlackTree!(`a.dur < b.dur? a.dur < b.dur : a < b`, Audio*);
        long available = totalTime, spent = 0, delight = 0;
        int y = n;
        long result = 0;
        foreach_reverse (x, ref a; audios) {
            spent += a.dur;
            delight += a.delight;
            if (used.length < halfCount) {
                a.used = true;
                used.insert(&a);
                available += a.dur >> 1;
            } else if (a.dur > used.front.dur) {
                a.used = true;
                available -= used.front.dur >> 1;
                used.front.used = false;
                unused.insert(used.front);
                used.removeFront();
                used.insert(&a);
                available += a.dur >> 1;
            } else {
                a.used = false;
                unused.insert(&a);
            }

            while (y && spent > available) {
                y--;
                spent -= audios[y].dur;
                delight -= audios[y].delight;
                if (!audios[y].used)
                    unused.removeKey(&audios[y]);
                else {
                    available -= audios[y].dur >> 1;
                    used.removeKey(&audios[y]);
                    if (!unused.empty) {
                        used.insert(unused.back);
                        unused.back.used = true;
                        available += unused.back.dur >> 1;
                        unused.removeBack();
                    }
                }
            }

            long t = delight;
            debug writefln("t = %s, y = %s, delight = %s, spent = %s, available = %s",
                t, y, delight, spent, available);
            result = max(result, t);
        }
        writeln(result);
        debug writeln();
    }
}


Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 50$$$) — the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.

In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.

9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji

NoteIn the first example, "battab" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string.

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

}


As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special cake placing some cylinders on each other.However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number i can be placed only on the table or on some cake number j where j < i. Moreover, in order to impress friends Babaei will put the cake i on top of the cake j only if the volume of the cake i is strictly greater than the volume of the cake j.Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of simple cakes Babaei has. Each of the following n lines contains two integers ri and hi (1 ≤ ri, hi ≤ 10 000), giving the radius and height of the i-th cake.

Print the maximum volume of the cake that Babaei can make. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn first sample, the optimal way is to choose the cake number 1.In second sample, the way to get the maximum volume is to use cakes with indices 1, 2 and 4.

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

long bit[100005];

int getPos(T)(T[] s, T value) {
  int lo = -1, hi = to!int(s.length);
  while (lo + 1 < hi) {
    int mid = (lo + hi) >> 1;
    if (s[mid] < value) lo = mid;
    else hi = mid;
  }
  return hi;
}

void update(int pos, long value) {
  for (int i = pos + 1; i < 100005; i += i & -i) {
    bit[i] = max(bit[i], value);
  }
}

long query(int pos) {
  long ret = 0;
  for (int i = pos + 1; i > 0; i -= i & -i) {
    ret = max(ret, bit[i]);
  }
  return ret;
}

void main() {
  int n;
  readf(" %s", &n);
  auto a = new long[n];
  foreach (i; 0..n) {
    int r, h;
    readf(" %s %s", &r, &h);
    a[i] = 1L * r * r * h;
  }
  auto b = a.dup.sort.uniq.array;
  long ans = 0;
  foreach (v; a) {
    int pos = getPos(b, v);
    long cur = v + query(pos - 1);
    ans = max(ans, cur);
    update(pos, cur);
  }
  writefln("%.10f", acos(-1.0) * ans);
}


You are given a rectangular grid with $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{ij}$$$ written in it.You can perform the following operation any number of times (possibly zero):  Choose any two adjacent cells and multiply the values in them by $$$-1$$$. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in $$$X$$$, the sum of all the numbers in the grid. What is the maximum $$$X$$$ you can achieve with these operations?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$,$$$m$$$ ($$$2 \le n$$$, $$$m \le 10$$$).  The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-100\leq a_{ij}\le 100$$$).

For each testcase, print one integer $$$X$$$, the maximum possible sum of all the values in the grid after applying the operation as many times as you want.

NoteIn the first test case, there will always be at least one $$$-1$$$, so the answer is $$$2$$$. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: $$$2\times 1 + 3\times2 + 3\times 3 + 2\times 4 + 1\times 5 = 30$$$.

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 m = RD!int;
		long cnt, x = long.max;
		foreach (i; 0..n)
		{
			auto a = RDA;
			foreach (j; 0..m)
			{
				x.chmin(abs(a[j]));
				if (a[j] < 0)
					++cnt;
				ans[ti] += abs(a[j]);
			}
		}
		if (cnt % 2)
		{
			ans[ti] -= x*2;
		}
	}

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


You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$.    An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$.    An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.

In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.

NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow):  first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices;  the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion;  then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it;  the vertex $$$4$$$ will be connected with the vertex $$$3$$$;  then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth);  you will just delete the vertex $$$4$$$;  there are no more vertices to delete.   In the second example you don't need to delete any vertex:  vertices $$$2$$$ and $$$3$$$ have children that respect them;  vertices $$$4$$$ and $$$5$$$ respect ancestors.   In the third example the tree will change this way:

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


Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must:  split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi];  reverse each of the subarrays;  join them into a single array in the same order (this array becomes new array a);  output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.

The first line of input contains a single integer n (0 ≤ n ≤ 20).  The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106).  The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.

NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i < j and x[i] > x[j].

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


Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm:  take the password $$$p$$$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $$$p'$$$ ($$$p'$$$ can still be equal to $$$p$$$);  generate two random strings, consisting of lowercase Latin letters, $$$s_1$$$ and $$$s_2$$$ (any of these strings can be empty);  the resulting hash $$$h = s_1 + p' + s_2$$$, where addition is string concatenation. For example, let the password $$$p =$$$ "abacaba". Then $$$p'$$$ can be equal to "aabcaab". Random strings $$$s1 =$$$ "zyx" and $$$s2 =$$$ "kjh". Then $$$h =$$$ "zyxaabcaabkjh".Note that no letters could be deleted or added to $$$p$$$ to obtain $$$p'$$$, only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password $$$p$$$ and the hash $$$h$$$, check that $$$h$$$ can be the hash for the password $$$p$$$.Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a non-empty string $$$p$$$, consisting of lowercase Latin letters. The length of $$$p$$$ does not exceed $$$100$$$. The second line of each test case contains a non-empty string $$$h$$$, consisting of lowercase Latin letters. The length of $$$h$$$ does not exceed $$$100$$$.

For each test case print the answer to it — "YES" if the given hash $$$h$$$ could be obtained from the given password $$$p$$$ or "NO" otherwise.

5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten

NoteThe first test case is explained in the statement.In the second test case both $$$s_1$$$ and $$$s_2$$$ are empty and $$$p'=$$$ "threetwoone" is $$$p$$$ shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case $$$s_1=$$$ "n", $$$s_2$$$ is empty and $$$p'=$$$ "one" is $$$p$$$ shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password.

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


You have a bag of balls of n different colors. You have ai balls of the i-th color.While there are at least two different colored balls in the bag, perform the following steps:   Take out two random balls without replacement one by one. These balls might be the same color.  Color the second ball to the color of the first ball. You are not allowed to switch the order of the balls in this step.  Place both balls back in the bag.  All these actions take exactly one second. Let M = 109 + 7. It can be proven that the expected amount of time needed before you stop can be represented as a rational number , where P and Q are coprime integers and where Q is not divisible by M. Return the value .

The first line of input will contain a single integer n (1 ≤ n ≤ 2 500) — the number of colors. The next line of input will contain n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the number of balls of each color.

Print a single integer, the answer to the problem.

NoteIn the first sample, no matter what happens, the balls will become the same color after one step.For the second sample, we have 6 balls. Let’s label the balls from 1 to 6, and without loss of generality, let’s say balls 1,2,3 are initially color 1, balls 4,5 are color 2, and ball 6 are color 3.Here is an example of how these steps can go:   We choose ball 5 and ball 6. Ball 6 then becomes color 2.  We choose ball 4 and ball 5. Ball 5 remains the same color (color 2).  We choose ball 1 and ball 5. Ball 5 becomes color 1.  We choose ball 6 and ball 5. Ball 5 becomes color 2.  We choose ball 3 and ball 4. Ball 4 becomes color 1.  We choose ball 4 and ball 6. Ball 6 becomes color 1.  We choose ball 2 and ball 5. Ball 5 becomes color 1.  At this point, the game ends since all the balls are the same color. This particular sequence took 7 seconds.It can be shown that the answer to this case is .

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

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

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

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

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

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

/*
  p[i] = a[i] (S - a[i]) / (S (S - 1))
  e[i] = 1 + p[i] e[i - 1] + (1 - 2 p[i]) e[i] + p[i] e[i + 1]
  e[0] = 0, e[S] = 0

  e[i - 1] = -1 / p[i] + 2 e[i] - e[i + 1]
  e[i + 1] - e[i] = (e[i] - e[i - 1]) - 1 / p[i]
*/

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      const S = A.sum;
      const maxA = A.maxElement;

      const d = Mint(S - 1) * Mint(S - 1) / S;
      auto es = new Mint[maxA + 1];
      es[0] = 0;
      Mint dd = d;
      foreach (i; 1 .. maxA + 1) {
        es[i] = es[i - 1] + dd;
        dd -= Mint(S - 1) * Mint(S - i).inv;
      }
      debug {
        writeln("es = ", es);
      }

      Mint ans;
      foreach (i; 0 .. N) {
        ans += es[A[i]];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.

The first line of input contains three integers y, k, n (1 ≤ y, k, n ≤ 109;   ≤ 105).

Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once. If there are no such values of x print a single integer -1.

module cf_239A;

import std.stdio;

void main() {
    int y, k, n, x = 1;

    readf("%d %d %d", &y, &k, &n);

    x = k - y % k;
    if (x + y > n) {
        writeln(-1);
    } else {
        while (x + y <= n) {
            writef("%d ", x);
            x += k;
        }
        writeln();
    }
}


This is the easy version of the problem. The difference is the constraints on $$$n$$$, $$$m$$$ and $$$t$$$. You can make hacks only if all versions of the problem are solved.Alice and Bob are given the numbers $$$n$$$, $$$m$$$ and $$$k$$$, and play a game as follows:The game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially $$$0$$$. The game consists of $$$n$$$ turns. Each turn, Alice picks a real number from $$$0$$$ to $$$k$$$ (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least $$$m$$$ out of the $$$n$$$ turns.Bob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).If Alice and Bob play optimally, what will the final score of the game be?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. Each test case consists of a single line containing the three integers, $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le m \le n \le 2000, 0 \le k < 10^9 + 7$$$) — the number of turns, how many of those turns Bob has to add, and the biggest number Alice can choose, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case output a single integer number — the score of the optimal game modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9 + 7$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

NoteIn the first test case, the entire game has $$$3$$$ turns, and since $$$m = 3$$$, Bob has to add in each of them. Therefore Alice should pick the biggest number she can, which is $$$k = 2$$$, every turn.In the third test case, Alice has a strategy to guarantee a score of $$$\frac{75}{8} \equiv 375000012 \pmod{10^9 + 7}$$$.In the fourth test case, Alice has a strategy to guarantee a score of $$$\frac{45}{2} \equiv 500000026 \pmod{10^9 + 7}$$$.

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

immutable int mod = 10 ^^ 9 + 7;
immutable int half = mod / 2 + 1;
static assert ((half * 2L) % mod == 1);

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m, k;
		readf !(" %s %s %s") (n, m, k);
		auto f = new int [] [] (n + 1, m + 1);
		foreach (i; 0..n + 1)
		{
			foreach (j; 0..min (i, m) + 1)
			{
				if (j == 0)
				{
					f[i][j] = 0;
				}
				else if (j == i)
				{
					f[i][j] = j;
				}
				else
				{
					f[i][j] = (half * 1L * (f[i - 1][j] +
					    f[i - 1][j - 1])) % mod;
				}
			}
		}
		int res = (f[n][m] * 1L * k) % mod;
		writeln (res);
	}
}


While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.

The first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m (). The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots. It is guaranteed that at least one ordering of the robots satisfies all m relations.

Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.

NoteIn the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.

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