Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-th (1 ≤ i ≤ m) type of ice cream form a connected subgraph. We build a new graph G with m vertices. We put an edge between the v-th and the u-th (1 ≤ u, v ≤ m, u ≠ v) vertices in G if and only if there exists a vertex in T that has both the v-th and the u-th types of ice cream in its set. The problem is to paint the vertices of G with minimum possible number of colors in a way that no adjacent vertices have the same color.Please note that we consider that empty set of vertices form a connected subgraph in this problem.As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.

The first line contains two integer n and m (1 ≤ n, m ≤ 3·105) — the number of vertices in T and the number of ice cream types. n lines follow, the i-th of these lines contain single integer si (0 ≤ si ≤ 3·105) and then si distinct integers, each between 1 and m — the types of ice cream in the i-th vertex. The sum of si doesn't exceed 5·105. n - 1 lines follow. Each of these lines describes an edge of the tree with two integers u and v (1 ≤ u, v ≤ n) — the indexes of connected by this edge vertices.

Print single integer c in the first line — the minimum number of colors to paint the vertices in graph G. In the second line print m integers, the i-th of which should be the color of the i-th vertex. The colors should be between 1 and c. If there are some answers, print any of them.

NoteIn the first example the first type of ice cream is present in the first vertex only, so we can color it in any color. The second and the third ice cream are both presented in the second vertex, so we should paint them in different colors.In the second example the colors of the second, the fourth and the fifth ice cream should obviously be distinct.

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.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;const 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;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static 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,m;
loop:while(read(n,m))
	{
		auto g=new int[][n+1],ice=new int[][n+1];
		foreach(i;0..n)
		{
			int s;
			input(s);
			ice[i+1]=arread!int;
		}
		foreach(i;0..n-1)
		{
			int u,v;
			read(u,v);
			g[u]~=v;
			g[v]~=u;
		}
		auto cl=new int[m+1];
		int ans;
		void dfs(int v,int pr)
		{
			auto q=new RedBlackTree!int;
			int x=1;
			foreach(c; ice[v]) {
				if(cl[c])q.insert(cl[c]);
			}
			foreach(c;q)
			{
				if(x==c)x++;
			}
			foreach(c;ice[v])
			{
				if(!cl[c])
				{
					cl[c]=x++;
					while(!q.equalRange(x).empty)x++;
				}
			}
			ans=max(ans,x-1);
			foreach(c;g[v])
			{
				if(c!=pr)dfs(c,v);
			}
		}
		dfs(1,-1);
		writeln(max(ans,1));
		foreach(x;cl[1..$])write(max(x,1),' ');
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.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;const 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;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static 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,m;
loop:while(read(n,m))
	{
		auto g=new int[][n+1],ice=new int[][n+1];
		foreach(i;0..n)
		{
			int s;
			input(s);
			ice[i+1]=arread!int;
		}
		foreach(i;0..n-1)
		{
			int u,v;
			read(u,v);
			g[u]~=v;
			g[v]~=u;
		}
		auto cl=new int[m+1];
		int ans;
		void dfs(int v,int pr)
		{
			auto q=new RedBlackTree!int;
			int x=1;
			foreach(c; ice[v]) {
				if(cl[c])q.insert(cl[c]);
			}
			foreach(c;q)
			{
				if(x==c)x++;
			}
			foreach(c;ice[v])
			{
				if(!cl[c])
				{
					cl[c]=x++;
					while(!q.equalRange(x).empty)x++;
				}
			}
			ans=max(ans,x-1);
			foreach(c;g[v])
			{
				if(c!=pr)dfs(c,v);
			}
		}
		dfs(1,-1);
		writeln(ans);
		foreach(x;cl[1..$])write(x,' ');
	}
}


In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.Given this information, is it possible to restore the exact floor for flat n?

The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory. m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct. It is guaranteed that the given information is not self-contradictory.

Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.

NoteIn the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.

import core.stdc.stdio;
import std.algorithm;
int l=1,r=1000000000;
void main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	int a,f;
	for (int i=1;i<=m;i++)
	{
		scanf("%d%d",&a,&f);
		l=max(l,1+(a-1)/f);
		if (f>1) r=min(r,(a-1)/(f-1));
	}
	l=1+(n-1)/l;
	r=1+(n-1)/r;
	if (l==r) printf("%d\n",l);
	else puts("-1");
}


Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).

The first line contains two integers m, d (1 ≤ m ≤ 2000, 0 ≤ d ≤ 9) — the parameters from the problem statement. The second line contains positive integer a in decimal presentation (without leading zeroes). The third line contains positive integer b in decimal presentation (without leading zeroes). It is guaranteed that a ≤ b, the number of digits in a and b are the same and don't exceed 2000.

Print the only integer a — the remainder after dividing by 109 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.

NoteThe numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.The numbers from the answer of the second example are 2, 4, 6 and 8.The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747.

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

immutable int BASE = 10;
immutable int MOD = 1_000_000_007;
immutable int NA = -1;

void main ()
{
	int m, d;
	while (readf (" %s %s", &m, &d) > 0)
	{
		readln;
		auto a = readln.strip;
		int n = a.length;
		a = format ("%0*d", n, BigInt (a) - 1);
		auto b = readln.strip;
		assert (n == b.length);

		auto fun (string s)
		{
			auto z = s.map !(x => x - '0').array;
			auto f = new int [] [] (2, m);
			int t = 0;
			int cur = 0;
			foreach (i; 0..n)
			{
				t ^= 1;
				f[t][] = 0;

				if (cur != NA)
				{
					cur = (cur * BASE) % m;
					foreach (e; 0..z[i])
					{
						if ((i & 1) == (e == d))
						{
							f[t][cur] += 1;
							if (f[t][cur] >= MOD)
							{
								f[t][cur] -=
								    MOD;
							}
						}
						cur = (cur + 1) % m;
					}
				}
				if ((i & 1) != (z[i] == d))
				{
					cur = NA;
				}

				foreach (r; 0..m)
				{
					int nr = (r * BASE) % m;
					foreach (e; 0..BASE)
					{
						if ((i & 1) == (e == d))
						{
							f[t][nr] += f[!t][r];
							if (f[t][nr] >= MOD)
							{
								f[t][nr] -=
								    MOD;
							}
						}
						nr = (nr + 1) % m;
					}
				}
				debug {writeln (cur, " ", f[t]);}
			}

			int res = (cur == 0) + f[t][0];
			if (res >= MOD)
			{
				res -= MOD;
			}
			return res;
		}

		writeln ((fun (b) - fun (a) + MOD) % MOD);
	}
}

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

immutable int BASE = 10;
immutable int MOD = 1_000_000_007;
immutable int NA = -1;

struct ModInt
{
	int contents;
//	alias contents this;

	invariant
	{
		assert (0 <= contents && contents < MOD);
	}

	this (int newContents)
	in
	{
		assert (0 <= newContents && newContents < MOD);
	}
	body
	{
		contents = newContents;
	}

	ref ModInt opOpAssign (string op) (const ModInt rhs)
	in
	{
		assert (0 <= rhs.contents && rhs.contents < MOD);
	}
	body
	{
		static if (op == "+")
		{
			contents += rhs.contents;
			if (contents >= MOD)
			{
				contents -= MOD;
			}
		}
		else static if (op == "-")
		{
			contents -= rhs.contents;
			if (contents < 0)
			{
				contents += MOD;
			}
		}
		else static if (op == "*")
		{
			contents = (contents * 1L * rhs.contents) % MOD;
		}
		else
		{
			static assert (false);
		}
		return this;
	}

	ref ModInt opOpAssign (string op) (const int rhs)
	in
	{
		assert (0 <= rhs && rhs < MOD);
	}
	body
	{
		mixin (q{this } ~ op ~ q{= ModInt (rhs);});
		return this;
	}

	ModInt opBinary (string op) (const ModInt rhs)
	in
	{
		assert (0 <= rhs.contents && rhs.contents < MOD);
	}
	body
	{
		ModInt res = this;
		mixin (q{res } ~ op ~ q{= rhs;});
		return res;
	}

	ModInt opBinary (string op) (const int rhs)
	in
	{
		assert (0 <= rhs && rhs < MOD);
	}
	body
	{
		ModInt res = this;
		mixin (q{res } ~ op ~ q{= ModInt (rhs);});
		return res;
	}

	string toString () const
	{
		return text (contents);
	}
}

void main ()
{
	int m, d;
	while (readf (" %s %s", &m, &d) > 0)
	{
		readln;
		auto a = readln.strip;
		int n = a.length;
		a = format ("%0*d", n, BigInt (a) - 1);
		auto b = readln.strip;
		assert (n == b.length);

		auto fun (string s)
		{
			auto z = s.map !(x => x - '0').array;
			auto f = new ModInt [] [] (2, m);
			int t = 0;
			int cur = 0;
			foreach (i; 0..n)
			{
				t ^= 1;
				f[t][] = ModInt (0);

				if (cur != NA)
				{
					cur = (cur * BASE) % m;
					foreach (e; 0..z[i])
					{
						if ((i & 1) == (e == d))
						{
							f[t][cur] += 1;
						}
						cur = (cur + 1) % m;
					}
				}
				if ((i & 1) != (z[i] == d))
				{
					cur = NA;
				}

				foreach (r; 0..m)
				{
					int nr = (r * BASE) % m;
					foreach (e; 0..BASE)
					{
						if ((i & 1) == (e == d))
						{
							f[t][nr] += f[!t][r];
						}
						nr = (nr + 1) % m;
					}
				}
				debug {writeln (cur, " ", f[t]);}
			}

			ModInt res = (cur == 0);
			res += f[t][0];
			return res;
		}

		writeln (fun (b) - fun (a));
	}
}

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

immutable int BASE = 10;
immutable int MOD = 1_000_000_007;
immutable int NA = -1;

struct ModInt
{
	int contents;
	alias contents this;

	invariant
	{
		assert (0 <= contents && contents < MOD);
	}

	this (int newContents)
	in
	{
		assert (0 <= newContents && newContents < MOD);
	}
	body
	{
		contents = newContents;
	}

	ref ModInt opOpBinary (string op, T) (const T rhs)
	in
	{
		assert (0 <= rhs && rhs < MOD);
	}
	body
	{
		static if (op == "+")
		{
			contents += rhs;
			if (contents >= MOD)
			{
				contents -= MOD;
			}
		}
		else if (op == "-")
		{
			contents -= rhs;
			if (contents < 0)
			{
				contents += MOD;
			}
		}
		else if (op == "*")
		{
			contents = (contents * 1L * rhs) % MOD;
		}
		else
		{
			static assert (false);
		}
		return this;
	}

	ModInt opBinary (string op, T) (const T rhs)
	in
	{
		assert (0 <= rhs && rhs < MOD);
	}
	body
	{
		ModInt res = this;
		mixin (q{res} ~ op ~ q{= rhs;});
		return res;
	}
}

void main ()
{
	int m, d;
	while (readf (" %s %s", &m, &d) > 0)
	{
		readln;
		auto a = readln.strip;
		int n = a.length;
		a = format ("%0*d", n, BigInt (a) - 1);
		auto b = readln.strip;
		assert (n == b.length);

		auto fun (string s)
		{
			auto z = s.map !(x => x - '0').array;
			auto f = new ModInt [] [] (2, m);
			int t = 0;
			int cur = 0;
			foreach (i; 0..n)
			{
				t ^= 1;
				f[t][] = ModInt (0);

				if (cur != NA)
				{
					cur = (cur * BASE) % m;
					foreach (e; 0..z[i])
					{
						if ((i & 1) == (e == d))
						{
							f[t][cur] += 1;
						}
						cur = (cur + 1) % m;
					}
				}
				if ((i & 1) != (z[i] == d))
				{
					cur = NA;
				}

				foreach (r; 0..m)
				{
					int nr = (r * BASE) % m;
					foreach (e; 0..BASE)
					{
						if ((i & 1) == (e == d))
						{
							f[t][nr] += f[!t][r];
						}
						nr = (nr + 1) % m;
					}
				}
				debug {writeln (cur, " ", f[t]);}
			}

			ModInt res = (cur == 0);
			res += f[t][0];
			return res;
		}

		writeln (fun (b) - fun (a));
	}
}


You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 100; -100 \le a, b \le 100$$$) — the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.

For each testcase, print a single integer — the maximum number of points that you can score.

NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \cdot 1 + 5 = 3$$$ points, i. e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations.

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

long solve(long l, long a, long b)
{
  if (l == 0)
    return 0;
  long x1 = (a + b) * l;
  long x2 = b + l * a;
  return max(x1, x2);
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n, a, b;
    readf!" %d %d %d "(n, a, b);
    auto s = readln.strip.split("").map!(to!int).array;
    long l = 1;
    int i = 1;
    int prev = s[0];
    long[] x;
    long result = 0;
    while (i < n) {
      while (i < n && s[i] == prev) {
        l++;
        i++;
      }
      x ~= l;
      l = 0;
      prev = !prev;
    }
    if (l != 0)
      x ~= l;
    long firstodd = 0;
    long sumodd = 0;
    long firsteven = 0;
    long sumeven = 0;
    foreach (j ; 0 .. x.length) {
      if (j % 2 == 1) {
        firstodd += solve(x[j], a, b);
        sumodd += x[j];
      } else {
        firsteven += solve(x[j], a, b);
        sumeven += x[j];
      }
    }
    firstodd += solve(sumeven, a, b);
    firsteven += solve(sumodd, a, b);
//    writeln(firstodd);
//    writeln(firsteven);
    writeln(max(firstodd, firsteven));
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (b >= 0)
			ans[ti] = (a+b) * n;
		else
		{
			long cnt;
			foreach (i; 1..n)
			{
				if (s[i] != s[i-1])
					++cnt;
			}
			cnt = (cnt+1) / 2 + 1;

			ans[ti] = a * n + b * cnt;
		}
	}

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

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

long solve(long l, long a, long b)
{
  long x1 = (a + b) * l;
  long x2 = b + l * a;
  return max(x1, x2);
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n, a, b;
    readf!" %d %d %d "(n, a, b);
    auto s = readln.strip.split("").map!(to!int).array;
    long l = 1;
    int i = 1;
    int prev = s[0];
    long[] x;
    long result = 0;
    while (i < n) {
      while (i < n && s[i] == prev) {
        l++;
        i++;
      }
      x ~= l;
      l = 0;
      prev = !prev;
    }
    if (l != 0)
      x ~= l;
//    writeln(x);
    long firstodd = 0;
    long sumodd = 0;
    long firsteven = 0;
    long sumeven = 0;
    foreach (j ; 0 .. x.length) {
      if (j % 2 == 1) {
        firstodd += solve(x[j], a, b);
        sumodd += x[j];
      } else {
        firsteven += solve(x[j], a, b);
        sumeven += x[j];
      }
    }
    firstodd += solve(sumeven, a, b);
    firsteven += solve(sumodd, a, b);
//    writeln(firstodd);
//    writeln(firsteven);
    writeln(max(firstodd, firsteven));
  }
}

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

long solve(long l, long a, long b)
{
  long x1 = (a + b) * l;
  long x2 = b + l * a;
  return max(x1, x2);
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n, a, b;
    readf!" %d %d %d "(n, a, b);
    auto s = readln.strip.split("").map!(to!int).array;
    long l = 1;
    int i = 1;
    int prev = s[0];
    long[] x;
    long result = 0;
    while (i < n) {
      while (i < n && s[i] == prev) {
        l++;
        i++;
      }
      x ~= l;
      l = 0;
      prev = !prev;
    }
    long firstodd = 0;
    long sumodd = 0;
    long firsteven = 0;
    long sumeven = 0;
    foreach (j ; 0 .. x.length) {
      if (j % 2 == 1) {
        firstodd += solve(x[j], a, b);
        sumodd += x[j];
      } else {
        firsteven += solve(x[j], a, b);
        sumeven += x[j];
      }
    }
    firstodd += solve(sumeven, a, b);
    firsteven += solve(sumodd, a, b);
    writeln(max(firstodd, firsteven));
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (b >= 0)
			ans[ti] = (a+b) * n;
		else
		{
			long cnt;
			foreach (i; 1..n)
			{
				if (s[i] != s[i-1])
					++cnt;
			}
			if (cnt <= 1)
				++cnt;

			ans[ti] = a * n + b * cnt;
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (b >= 0)
			ans[ti] = (a+b) * n;
		else
		{
			long cnt;
			foreach (i; 1..n)
			{
				if (s[i] != s[i-1])
					++cnt;
			}
			cnt.chmax(1);

			ans[ti] = a * n + b * cnt;
		}
	}

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


You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands:  for $$$n$$$ — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every "for $$$n$$$" is matched with "end", thus the function is guaranteed to be valid. "for $$$n$$$" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some "add" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

The first line contains a single integer $$$l$$$ ($$$1 \le l \le 10^5$$$) — the number of lines in the function. Each of the next $$$l$$$ lines contains a single command of one of three types:   for $$$n$$$ ($$$1 \le n \le 100$$$) — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$.

If overflow happened during execution of $$$f(0)$$$, then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

9
add
for 43
end
for 10
for 15
add
end
add
end

11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end

NoteIn the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for $$$n$$$" can be immediately followed by "end" and that "add" can be outside of any for loops.In the second example there are no commands "add", thus the returning value is 0.In the third example "add" command is executed too many times, which causes $$$x$$$ to go over $$$2^{32}-1$$$.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		real [] m;
		m ~= 1;
		real res = 0;
		foreach (i; 0..n)
		{
			auto command = readln.split;
			if (command[0] == "add")
			{
				res += m.back;
			}
			else if (command[0] == "for")
			{
				m ~= m.back * command[1].to !(int);
			}
			else if (command[0] == "end")
			{
				m.popBack ();
				m.assumeSafeAppend ();
			}
			else
			{
				assert (false);
                        }
		}
		if (res >= (1L << 32))
		{
			writeln ("OVERFLOW!!!");
		}
		else
		{
			writefln ("%.0f", res);
		}
	}
}

//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;
import std.typecons;

alias T = Tuple!(int, ulong);

void overflow () {
  writeln ("OVERFLOW!!!");
}

void main() {
  string s;
  readf!" %s" (s);
  auto z = s.splitter;
  string rs () {
    auto r = z.front;
    z.popFront ();
    return r;
  }
  immutable ulong m = 1L << 32;

  immutable l = rs().strip().to!int;
  auto st = new T[5 * l];
  int k;
  foreach (qid; 0 .. l) {
    auto t = rs ();
    if (t[0] == 'a') {
      st[k++] = tuple (1, 1);
    } else if (t[0] == 'f') {
      st[k++] = tuple (2, rs().strip().to!ulong);
    } else if (t[0] == 'e') {
      ulong x;
      while (st[k-1][0] != 2) {
        x += st[k-1][1];
        if (x >= m) {
          overflow ();
          return;
        }
        --k;
      }
      x *= st[k-1][1];
      if (x >= m) {
        overflow ();
        return;
      }
      st[k-1] = tuple (1, x);
    }
  }
  ulong y;
  foreach (i; 0 .. k) {
    y += st[i][1];
    if (y >= m) {
      overflow ();
      return;
    }
  }
  writeln (y);
}

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 read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int l = read.to!int;

	long infty = 1L<<32;

	long[] depths = [1];
	long ans;
	foreach(_; 0 .. l){

		string cmd = read;
		if(cmd == "for"){
			long val = read.to!long;
			long d = depths[$ - 1] * val;
			if(d >= infty) d = infty;

			depths ~= d;
		}
		else if(cmd == "add"){
			long d = depths[$ - 1];
			ans += d;
			if(ans >= infty){
				"OVERFLOW!!!".writeln;
				return;
			}
		}
		else if(cmd == "end"){
			depths.length -= 1;
		}

	}
	ans.writeln;
}

import std.typecons;

import core.stdc.stdio : scanf;
import std.stdio;
import std.algorithm;
import std.range;
import std.bigint;

alias PII = Tuple!(int, int);
alias PLL = Tuple!(long, long);

void main() {

    long n;

    scanf("%d\n", &n);

    long x = 0;

    long[] stack;

    stack ~= 1L;

    long INF = (1L << 32);

    foreach (cmd; 0 .. n) {
        char[100] c;
        scanf("%s", &c);
        if (c[0] == 'a') {
            x = x + stack.back;
            if (x >= INF) {
                writeln("OVERFLOW!!!");
                return;
            }
        }

        if (c[0] == 'f') {
            long tt;
            scanf("%lld\n", &tt);
            stack ~= stack.back * tt;
            if (stack.back >= INF)
                stack.back = INF;

        }

        if (c[0] == 'e') {
            stack.popBack();
        }
    }

    writeln(x);
}

import std.typecons;

// import core.stdc.stdio;
import std.stdio;
import std.algorithm;
import std.range;
import std.bigint;

alias PII = Tuple!(int, int);
alias PLL = Tuple!(long, long);

void main() {

    long n;

    stdin.readf("%d", n);

    BigInt x;

    BigInt[] stack;

    stack ~= BigInt(1);

    foreach (cmd; 0 .. n) {
        string c = stdin.readln();
        if (c[0] == 'a') {
            x = x + stack.back;
            if (x > (1L << 32) - 1) {
                writeln("OVERFLOW!!!");
                return;
            }
        }

        if (c[0] == 'f') {
            auto t = BigInt(c.split[1]);
            // writeln(t);
            stack ~= stack.back * t;
        }

        if (c[0] == 'e') {
            stack.popBack();
        }
    }

    writeln(x);
}


Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output the number of pieces of sausage that lay on the crust.

NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

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

void main() {
    auto s = readln.split.map!(to!long);
    auto R = s[0];
    auto D = s[1];
    auto C = R - D;
    auto N = readln.chomp.to!int;

    bool ok1(long x, long y, long r) {
        return x * x + y * y >= (r + C) * (r + C);
    }

    bool ok2(long x, long y, long r) {
        return x * x + y * y <= (r - R) * (r - R);
    }

    int ans = 0;
    while (N--) {
        s = readln.split.map!(to!long);
        auto x = s[0];
        auto y = s[1];
        auto r = s[2];
        ans += ok1(x, y, r) && ok2(x, y, r);
    }

    ans.writeln;
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio      : readln, writeln;
import std.array      : split;
import std.string     : chomp;
import std.conv       : to;
import std.math       : sqrt;

auto gets() { return readln.chomp; }
auto getVals(T)() { return gets.split.to!(T[]); }

void main() {
    auto rd = getVals!double;
    auto r = rd[0], d = rd[1];
    auto n = gets.to!int;
    auto ans = 0;
    for (auto i = 0; i < n; i++) {
        auto xyr = getVals!double;
        auto xi = xyr[0], yi = xyr[1], ri = xyr[2];
        auto di = sqrt(xi * xi + yi * yi);
        if (di + ri <= r && di - ri >= r - d) {
            ans++;
        }
    }
    writeln(ans);
}


Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \le pos \le n$$$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $$$s_{pos}$$$:   if $$$s_{pos}$$$ is equal to R the bot chooses "Rock";  if $$$s_{pos}$$$ is equal to S the bot chooses "Scissors";  if $$$s_{pos}$$$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round — on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \dots c_n$$$ such that $$$\frac{win(1) + win(2) + \dots + win(n)}{n}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \dots s_{n}$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$s_i \in \{\text{R}, \text{S}, \text{P}\}$$$) — the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ choices $$$c_1 c_2 \dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.

NoteIn the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case:   if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$;  if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$;  if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$;  The average is equal to $$$\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining "Rock paper scissors" game:

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto best = "RSP".maxElement !(c => s.count (c));
		auto res = best == 'R' ? 'P' : best == 'S' ? 'R' : 'S';
		writeln (res.repeat (s.length));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto best = "RSP".maxElement !(c => s.count (c));
		auto res = best == 'R' ? 'P' : best == 'S' ? 'R' : 'P';
		writeln (res.repeat (s.length));
	}
}


Monocarp had a permutation $$$a$$$ of $$$n$$$ integers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once).Then Monocarp calculated an array of integers $$$b$$$ of size $$$n$$$, where $$$b_i = \left\lfloor \frac{i}{a_i} \right\rfloor$$$. For example, if the permutation $$$a$$$ is $$$[2, 1, 4, 3]$$$, then the array $$$b$$$ is equal to $$$\left[ \left\lfloor \frac{1}{2} \right\rfloor, \left\lfloor \frac{2}{1} \right\rfloor, \left\lfloor \frac{3}{4} \right\rfloor, \left\lfloor \frac{4}{3} \right\rfloor \right] = [0, 2, 0, 1]$$$.Unfortunately, the Monocarp has lost his permutation, so he wants to restore it. Your task is to find a permutation $$$a$$$ that corresponds to the given array $$$b$$$. If there are multiple possible permutations, then print any of them. The tests are constructed in such a way that least one suitable permutation exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le n$$$). Additional constrains on the input:   the sum of $$$n$$$ over test cases does not exceed $$$5 \cdot 10^5$$$;  there exists at least one permutation $$$a$$$ that would yield this array $$$b$$$.

For each test case, print $$$n$$$ integers — a permutation $$$a$$$ that corresponds to the given array $$$b$$$. If there are multiple possible permutations, then print any of them.

import std;

int t,n;
uint k;
static const uint N = 500007;

struct node {
    uint l, r, id;
    int opCmp(ref const node rhs) const {
        if (r == rhs.r)
            return l > rhs.l ? -1 : 1;
        return r < rhs.r ? -1 : 1;
    }
}

node[N] q;
uint[N] a, ans, f;
bool[N] st;

uint find(uint x) {
    if (x == f[x])
        return f[x];
    return f[x] = find(f[x]);
}

void main()
{
    import core.stdc.stdio;

    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d", &n);
        getchar();
        foreach(i; 1 .. (n + 1)) {
            f[i] = i;
            st[i] = false;
            scanf("%u", &k);
            a[i] = k;
        }
        foreach(i; 1 .. (n + 1)) {
            if (a[i] == 0)
                q[i] = node(i+1,n,i);
            else
                q[i] = node(i/(a[i]+1)+1,i/a[i],i);
        }
        sort!"a < b"(q[1..n+1]).array;
        foreach(i;1 .. (n + 1)) {
            uint l = find(q[i].l);
            while(st[l]) {
                f[l] = find(l + 1);
                l = find(q[i].l);
            }
            ans[q[i].id] = l;
            st[l] = true;
        }
        for(int i = 1;i<=n;i++)
            printf("%d ", ans[i]);
        printf("\n");
        //writefln("%(%s %)", ans[1..n+1]);
    }
}

import std;

int t,n;
uint k;
static const uint N = 500007;

struct node {
    uint l, r, id;
    int opCmp(ref const node rhs) const {
        if (r == rhs.r)
            return l > rhs.l ? -1 : 1;
        return r < rhs.r ? -1 : 1;
    }
}

node[N] q;
uint[N] a, ans, f;
bool[N] st;

uint find(uint x) {
    if (x == f[x])
        return f[x];
    return f[x] = find(f[x]);
}

void main()
{
    import std.outbuffer: OutBuffer;

    OutBuffer buf = new OutBuffer();

    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d", &n);
        getchar();
        foreach(i; 1 .. (n + 1)) {
            f[i] = i;
            st[i] = false;
            scanf("%u", &k);
            a[i] = k;
        }
        foreach(i; 1 .. (n + 1)) {
            if (a[i] == 0)
                q[i] = node(i+1,n,i);
            else
                q[i] = node(i/(a[i]+1)+1,i/a[i],i);
        }
        sort!"a < b"(q[1..n+1]).array;
        foreach(i;1 .. (n + 1)) {
            uint l = find(q[i].l);
            while(st[l]) {
                f[l] = find(l + 1);
                l = find(q[i].l);
            }
            ans[q[i].id] = l;
            st[l] = true;
        }
        buf.writefln("%(%s %)", ans[1..n+1]);
    }
    write(buf.toString());
}

import std;

int t,n;
uint k;
static const uint N = 500007;

struct node {
    uint l, r, id;
    int opCmp(ref const node rhs) const {
        if (r == rhs.r)
            return l > rhs.l ? -1 : 1;
        return r < rhs.r ? -1 : 1;
    }
}

node[N] q;
uint[N] a, ans, f;
bool[N] st;

uint find(uint x) {
    if (x == f[x])
        return f[x];
    return f[x] = find(f[x]);
}

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d", &n);
        getchar();
        foreach(i; 1 .. (n + 1)) {
            f[i] = i;
            st[i] = false;
            scanf("%u", &k);
            a[i] = k;
        }
        foreach(i; 1 .. (n + 1)) {
            if (a[i] == 0)
                q[i] = node(i+1,n,i);
            else
                q[i] = node(i/(a[i]+1)+1,i/a[i],i);
        }
        sort!"a < b"(q[1..n+1]).array;
        foreach(i;1 .. (n + 1)) {
            uint l = find(q[i].l);
            while(st[l]) {
                f[l] = find(l + 1);
                l = find(q[i].l);
            }
            ans[q[i].id] = l;
            st[l] = true;
        }
        writefln("%(%s %)", ans[1..n+1]);
    }
}

import std;

int t,n;
uint k;
static const uint N = 500007;

struct node {
    uint l, r, id;
    bool opCmp(node rhs) const {
        if (r == rhs.r)
            return l > rhs.l;
        return r < rhs.r;
    }
}

node[N] q;
uint[N] a, ans, f;
bool[N] st;

uint find(uint x) {
    if (x == f[x])
        return f[x];
    f[x] = find(f[x]);
    return f[x];
}

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d", &n);
        getchar();
        foreach(i; 1 .. (n + 1)) {
            f[i] = i;
            st[i] = false;
            scanf("%u", &k);
            a[i] = k;
        }
        foreach(i; 1 .. (n + 1))
            if (a[i] == 0L)
                q[i] = node(i+1,n,i);
            else
                q[i] = node(i/(a[i]+1)+1,i/a[i],i);
        q[1..n+1].sort();
        foreach(i;1 .. (n + 1)) {
            uint l = find(q[i].l);
            while(st[l]) {
                f[l] = find(l + 1);
                l = find(q[i].l);
            }
            ans[q[i].id] = l;
            st[l] = true;
        }
        writefln("%(%s %)", ans[1..n+1]);
    }
}


You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array:   [1] (from index 1 to index 1), imbalance value is 0;  [1, 4] (from index 1 to index 2), imbalance value is 3;  [1, 4, 1] (from index 1 to index 3), imbalance value is 3;  [4] (from index 2 to index 2), imbalance value is 0;  [4, 1] (from index 2 to index 3), imbalance value is 3;  [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.

The first line contains one integer n (1 ≤ n ≤ 106) — size of the array a. The second line contains n integers a1, a2... an (1 ≤ ai ≤ 106) — elements of the array.

Print one integer — the imbalance value of a.

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

immutable int mod = 10^^9 + 7;

int n;
int[] a;

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

    auto leftmin = new int[](n);
    auto rightmin = new int[](n);
    auto stack = new Stack!int(n + 10);

    //debug stack.empty.writeln;

    foreach (i ; 0 .. n) {
        while (!stack.empty && a[stack.top] > a[i]) {
            //debug {writeln("i:", i, " ", "stack top:", stack.front);}
            stack.pop;
        }

        if (stack.empty) {
            leftmin[i] = -1;
        }
        else {
            //debug {writeln("i:", i, " ", "stack top:", stack.front);}
            leftmin[i] = stack.top;
        }

        debug {
            //writeln("leftmin:", leftmin);
        }
        stack.push(i);
    }

    stack.clear;
    //debug stack.empty.writeln;

    foreach_reverse (i ; 0 .. n) {
        while (!stack.empty && a[stack.top] >= a[i]) {
            stack.pop;
        }

        if (stack.empty) rightmin[i] = n;
        else rightmin[i] = stack.top;

        stack.push(i);
    }

    stack.clear;

    debug {
        writeln("leftmin:", leftmin);
        writeln("rightmin", rightmin);
    }

    auto leftmax = new int[](n);
    auto rightmax = new int[](n);
    stack.clear;

    foreach (i ; 0 .. n) {
        while (!stack.empty && a[stack.top] < a[i]) stack.pop;

        leftmax[i] = (stack.empty ? -1 : stack.top);
        stack.push(i);
    }

    stack.clear;

    foreach_reverse (i ; 0 .. n) {
        while (!stack.empty && a[stack.top] <= a[i]) stack.pop;

        rightmax[i] = (stack.empty ? n : stack.top);
        stack.push(i);
    }

    debug {
        writeln("leftmax:", leftmax);
        writeln("rightmax:", rightmax);
    }

    long ans, v;

    foreach (i ; 0 .. n) {
        v = (i - leftmin[i]).to!long * (rightmin[i] - i) * a[i];
        ans -= v;
        v = (i - leftmax[i]).to!long * (rightmax[i] - i) * a[i];
        ans += v;
    }

    writeln(ans);
}

class Stack(T) {
    private:
    int N, peek;
    T[] data;

    public:
    this(int size) {
        N = size;
        data = new T[](N);
    }

    bool empty() @property {
        return peek == 0;
    }

    bool full() @property {
        return peek == N;
    }

    void push(T x) {
        if (full) throw new Exception("Stack is Full.");
        data[peek++] = x;
    }

    void pop() @property {
        if (empty) throw new Exception("Stack is Empty.");
        --peek;
    }

    T top() @property {
        if (empty) throw new Exception("Stack is Empty.");
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }
}

unittest {
    auto st = new Stack!int(5);
    assert(st.empty);
    st.push(3);
    st.push(1);
    st.push(4);
    st.push(1);
    st.push(5);
    assert(st.full);
    assert(st.top == 5);
    st.pop;
    assert(st.top == 1);
    st.pop;
    assert(st.top == 4);
    st.pop;
    st.pop;
    assert(st.top == 3);
    st.pop;
    assert(st.empty);

    st.push(3);
    st.push(5);
    st.push(100);

    assert(!st.empty);

    st.clear;

    assert(st.empty);

    st.push(5);
    st.push(1);

    assert(st.top == 1);
    st.pop;
    assert(st.top == 5);
    st.pop;

    assert(st.empty);

    stderr.writeln("Unittest has passed.");
}

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

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

immutable int mod = 10^^9 + 7;

int n;
int[] a;

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

    auto leftmin = new int[](n);
    auto rightmin = new int[](n);
    auto stack = new SList!(int)();

    //debug stack.empty.writeln;

    foreach (i ; 0 .. n) {
        while (!stack.empty && a[stack.front] > a[i]) {
            //debug {writeln("i:", i, " ", "stack top:", stack.front);}
            stack.removeFront;
        }

        if (stack.empty) {
            leftmin[i] = -1;
        }
        else {
            //debug {writeln("i:", i, " ", "stack top:", stack.front);}
            leftmin[i] = stack.front;
        }

        debug {
            //writeln("leftmin:", leftmin);
        }
        stack.insert(i);
    }

    stack.clear;
    //debug stack.empty.writeln;

    foreach_reverse (i ; 0 .. n) {
        while (!stack.empty && a[stack.front] >= a[i]) {
            stack.removeFront;
        }

        if (stack.empty) rightmin[i] = n;
        else rightmin[i] = stack.front;

        stack.insert(i);
    }

    stack.clear;

    debug {
        writeln("leftmin:", leftmin);
        writeln("rightmin", rightmin);
    }

    auto leftmax = new int[](n);
    auto rightmax = new int[](n);
    stack.clear;

    foreach (i ; 0 .. n) {
        while (!stack.empty && a[stack.front] < a[i]) stack.removeFront;

        leftmax[i] = (stack.empty ? -1 : stack.front);
        stack.insert(i);
    }

    stack.clear;

    foreach_reverse (i ; 0 .. n) {
        while (!stack.empty && a[stack.front] <= a[i]) stack.removeFront;

        rightmax[i] = (stack.empty ? n : stack.front);
        stack.insert(i);
    }

    debug {
        writeln("leftmax:", leftmax);
        writeln("rightmax:", rightmax);
    }

    long ans, v;

    foreach (i ; 0 .. n) {
        v = (i - leftmin[i]).to!long * (rightmin[i] - i) * a[i];
        ans -= v;
        v = (i - leftmax[i]).to!long * (rightmax[i] - i) * a[i];
        ans += v;
    }

    writeln(ans);
}

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

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

immutable int mod = 10^^9 + 7;

int n;
int[] a;

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

    Stack!int st = Stack!int(n + 10);

    auto leftmin = new int[](n);

    foreach (i ; 0 .. n) {
        while (!st.empty && a[st.top] > a[i]) st.pop;

        leftmin[i] = (st.empty ? -1 : st.top);
        st.push(i);
    }

    st.clear;

    auto rightmin = new int[](n);

    foreach_reverse (i ; 0 .. n) {
        while (!st.empty && a[st.top] >= a[i]) st.pop;

        rightmin[i] = (st.empty ? n : st.top);
        st.push(i);
    }

    st.clear;

    auto leftmax = new int[](n);

    foreach (i ; 0 .. n) {
        while (!st.empty && a[st.top] < a[i]) st.pop;

        leftmax[i] = (st.empty ? -1 : st.top);
        st.push(i);
    }

    st.clear;

    auto rightmax = new int[](n);

    foreach_reverse (i ; 0 .. n) {
        while (!st.empty && a[st.top] <= a[i]) st.pop;

        rightmax[i] = (st.empty ? n : st.top);
        st.push(i);
    }

    long ans;

    foreach (i ; 0 .. n) {
        ans += 1L * (i - leftmax[i]) * (rightmax[i] - i) * a[i];
        ans -= 1L * (i - leftmin[i]) * (rightmin[i] - i) * a[i];
    }

    writeln(ans);
}

struct Stack(T) {
private:
    int N, peek;
    T[] data;

public:
    this(int size)
    {
        N = size;
        data = new T[](N);
    }

    bool empty() @property
    {
        return peek == 0;
    }

    bool full() @property
    {
        return peek == N;
    }

    void push(T x) @property
    {
        assert(!full);
        data[peek++] = x;
    }

    void pop() @property
    {
        assert(!empty);
        --peek;
    }

    T top() @property
    {
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }

}

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

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

int n;
int[] a;

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

    int[] leftmin = new int[](n);
    auto st = Stack!int(n + 10);

    foreach (i ; 0 .. n) {
        while (!st.empty && a[st.top] > a[i]) st.pop;

        leftmin[i] = (st.empty ? -1 : st.top);
        st.push(i);
    }

    st.clear;

    int[] rightmin = new int[](n);

    foreach_reverse (i ; 0 .. n) {
        while (!st.empty && a[st.top] >= a[i]) st.pop;

        rightmin[i] = (st.empty ? n : st.top);
        st.push(i);
    }

    st.clear;

    int[] leftmax = new int[](n);

    foreach (i ; 0 .. n) {
        while (!st.empty && a[st.top] < a[i]) st.pop;

        leftmax[i] = (st.empty ? -1 : st.top);
        st.push(i);
    }

    st.clear;

    int[] rightmax = new int[](n);

    foreach_reverse (i ; 0 .. n) {
        while (!st.empty && a[st.top] <= a[i]) st.pop;

        rightmax[i] = (st.empty ? n : st.top);
        st.push(i);
    }

    long ans;

    foreach (i ; 0 .. n) {
        ans += 1L * (i - leftmax[i]) * (rightmax[i] - i) * a[i];
        ans -= 1L * (i - leftmin[i]) * (rightmin[i] - i) * a[i];
    }

    writeln(ans);
}

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

struct Stack(T) {
private:
    int N, peek;
    T[] data;

public:
    this(int size)
    {
        N = size;
        data = new T[](N);
    }

    bool empty() @property
    {
        return peek == 0;
    }

    bool full() @property
    {
        return peek == N;
    }

    void push(T x) @property
    {
        assert(!full);
        data[peek++] = x;
    }

    void pop() @property
    {
        assert(!empty);
        --peek;
    }

    T top() @property
    {
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }

    int length() @property
    {
        return peek;
    }

}

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

immutable int mod = 10^^9 + 7;

int n;
int[] a;

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

    auto pmini = new int[](n);
    auto pmaxi = new int[](n);

    int maxa = a[0], mina = a[0];

    foreach (i ; 1 .. n) {
        pmini[i] = pmini[i - 1];
        pmaxi[i] = pmaxi[i - 1];

        if (a[i] > maxa) {
            maxa = a[i];
            pmaxi[i] = i;
        }

        if (a[i] < mina) {
            mina = a[i];
            pmini[i] = i;
        }
    }

    debug {
        writeln("pmini:",pmini);
        writeln("pmaxi:",pmaxi);
    }

    auto smini = new int[](n);
    auto smaxi = new int[](n);

    smini[n - 1] = n - 1;
    smaxi[n - 1] = n - 1;

    maxa = a[n - 1], mina = a[n - 1];

    foreach_reverse (i ; 0 .. n - 1) {
        smini[i] = smini[i + 1];
        smaxi[i] = smaxi[i + 1];

        if (a[i] >= maxa) {
            maxa = a[i];
            smaxi[i] = i;
        }

        if (a[i] <= mina) {
            mina = a[i];
            smini[i] = i;
        }
    }

    debug {
        writeln("smini:", smini);
        writeln("smaxi:", smaxi);
    }

    long ans, v;

    int j, k;

    foreach (i ; 0 .. n) {

        if (i == pmaxi[i])
            j = binsearch1(smaxi, i);
        else
            j = i;

        if (i == pmaxi[i])
            k = binsearch2(pmaxi, i);
        else
            k = i;

        debug {
            //writeln(j, " ", i, " ", k);
        }

        ans += (i - j + 1).to!long * (k - i + 1) * a[i];

        if (i == smini[i])
            j = binsearch1(smini, i);
        else
            j = i;

        if (i == pmini[i])
            k = binsearch2(pmini, i);
        else
            k = i;

        ans -= (i - j + 1).to!long * (k - i + 1) * a[i];
    }

    assert(ans >= 0);

    writeln(ans);
}

int binsearch1(int[] s, int i) {
    int btm, top, mid;
    btm = -1;
    top = i;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;

        if (s[mid] == s[i]) {
            top = mid;
        }
        else {
            btm = mid;
        }
    }

    return top;
}

int binsearch2(int[] s, int i) {
    int btm, top, mid;
    btm = i;
    top = n;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;

        if (s[mid] == s[i]) {
            btm = mid;
        }
        else {
            top = mid;
        }
    }

    return btm;
}

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

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

immutable int mod = 10^^9 + 7;

int n;
int[] a;

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

    auto pmini = new int[](n);
    auto pmaxi = new int[](n);

    int maxa = a[0], mina = a[0];

    foreach (i ; 1 .. n) {
        pmini[i] = pmini[i - 1];
        pmaxi[i] = pmaxi[i - 1];

        if (a[i] > maxa) {
            maxa = a[i];
            pmaxi[i] = i;
        }

        if (a[i] < mina) {
            mina = a[i];
            pmini[i] = i;
        }
    }

    debug {
        writeln("pmini:",pmini);
        writeln("pmaxi:",pmaxi);
    }

    auto smini = new int[](n);
    auto smaxi = new int[](n);

    smini[n - 1] = n - 1;
    smaxi[n - 1] = n - 1;

    maxa = a[n - 1], mina = a[n - 1];

    foreach_reverse (i ; 0 .. n - 1) {
        smini[i] = smini[i + 1];
        smaxi[i] = smaxi[i + 1];

        if (a[i] >= maxa) {
            maxa = a[i];
            smaxi[i] = i;
        }

        if (a[i] <= mina) {
            mina = a[i];
            smini[i] = i;
        }
    }

    debug {
        writeln("smini:", smini);
        writeln("smaxi:", smaxi);
    }

    long ans, v;

    int j, k;

    foreach (i ; 0 .. n) {

        if (i == pmaxi[i])
            j = binsearch1(smaxi, i);
        else
            j = i;

        if (i == pmaxi[i])
            k = binsearch2(pmaxi, i);
        else
            k = i;

        debug {
            writeln(j, " ", i, " ", k);
        }

        ans += (i - j + 1).to!long * (k - i + 1) * a[i];

        if (i == smini[i])
            j = binsearch1(smini, i);
        else
            j = i;

        if (i == pmini[i])
            k = binsearch2(pmini, i);
        else
            k = i;

        debug {

        }

        ans -= (i - j + 1).to!long * (k - i + 1) * a[i];
    }

    writeln(ans);
}

int binsearch1(int[] s, int i) {
    int btm, top, mid;
    btm = -1;
    top = i;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;

        if (s[mid] == s[i]) {
            top = mid;
        }
        else {
            btm = mid;
        }
    }

    return top;
}

int binsearch2(int[] s, int i) {
    int btm, top, mid;
    btm = i;
    top = n;

    while (top - btm > 1) {
        mid = btm + (top - btm) / 2;

        if (s[mid] == s[i]) {
            btm = mid;
        }
        else {
            top = mid;
        }
    }

    return btm;
}

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


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s$$$.For some non-empty substring$$$^\dagger$$$ $$$t$$$ of string $$$s$$$ containing $$$x$$$ characters 0 and $$$y$$$ characters 1, define its cost as:  $$$x \cdot y$$$, if $$$x > 0$$$ and $$$y > 0$$$;  $$$x^2$$$, if $$$x > 0$$$ and $$$y = 0$$$;  $$$y^2$$$, if $$$x = 0$$$ and $$$y > 0$$$. Given a binary string $$$s$$$ of length $$$n$$$, find the maximum cost across all its non-empty substrings.$$$^\dagger$$$ A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum cost across all substrings.

NoteIn the first test case, we can take a substring $$$111$$$. It contains $$$3$$$ characters 1 and $$$0$$$ characters 0. So $$$a = 3$$$, $$$b = 0$$$ and its cost is $$$3^2 = 9$$$.In the second test case, we can take the whole string. It contains $$$4$$$ characters 1 and $$$3$$$ characters 0. So $$$a = 4$$$, $$$b = 3$$$ and its cost is $$$4 \cdot 3 = 12$$$.In the third test case, we can can take a substring $$$1111$$$ and its cost is $$$4^2 = 16$$$.In the fourth test case, we can take the whole string and cost is $$$4 \cdot 3 = 12$$$.In the fifth test case, we can take a substring $$$000$$$ and its cost is $$$3 \cdot 3 = 9$$$.In the sixth test case, we can only take the substring $$$0$$$ and its cost is $$$1 \cdot 1 = 1$$$.

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

// Lengths of sequences satisfying the condition (moving to the right)
int[] seq_length_right(alias less = "a < b", T)(T[] a)
{
  if (a.length == 0)
    return new int[](0);
  auto tmp = new int[](a.length);
  int count = 1;
  tmp[$ - 1] = count;
  foreach_reverse (i ; 0 .. a.length - 1) {
    if (binaryFun!less(a[i], a[i + 1]))
      count++;
    else
      count = 1;
    tmp[i] = count;
  }
  return tmp;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!long;
    auto s = readln.strip;
    auto a = s.seq_length_right!"a==b";
    long x = s.count('0');
    long y = s.count('1');
    long z = a.maxElement;
    writeln(max(x * y, z * z));
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;
		auto res = s.count ('0') * 1L * s.count ('1');
		res = max (res,
		    s.group.map !(c => c[1]).maxElement.to !(long) ^^ 2);
		writeln (res);
	}
}

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

// Lengths of sequences satisfying the condition (moving to the right)
int[] seq_length_right(alias less = "a < b", T)(T[] a)
{
  if (a.length == 0)
    return new int[](0);
  auto tmp = new int[](a.length);
  int count = 1;
  tmp[$ - 1] = count;
  foreach_reverse (i ; 0 .. a.length - 1) {
    if (binaryFun!less(a[i], a[i + 1]))
      count++;
    else
      count = 1;
    tmp[i] = count;
  }
  return tmp;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!long;
    auto s = readln.strip;
    auto a = s.seq_length_right!"a==b";
    auto x = s.count('0');
    auto y = s.count('1');
    writeln(max(cast(long)x * y, cast(long)a.maxElement * a.maxElement));
  }
}

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

// Lengths of sequences satisfying the condition (moving to the right)
int[] seq_length_right(alias less = "a < b", T)(T[] a)
{
  if (a.length == 0)
    return new int[](0);
  auto tmp = new int[](a.length);
  int count = 1;
  tmp[$ - 1] = count;
  foreach_reverse (i ; 0 .. a.length - 1) {
    if (binaryFun!less(a[i], a[i + 1]))
      count++;
    else
      count = 1;
    tmp[i] = count;
  }
  return tmp;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!long;
    auto s = readln.strip;
    auto a = s.seq_length_right!"a==b";
    auto x = s.count('0');
    auto y = s.count('1');
    writeln(max(x * y, a.maxElement * a.maxElement));
  }
}


You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.

For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.

NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$.

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

void main () {
    int t;
	readf("%d\n", &t);
	while(t--) {
		int n, x;
		readf("%d %d\n", &n, &x);
		auto a = readln.split.to!(int[]);
		auto b = readln.split.to!(int[]);
		sort(a);
		sort(b);
		auto result = true;
		for(int i = 0; i < n; i++) {
			if(a[i] + b[n-i-1] > x) {
				result = false;
				break;
			}
		}
		if(result)
			writeln("Yes");
		else
			writeln("No");

		if(t)
			readln();
	}
}

// Cheese-Cracker: cheese-cracker.github.io

void play(){
    int n, x;
    n = rd!int; x = rd!int;
    ll[] a =  rdarr;
    ll[] b = rdarr;
    a.sort;
    b.sort;
    b.reverse;
    foreach(i; 0..n){
        if(a[i] + b[i] > x){
            writeln("No");
            return;
        }
    }
    writeln("Yes");
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, "x",  long, "y");
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		sort !(q{a < b}) (a);
		sort !(q{a > b}) (b);
		auto res = zip (a, b).all !(p => p[0] + p[1] <= x);
		writeln (res ? "Yes" : "No");
	}
}


The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≤ si ≤ c).Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 ≤ c, and 0, otherwise.You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right — (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.A star lies in a rectangle if it lies on its border or lies strictly inside it.

The first line contains three integers n, q, c (1 ≤ n, q ≤ 105, 1 ≤ c ≤ 10) — the number of the stars, the number of the views and the maximum brightness of the stars. The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 ≤ xi, yi ≤ 100, 0 ≤ si ≤ c ≤ 10) — the coordinates of i-th star and its initial brightness. The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 ≤ ti ≤ 109, 1 ≤ x1i < x2i ≤ 100, 1 ≤ y1i < y2i ≤ 100) — the moment of the i-th view and the coordinates of the viewed rectangle.

For each view print the total brightness of the viewed stars.

NoteLet's consider the first example.At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.

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 s = readln.split.map!(to!int);
    auto N = s[0];
    auto Q = s[1];
    auto C = s[2];
    auto X = new int[](N);
    auto Y = new int[](N);
    auto S = new int[](N);
    foreach (i; 0..N) {
        s = readln.split.map!(to!int);
        X[i] = s[0];
        Y[i] = s[1];
        S[i] = s[2];
    }

    auto A = new int[][][](C + 1, 110, 110);
    foreach (t; 0..C+1) {
        foreach (i; 0..N) {
            A[t][X[i] + 1][Y[i] + 1] += (S[i] + t) % (C + 1);
        }
    }

    foreach (t; 0..C+1)
        foreach (i; 0..102)
            foreach (j; 0..102)
                A[t][i][j + 1] += A[t][i][j];
    foreach (t; 0..C+1)
        foreach (j; 0..102)
            foreach (i; 0..102)
                A[t][i + 1][j] += A[t][i][j];

    int cumsum(int t, int x1, int y1, int x2, int y2) {
        return A[t][x2 + 1][y2 + 1] - A[t][x2 + 1][y1] - A[t][x1][y2 + 1] + A[t][x1][y1];
    }

    while (Q--) {
        s = readln.split.map!(to!int);
        auto t = s[0] % (C + 1);
        auto x1 = s[1];
        auto y1 = s[2];
        auto x2 = s[3];
        auto y2 = s[4];
        cumsum(t, x1, y1, x2, y2).writeln;
    }
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

immutable lim = 110;
int n, q, c;

void main() {
    scan(n, q, c);

    auto star = new int[][][](c + 1, lim, lim);

    int xi, yi, si;

    foreach (i ; 0 .. n) {
        scan(xi, yi, si);
        star[si][xi][yi]++;
    }

    foreach (k ; 0 .. c + 1) {
        foreach (i ; 1 .. lim) {
            foreach (j ; 1 .. lim) {
                star[k][i][j] += star[k][i - 1][j] + star[k][i][j - 1] - star[k][i - 1][j - 1];
            }
        }
    }

    int acc2d(int k, int x1, int y1, int x2, int y2) {
        return star[k][x2][y2] - star[k][x2][y1 - 1] - star[k][x1 - 1][y2] + star[k][x1 - 1][y1 - 1];
    }

    int ti, x1i, y1i, x2i, y2i;

    foreach (qi ; 0 .. q) {
        scan(ti, x1i, y1i, x2i, y2i);

        int ans;

        foreach (k ; 0 .. c + 1) {
            int p = (k + ti) % (c + 1);
            ans += acc2d(k, x1i, y1i, x2i, y2i) * p;
        }

        writeln(ans);
    }
}

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

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

import 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 s = readln.split.map!(to!int);
    auto N = s[0];
    auto Q = s[1];
    auto C = s[2];
    auto X = new int[](N);
    auto Y = new int[](N);
    auto S = new int[](N);
    foreach (i; 0..N) {
        s = readln.split.map!(to!int);
        X[i] = s[0];
        Y[i] = s[1];
        S[i] = s[2];
    }

    auto A = new int[][][](C + 1, 110, 110);
    foreach (t; 0..C+1) {
        foreach (i; 0..N) {
            A[t][X[i] + 1][Y[i] + 1] += (S[i] + t) % (C + 1);
        }
    }

    foreach (t; 0..C+1)
        foreach (i; 0..102)
            foreach (j; 0..102)
                A[t][i][j + 1] += A[t][i][j];
    foreach (t; 0..C+1)
        foreach (j; 0..102)
            foreach (i; 0..102)
                A[t][i + 1][j] += A[t][i][j];

    int cumsum(int t, int x1, int y1, int x2, int y2) {
        return A[t][x2 + 1][y2 + 1] - A[t][x2 + 1][y1] - A[t][x1][y2 - 1] + A[t][x1][y1];
    }

    while (Q--) {
        s = readln.split.map!(to!int);
        auto t = s[0] % (C + 1);
        auto x1 = s[1];
        auto y1 = s[2];
        auto x2 = s[3];
        auto y2 = s[4];
        cumsum(t, x1, y1, x2, y2).writeln;
    }
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

immutable lim = 110;

int n, q, c;

void main() {
    scan(n, q, c);

    auto kido = new int[][][](c + 1, lim, lim);
    auto exst = new bool[][](lim, lim);

    int xi, yi, si;

    foreach (i ; 0 .. n) {
        scan(xi, yi, si);
        kido[0][xi][yi] = si;
        exst[xi][yi] = true;
    }

    foreach (k ; 0 .. c) {
        foreach (i ; 0 .. lim) {
            foreach (j ; 0 .. lim) {
                if (exst[i][j]) {
                    kido[k + 1][i][j] = (kido[k][i][j] + 1) % (c + 1);
                }
            }
        }
    }

    foreach (k; 0 .. c + 1) {
        foreach (i ; 0 .. lim) {
            foreach (j ; 0 .. lim - 1) {
                kido[k][i][j + 1] += kido[k][i][j];
            }
        }

        foreach (j ; 0 .. lim) {
            foreach (i ; 0 .. lim - 1) {
                kido[k][i + 1][j] += kido[k][i][j];
            }
        }
    }

    int ti, x1i, y1i, x2i, y2i;

    foreach (qi ; 0 .. q) {
        scan(ti, x1i, y1i, x2i, y2i);
        ti %= (c + 1);

        int ans;
        ans += kido[ti][x2i][y2i];
        ans -= kido[ti][x2i][y1i - 1];
        ans -= kido[ti][x1i - 1][y2i];
        ans += kido[ti][x1i - 1][y1i - 1];

        writeln(ans);
    }
}

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

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

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

immutable lim = 110;

int n, q, c;

void main() {
    scan(n, q, c);

    auto kido = new int[][][](c + 1, lim, lim);
    auto exst = new bool[][](lim, lim);

    int xi, yi, si;

    foreach (i ; 0 .. n) {
        scan(xi, yi, si);

        if (exst[xi][yi]) {
            writeln("Error");
            return;
        }

        kido[0][xi][yi] = si;
        exst[xi][yi] = true;
    }

    foreach (k ; 0 .. c) {
        foreach (i ; 0 .. lim) {
            foreach (j ; 0 .. lim) {
                if (exst[i][j]) {
                    kido[k + 1][i][j] = (kido[k][i][j] + 1) % (c + 1);
                }
            }
        }
    }

    debug {
        foreach (k ; 0 .. c + 1) {
            writefln("%(%(%s %)\n%)", kido[k]);
            writeln;
        }
    }

    foreach (k; 0 .. c + 1) {
        foreach (i ; 0 .. lim) {
            foreach (j ; 0 .. lim - 1) {
                kido[k][i][j + 1] += kido[k][i][j];
            }
        }

        foreach (j ; 0 .. lim) {
            foreach (i ; 0 .. lim - 1) {
                kido[k][i + 1][j] += kido[k][i][j];
            }
        }
    }

    int ti, x1i, y1i, x2i, y2i;

    foreach (qi ; 0 .. q) {
        scan(ti, x1i, y1i, x2i, y2i);
        ti %= (c + 1);

        int ans;
        ans += kido[ti][x2i][y2i];
        ans -= kido[ti][x2i][y1i - 1];
        ans -= kido[ti][x1i - 1][y2i];
        ans += kido[ti][x1i - 1][y1i - 1];

        writeln(ans);
    }
}

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

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

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

immutable lim = 10;

int n, q, c;

void main() {
    scan(n, q, c);

    auto kido = new int[][][](c + 1, lim, lim);
    auto exst = new bool[][](lim, lim);

    int xi, yi, si;

    foreach (i ; 0 .. n) {
        scan(xi, yi, si);

        if (exst[xi][yi]) {
            writeln("Error");
            return;
        }

        kido[0][xi][yi] = si;
        exst[xi][yi] = true;
    }

    foreach (k ; 0 .. c) {
        foreach (i ; 0 .. lim) {
            foreach (j ; 0 .. lim) {
                if (exst[i][j]) {
                    kido[k + 1][i][j] = (kido[k][i][j] + 1) % (c + 1);
                }
            }
        }
    }

    debug {
        foreach (k ; 0 .. c + 1) {
            writefln("%(%(%s %)\n%)", kido[k]);
            writeln;
        }
    }

    foreach (k; 0 .. c + 1) {
        foreach (i ; 0 .. lim) {
            foreach (j ; 0 .. lim - 1) {
                kido[k][i][j + 1] += kido[k][i][j];
            }
        }

        foreach (j ; 0 .. lim) {
            foreach (i ; 0 .. lim - 1) {
                kido[k][i + 1][j] += kido[k][i][j];
            }
        }
    }

    int ti, x1i, y1i, x2i, y2i;

    foreach (qi ; 0 .. q) {
        scan(ti, x1i, y1i, x2i, y2i);
        ti %= (c + 1);

        int ans;
        ans += kido[ti][x2i][y2i];
        ans -= kido[ti][x2i][y1i - 1];
        ans -= kido[ti][x1i - 1][y2i];
        ans += kido[ti][x1i - 1][y1i - 1];

        writeln(ans);
    }
}

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

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


Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.

The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b1, ..., bn  — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.

Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi.  If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.

import std.stdio;
import std.algorithm;

void main() {
  int n;
  readf(" %s", &n);
  int length = 1;
  int[] prevDigit = new int[1001];
  prevDigit[0] = 0;
  while (n--) {
    int need;
    readf(" %s", &need);
    int sum = 0;
    for (int i = 0; i < length; i++) {
      sum += prevDigit[i];
    }
    bool can = false;
    for (int i = 0; i < length; i++) {
      if (prevDigit[i] < 9) {
        int delta = need - sum;
        if (delta >= 1 && delta <= 9 * i + 9 - prevDigit[i]) {
          prevDigit[i]++;
          delta--;
          for (int j = 0; j < i; j++) {
            int add = min(9, delta);
            prevDigit[j] = add;
            delta -= add;
          }
          prevDigit[i] += delta;
          can = true;
          break;
        }
      }
      sum -= prevDigit[i];
    }
    if (!can) {
      need--;
      int nine = 0;
      while (nine * 9 <= need) {
        nine++;
      }
      nine--;
      for (int i = 0; i < nine; i++) {
        prevDigit[i] = nine;
      }
      length = max(nine + 1, length + 1);
      prevDigit[length - 1] = 1;
      for (int i = 0; i < length - 1; i++) {
        int add = min(9, need);
        prevDigit[i] = add;
        need -= add;
      }
      prevDigit[length - 1] += need;
    }
    for (int i = length - 1; i >= 0; i--) {
      write(prevDigit[i]);
    }
    writeln;
  }
}

import std.stdio;
import std.algorithm;

void main() {
  int n;
  readf(" %s", &n);
  int length = 1;
  int[] prevDigit = new int[1001];
  prevDigit[0] = 0;
  while (n--) {
    int need;
    readf(" %s", &need);
    int sum = 0;
    for (int i = 0; i < length; i++) {
      sum += prevDigit[i];
    }
    bool can = false;
    for (int i = 0; i < length; i++) {
      if (prevDigit[i] < 9 && sum + 9 * i + 9 - prevDigit[i] >= need && need - sum - 9 * i > 0) {
        prevDigit[i] += need - sum - 9 * i;
        can = true;
        break;
      }
      sum -= prevDigit[i];
    }
    if (!can) {
      need--;
      int nine = 0;
      while (nine * 9 <= need) {
        nine++;
      }
      nine--;
      for (int i = 0; i < nine; i++) {
        prevDigit[i] = nine;
      }
      length = max(nine + 1, length + 1);
      prevDigit[] = 0;
      prevDigit[length - 1] = 1;
      for (int i = 0; i < length; i++) {
        int add = min(9 - prevDigit[i], need);
        prevDigit[i] += add;
        need -= add;
      }
    }
    for (int i = length - 1; i >= 0; i--) {
      write(prevDigit[i]);
    }
    writeln;
  }
}


n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.

The first line contains integer n (1 ≤ n ≤ 18) — the amount of fish in the lake. Then there follow n lines with n real numbers each — matrix a. aij (0 ≤ aij ≤ 1) — the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.

Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.

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

double saiki(int mask, int n, double[][] a, double[] dp)
{
    if (dp[mask] != -1)
    {
        return dp[mask];
    }
    if (mask + 1 == 1 << n)
    {
        dp[mask] = 1.0;
        return 1.0;
    }
    int[] dead, live;
    foreach (i; 0 .. n)
    {
        if ((mask & (1 << i)) == 0)
        {
            dead ~= i;
        }
        else
        {
            live ~= i;
        }
    }
    auto prob = 1.0 / ((live.length + 1) * live.length / 2);
    auto res = 0.0;
    foreach (i; 0 .. dead.length)
    {
        foreach (j; 0 .. live.length)
        {
            if (a[live[j]][dead[i]] > 0)
            {
                auto ret = saiki(mask | (1 << dead[i]), n, a, dp);
                res += ret * a[live[j]][dead[i]] * prob;
            }
        }
    }
    dp[mask] = res;
    return res;
}

void solve(double[][] a, int n)
{
    auto dp = new double[1 << n];
    fill(dp, -1);
    foreach (i; 0 .. n)
    {
        auto ret = saiki(1 << i, n, a, dp);
        writef("%.10f", ret);
        if (i < n - 1)
        {
            write(" ");
        }
    }
    writeln();
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new double[][](n, n);
        foreach (i; 0 .. n)
        {
            foreach (j; 0 .. n)
            {
                readf(" %f", &a[i][j]);
            }
            readln;
        }
        solve(a, n);
    }
    return 0;
}

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

double saiki(int mask, int n, double[][] a, double[] dp)
{
    if (dp[mask] != -1)
    {
        return dp[mask];
    }
    if (mask + 1 == 1 << n)
    {
        dp[mask] = 1.0;
        return 1.0;
    }
    int[] dead, live;
    foreach (i; 0 .. n)
    {
        if ((mask & (1 << i)) == 0)
        {
            dead ~= i;
        }
        else
        {
            live ~= i;
        }
    }
    auto prob = 1.0 / ((live.length + 1) * live.length / 2);
    auto res = 0.0;
    foreach (i; 0 .. dead.length)
    {
        foreach (j; 0 .. live.length)
        {
            if (a[live[j]][dead[i]] > 0)
            {
                auto ret = saiki(mask | (1 << dead[i]), n, a, dp);
                res += ret * a[live[j]][dead[i]] * prob;
            }
        }
    }
    dp[mask] = res;
    return res;
}

void solve(double[][] a, int n)
{
    auto dp = new double[1 << n];
    fill(dp, -1);
    foreach (i; 0 .. n)
    {
        auto ret = saiki(1 << i, n, a, dp);
        writef("%.6f", ret);
        if (i < n - 1)
        {
            write(" ");
        }
    }
    writeln();
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new double[][](n, n);
        foreach (i; 0 .. n)
        {
            foreach (j; 0 .. n)
            {
                readf(" %f", &a[i][j]);
            }
            readln;
        }
        solve(a, n);
    }
    return 0;
}