One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.A contest has just finished. There are n teams, numbered 1 through n. The i-th team has ti balloons and weight wi. It's guaranteed that ti doesn't exceed wi so nobody floats initially.Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.What is the best place Limak can get?

The first line of the standard input contains one integer n (2 ≤ n ≤ 300 000) — the number of teams. The i-th of n following lines contains two integers ti and wi (0 ≤ ti ≤ wi ≤ 1018) — respectively the number of balloons and the weight of the i-th team. Limak is a member of the first team.

Print one integer denoting the best place Limak can get.

NoteIn the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is: Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified. Limak gives 1 balloon to each of two teams with 16 balloons initially. Limak has 20 - 6 - 6 - 1 - 1 = 6 balloons. There are three other teams left and their numbers of balloons are 40, 14 and 2. Limak gets the third place because there are two teams with more balloons. In the second sample, Limak has the second place and he can't improve it.In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81 000 000 000, 5 000 000 000 and 46 000 000 000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7).

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

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

    long ct, cw;
    readf("%s %s", &ct, &cw);
    readln;

    Tuple!(long, long)[] arr;
    foreach (_; 0 .. n-1) {
        long t, w;
        readf("%s %s", &t, &w);
        readln;

        arr ~= tuple(t, w);
    }

    arr.schwartzSort!(x => x[0]);

    debug { arr.writeln; }

    auto rbt = make!(RedBlackTree!(long, "a < b", true));

    while (arr.back[0] > ct) {
        rbt.insert(arr.back[1] - arr.back[0] + 1);
        arr.popBack();
    }

    int ans = rbt.length.to!int + 1;
    while (!rbt.empty && rbt.front <= ct) {
        if (!rbt.empty && rbt.front <= ct) {
            ct -= rbt.front;
            rbt.removeFront();
        }

        while (!arr.empty && arr.back[0] > ct) {
            rbt.insert(arr.back[1] - arr.back[0] + 1);
            arr.popBack();
        }

        ans = min(ans, rbt.length + 1);
    }

    ans = min(ans, rbt.length + 1);

    ans.writeln;
}

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

void main()
{
	int n;
	while(input(&n))
	{
		long t,w;
		input(&t,&w);
		auto a=new pll[n-1];
		foreach(i;0..n-1) input(&a[i].fi,&a[i].se);
		sort(a);
		auto r=new long[n-1];
		foreach(i;0..n-1)r[i]=a[i].se-a[i].fi+1;
		int pos=upb(a,mp(t,long.max));
		auto q=rbt!(true,long)(r[pos..$]);
		int ans=q.length;
		while(!q.empty && t>=q.front)
		{
			t-=q.front;
			q.removeFront;
			int p=upb(a,mp(t,long.max));
			if(p<pos)q.insert(r[p..pos]);
			pos=p;
			ans=min(ans,q.length);
		}
		writeln(ans+1);
	}
	debug system("pause");
}

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

void main()
{
	int n;
	while(input(&n))
	{
		long t,w;
		input(&t,&w);
		auto a=new pll[n-1];
		foreach(i;0..n-1) input(&a[i].fi,&a[i].se);
		sort(a);
		auto r=new long[n-1];
		foreach(i;0..n-1)r[i]=a[i].se-a[i].fi+1;
		int pos=upb(a,mp(t,long.max));
		auto q=heapify(r[pos..$]);
		int ans=q.length;
		while(!q.empty && t>=q.front)
		{
			t-=q.front;
			q.removeFront;
			int p=upb(a,mp(t,long.max));
			foreach(i;r[p..pos])q.insert(i);
			pos=p;
			ans=min(ans,q.length);
		}
		writeln(ans+1);
	}
	debug system("pause");
}

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

void main()
{
	int n;
	while(input(&n))
	{
		long t,w;
		input(&t,&w);
		auto a=new pll[n-1];
		foreach(i;0..n-1) input(&a[i].fi,&a[i].se);
		sort(a);
		auto r=new long[n-1];
		foreach(i;0..n-1)r[i]=a[i].se-a[i].fi+1;
		int pos=upb(a,mp(t,long.max));
		auto q=rbt!(true,long)(r[pos..$]);
		int ans=q.length;
		while(pos>0 && !q.empty && t>=q.front)
		{
			t-=q.front;
			q.removeFront;
			int p=upb(a,mp(t,long.max));
			if(p<pos)q.insert(r[p..pos]);
			pos=p;
			ans=min(ans,q.length);
		}
		writeln(ans+1);
	}
	debug system("pause");
}

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

void main()
{
	int n;
	while(input(&n))
	{
		long t,w;
		input(&t,&w);
		auto a=new pll[n-1];
		foreach(i;0..n-1) input(&a[i].fi,&a[i].se);
		sort(a);
		auto r=new long[n-1];
		foreach(i;0..n-1)r[i]=a[i].se-a[i].fi+1;
		int pos=upb(a,mp(t,long.max));
		auto q=rbt!(true)(r[pos..$]);
		int ans=q.length;
		while(pos>0 && !q.empty && t>=q.front)
		{
			t-=q.front;
			q.removeFront;
			int p=upb(a,mp(t,long.max));
			q.insert(r[p..pos]);
			pos=p;
			ans=min(ans,q.length);
		}
		writeln(ans+1);
	}
	debug system("pause");
}


You're given an array $$$b$$$ of length $$$n$$$. Let's define another array $$$a$$$, also of length $$$n$$$, for which $$$a_i = 2^{b_i}$$$ ($$$1 \leq i \leq n$$$). Valerii says that every two non-intersecting subarrays of $$$a$$$ have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers $$$l_1,r_1,l_2,r_2$$$ that satisfy the following conditions:   $$$1 \leq l_1 \leq r_1 \lt l_2 \leq r_2 \leq n$$$;  $$$a_{l_1}+a_{l_1+1}+\ldots+a_{r_1-1}+a_{r_1} = a_{l_2}+a_{l_2+1}+\ldots+a_{r_2-1}+a_{r_2}$$$. If such four integers exist, you will prove Valerii wrong. Do they exist?An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of every test case contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$). The second line of every test case contains $$$n$$$ integers $$$b_1,b_2,\ldots,b_n$$$ ($$$0 \le b_i \le 10^9$$$).

For every test case, if there exist two non-intersecting subarrays in $$$a$$$ that have the same sum, output YES on a separate line. Otherwise, output NO on a separate line.  Also, note that each letter can be in any case.

NoteIn the first case, $$$a = [16,8,1,2,4,1]$$$. Choosing $$$l_1 = 1$$$, $$$r_1 = 1$$$, $$$l_2 = 2$$$ and $$$r_2 = 6$$$ works because $$$16 = (8+1+2+4+1)$$$.In the second case, you can verify that there is no way to select to such subarrays.

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 a = readln.splitter.map !(to !(int)).array;
		sort (a);
		writeln (a.isStrictlyMonotonic ? "NO" : "YES");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto b = RDA;

		bool[long] set;
		foreach (i; 0..n)
		{
			if (set.get(b[i], false))
			{
				ans[ti] = true;
				break;
			}
			set[b[i]] = true;
		}
	}

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


At Moscow Workshops ICPC team gets a balloon for each problem they solved first. Team MSU Red Panda got so many balloons that they didn't know how to spend them. So they came up with a problem with them.There are several balloons, not more than $$$10^6$$$ in total, each one is colored in one of $$$k$$$ colors. We can perform the following operation: choose $$$k-1$$$ balloons such that they are of $$$k-1$$$ different colors, and recolor them all into remaining color. We can perform this operation any finite number of times (for example, we can only perform the operation if there are at least $$$k-1$$$ different colors among current balls).How many different balloon configurations can we get? Only number of balloons of each color matters, configurations differing only by the order of balloons are counted as equal. As this number can be very large, output it modulo $$$998244353$$$.

The first line contains a single integer $$$k$$$ ($$$2 \le k \le 10^5$$$) —the number of colors. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0 \le a_i$$$) —initial configuration of balloons. $$$a_i$$$ is number of balloons of color $$$i$$$. The total number of balloons doesn't exceed $$$10^6$$$. In other words, $$$a_1 + a_2 + a_3 + \ldots + a_k \le 10^6$$$.

Output number of possible configurations modulo $$$998244353$$$.

NoteIn the first example, there are $$$3$$$ configurations we can get: $$$[0, 1, 2]$$$, $$$[2, 0, 1]$$$, $$$[1, 2, 0]$$$.In the second example, we can apply the operation not more than once, and possible configurations are: $$$[1, 1, 1, 1]$$$, $$$[0, 0, 0, 4]$$$, $$$[0, 0, 4, 0]$$$, $$$[0, 4, 0, 0]$$$, $$$[4, 0, 0, 0]$$$. In the third example, we can't apply any operations, so the only achievable configuration is the starting one.

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

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

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

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

enum long MO = 998244353;
enum LIM = 3 * 10^^6;

long[] inv, fac, invFac;
void prepare() {
  inv = new long[LIM];
  fac = new long[LIM];
  invFac = new long[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = MO - ((MO / i) * inv[cast(size_t)(MO % i)]) % MO;
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = (fac[i - 1] * i) % MO;
    invFac[i] = (invFac[i - 1] * inv[i]) % MO;
  }
}
long binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] % MO * invFac[cast(size_t)(n - k)] % MO;
  } else {
    return 0;
  }
}

int K;
int[] A;

void main() {
  prepare();

  //*
  debug {
    {
      enum s = [0, 1, 2, 2, 2];
      K = cast(int)(s.length);
      enum lim = s.sum + 1;
      auto vis = new bool[lim^^K];
      int encode(int[] u) {
        int ret;
        foreach (i; 0 .. K) ret += u[i] * lim^^i;
        return ret;
      }
      DList!(int[]) q;
      vis[encode(s)] = true;
      q.insertBack(s);
      for (; !q.empty; ) {
        const u = q.front;
        q.removeFront;
        foreach (i; 0 .. K) {
          auto v = u.dup;
          v[] -= 1;
          v[i] += K;
          if (v.all!"a >= 0") {
            if (!vis[encode(v)]) {
              vis[encode(v)] = true;
              q.insertBack(v);
            }
          }
        }
      }
      int cntAll;
      int cnt;
      foreach (key; 0 .. lim^^K) {
        auto u = iota(K).map!(i => (key / lim^^i % lim)).array;
        bool ok = (s.sum == u.sum);
        foreach (i; 1 .. K) {
          ok = ok && (((u[i] - u[0]) - (s[i] - s[0])) % K == 0);
        }
        if (ok) {
          ++cntAll;
        }
        if (vis[encode(u)]) {
          ++cnt;
          writeln(u);
        }
      }
      writeln(cntAll, " ", cnt);
    }
  }
  //*/

  try {
    for (; ; ) {
      K = readInt();
      A = new int[K];
      foreach (i; 0 .. K) {
        A[i] = readInt();
      }

      long ans;

      A.sort;
      bool ok = true;
      /*
      foreach (i; 0 .. K) {
        if (A[i] > i) {
          break;
        }
        if (A[i] < i) {
          ans = i;
          ok = false;
          break;
        }
      }
      */
      foreach (i; 0 .. K) {
        if (A[i] < i) {
          A[i + 1 .. $] = A[i];
          break;
        }
      }

      if (ok) {
        int s;
        auto f = new int[K];
        foreach (i; 0 .. K) {
          s += A[i] / K;
          ++f[A[i] % K];
        }
        foreach (i; 0 .. K) {
          if (s >= 0) {
            // multi-choose s times from K
            ans += binom(K + s - 1, K - 1);
            ans %= MO;
          }
          s -= 1;
          s += f[K - 1 - i];
        }
      }
      ans = (ans % MO + MO) % MO;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum long MO = 998244353;
enum LIM = 3 * 10^^6;

long[] inv, fac, invFac;
void prepare() {
  inv = new long[LIM];
  fac = new long[LIM];
  invFac = new long[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = MO - ((MO / i) * inv[cast(size_t)(MO % i)]) % MO;
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = (fac[i - 1] * i) % MO;
    invFac[i] = (invFac[i - 1] * inv[i]) % MO;
  }
}
long binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] % MO * invFac[cast(size_t)(n - k)] % MO;
  } else {
    return 0;
  }
}

int K;
int[] A;

void main() {
  prepare();

  /*
  debug {
    enum lim = 10;
    auto vis = new bool[][][][](lim, lim, lim, lim);
    enum a0 = 3, b0 = 1, c0 = 5, d0 = 0;
    vis[a0][b0][c0][d0] = true;
    foreach (iter; 0 .. lim^^4) {
      foreach (a; 0 .. lim) foreach (b; 0 .. lim) foreach (c; 0 .. lim) foreach (d; 0 .. lim) {
        if (vis[a][b][c][d]) {
          if (b > 0 && c > 0 && d > 0) vis[a + 3][b - 1][c - 1][d - 1] = true;
          if (a > 0 && c > 0 && d > 0) vis[a - 1][b + 3][c - 1][d - 1] = true;
          if (a > 0 && b > 0 && d > 0) vis[a - 1][b - 1][c + 3][d - 1] = true;
          if (a > 0 && b > 0 && c > 0) vis[a - 1][b - 1][c - 1][d + 3] = true;
        }
      }
    }
    int cntAll;
    int cnt;
    foreach (a; 0 .. lim) foreach (b; 0 .. lim) foreach (c; 0 .. lim) foreach (d; 0 .. lim) {
      if (a0 + b0 + c0 + d0 == a + b + c + d &&
          ((b - a) - (b0 - a0)) % 4 == 0 &&
          ((c - a) - (c0 - a0)) % 4 == 0 &&
          ((d - a) - (d0 - a0)) % 4 == 0) {
        ++cntAll;
      }
      if (vis[a][b][c][d]) {
        ++cnt;
      }
    }
    writeln(cntAll, " ", cnt);
  }
  */

  try {
    for (; ; ) {
      K = readInt();
      A = new int[K];
      foreach (i; 0 .. K) {
        A[i] = readInt();
      }

      long ans;
      const cntZero = A.count(0);
      if (cntZero >= 2) {
        ans = 1;
      } else {
        int s;
        auto f = new int[K];
        foreach (i; 0 .. K) {
          s += A[i] / K;
          ++f[A[i] % K];
        }
        foreach (i; 0 .. K) {
          if (s >= 0) {
            // multi-choose s times from K
            ans += binom(K + s - 1, K - 1);
            ans %= MO;
          }
          --s;
          s += f[K - 1 - i];
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum long MO = 998244353;
enum LIM = 3 * 10^^6;

long[] inv, fac, invFac;
void prepare() {
  inv = new long[LIM];
  fac = new long[LIM];
  invFac = new long[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = MO - ((MO / i) * inv[cast(size_t)(MO % i)]) % MO;
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = (fac[i - 1] * i) % MO;
    invFac[i] = (invFac[i - 1] * inv[i]) % MO;
  }
}
long binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] % MO * invFac[cast(size_t)(n - k)] % MO;
  } else {
    return 0;
  }
}

int K;
int[] A;

void main() {
  prepare();

  /*
  debug {
    enum lim = 10;
    auto vis = new bool[][][][](lim, lim, lim, lim);
    enum a0 = 0, b0 = 1, c0 = 2, d0 = 6;
    vis[a0][b0][c0][d0] = true;
    foreach (iter; 0 .. lim^^4) {
      foreach (a; 0 .. lim) foreach (b; 0 .. lim) foreach (c; 0 .. lim) foreach (d; 0 .. lim) {
        if (vis[a][b][c][d]) {
          if (b > 0 && c > 0 && d > 0) vis[a + 3][b - 1][c - 1][d - 1] = true;
          if (a > 0 && c > 0 && d > 0) vis[a - 1][b + 3][c - 1][d - 1] = true;
          if (a > 0 && b > 0 && d > 0) vis[a - 1][b - 1][c + 3][d - 1] = true;
          if (a > 0 && b > 0 && c > 0) vis[a - 1][b - 1][c - 1][d + 3] = true;
        }
      }
    }
    int cntAll;
    int cnt;
    foreach (a; 0 .. lim) foreach (b; 0 .. lim) foreach (c; 0 .. lim) foreach (d; 0 .. lim) {
      if (a0 + b0 + c0 + d0 == a + b + c + d &&
          ((b - a) - (b0 - a0)) % 4 == 0 &&
          ((c - a) - (c0 - a0)) % 4 == 0 &&
          ((d - a) - (d0 - a0)) % 4 == 0) {
        ++cntAll;
      }
      if (vis[a][b][c][d]) {
// writeln(a," ",b," ",c," ",d);
        ++cnt;
      }
    }
    writeln(cntAll, " ", cnt);
  }
  //*/

  try {
    for (; ; ) {
      K = readInt();
      A = new int[K];
      foreach (i; 0 .. K) {
        A[i] = readInt();
      }

      long ans;

      A.sort;
      bool ok = true;
      foreach (i; 0 .. K) {
        if (A[i] > i) {
          break;
        }
        if (A[i] < i) {
          ans = i;
          ok = false;
          break;
        }
      }

      if (ok) {
        int s;
        auto f = new int[K];
        foreach (i; 0 .. K) {
          s += A[i] / K;
          ++f[A[i] % K];
        }
        foreach (i; 0 .. K) {
          if (s >= 0) {
            // multi-choose s times from K
            ans += binom(K + s - 1, K - 1);
            ans %= MO;
          }
          s -= 1;
          s += f[K - 1 - i];
        }
      }
      ans = (ans % MO + MO) % MO;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


A bracket sequence is a string containing only characters "(" and ")".A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.You are given $$$n$$$ bracket sequences $$$s_1, s_2, \dots , s_n$$$. Calculate the number of pairs $$$i, j \, (1 \le i, j \le n)$$$ such that the bracket sequence $$$s_i + s_j$$$ is a regular bracket sequence. Operation $$$+$$$ means concatenation i.e. "()(" + ")()" = "()()()".If $$$s_i + s_j$$$ and $$$s_j + s_i$$$ are regular bracket sequences and $$$i \ne j$$$, then both pairs $$$(i, j)$$$ and $$$(j, i)$$$ must be counted in the answer. Also, if $$$s_i + s_i$$$ is a regular bracket sequence, the pair $$$(i, i)$$$ must be counted in the answer.

The first line contains one integer $$$n \, (1 \le n \le 3 \cdot 10^5)$$$ — the number of bracket sequences. The following $$$n$$$ lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed $$$3 \cdot 10^5$$$.

In the single line print a single integer — the number of pairs $$$i, j \, (1 \le i, j \le n)$$$ such that the bracket sequence $$$s_i + s_j$$$ is a regular bracket sequence.

NoteIn the first example, suitable pairs are $$$(3, 1)$$$ and $$$(2, 2)$$$.In the second example, any pair is suitable, namely $$$(1, 1), (1, 2), (2, 1), (2, 2)$$$.

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

immutable long MOD = 10^^9+7;

void main() {
    auto N = readln.chomp.to!int;
    auto S = N.iota.map!(_ => readln.chomp).array;
    auto cnts = new int[](N);
    auto mns = new int[](N);
    int[int] mn;

    foreach (i, s; S.enumerate) {
        int cnt = 0;
        int minv = 0;
        foreach (c; s) {
            cnt += c == '(' ? 1 : -1;
            minv = min(minv, cnt);
        }
        cnts[i] = cnt;
        mns[i] = minv;
        if (minv == cnts[i]) mn[minv] += 1;
    }

    long ans = 0;
    foreach (i; 0..N) {
        if (mns[i] < 0) continue;
        if (-cnts[i] !in mn) continue;
        ans += mn[-cnts[i]];
    }

    ans.writeln;
}

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

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

    string[] strs;
    foreach (_; 0..n) strs ~= readln.chomp;

    long ans = 0;
    int [int] v;
    foreach (s; strs) {
        int sc = 0, lo = 0;
        foreach (c; s) {
            if (c == '(') ++sc;
            else {
                --sc;
                lo = min(lo, sc);
            }
        }

        debug { writeln(s, ' ', sc, ' ', lo); }

        if (lo < 0 && lo < sc) continue;

        ans += sc == 0 ? v.get(0, 0) * 2 + 1 : v.get(-sc, 0);
        v[sc] += 1;
    }

    ans.writeln;
}

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

  int n; rd(n);
  long[int] freq;
  auto y=new int[](n);
  auto ng=new bool[](n);
  foreach(i; 0..n){
    auto s=readln.chomp.to!(char[]);
    char[] st;
    foreach(c; s){
      if(c=='('){
        st~='(';
      }else{
        if(st.length>0){
          if(st.back=='(') st=st[0..($-1)];
          else st~=')';
        }else{
          st~=')';
        }
      }
    }
    int x=0;
    foreach(c; st){
      if(c=='(') x++;
      else x--;
    }
    if(st.length>=2 && (st[0]==')' && st[$-1]=='(')){ng[i]=true; continue;}
    y[i]=x;
    if(x in freq) freq[x]++;
    else freq[x]=1;
    hell:;
  }

  long tot=0;
  foreach(i; 0..n)if(ng[i]==false){
    if(y[i]>=0 && (-y[i] in freq)){
      tot+=freq[-y[i]];
    }
    // writeln(tot);
  }

  writeln(tot);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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

  int n; rd(n);
  long[int] freq;
  auto y=new int[](n);
  auto ng=new bool[](n);
  foreach(i; 0..n){
    auto s=readln.chomp.to!(char[]);
    char[] st;
    foreach(c; s){
      if(c=='('){
        st~='(';
      }else{
        if(st.length>0){
          if(st.back=='(') st=st[0..($-1)];
          else st~=')';
        }else{
          st~=')';
        }
      }
    }
    int x=0;
    foreach(c; st){
      if(c=='(') x++;
      else x--;
    }
    if(st.length>=2 && (st[0]==')' && st[$-1]=='(')) continue;
    y[i]=x;
    if(x in freq) freq[x]++;
    else freq[x]=1;
    hell:;
  }

  long tot=0;
  foreach(i; 0..n)if(ng[i]==false){
    if(y[i]>=0 && (-y[i] in freq)){
      tot+=freq[-y[i]];
    }
    // writeln(tot);
  }

  writeln(tot);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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

  int n; rd(n);
  long[int] freq;
  auto y=new int[](n);
  auto ng=new bool[](n);
  foreach(i; 0..n){
    auto s=readln.chomp.to!(char[]);
    int x=0;
    foreach(c; s){
      if(c=='('){
        if(x<0){ng[i]=true; goto hell;}
        else x++;
      }else{
        x--;
      }
    }
    y[i]=x;
    if(x in freq) freq[x]++;
    else freq[x]=1;
    hell:;
  }

  long tot=0;
  foreach(i; 0..n)if(ng[i]==false){
    if(y[i]>=0 && (-y[i] in freq)){
      tot+=freq[-y[i]];
      if(freq[y[i]]==0) tot--;
    }
    // writeln(tot);
  }

  writeln(tot);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1  +  a2 ...  +  ak,  a2  +  a3  +  ...  +  ak + 1,  ...,  an - k + 1  +  an - k + 2  +  ...  +  an), then those numbers will form strictly increasing sequence.For example, for the following sample: n = 5,  k = 3,  a = (1,  2,  4,  5,  6) the sequence of numbers will look as follows: (1  +  2  +  4,  2  +  4  +  5,  4  +  5  +  6) = (7,  11,  15), that means that sequence a meets the described property. Obviously the sequence of sums will have n - k + 1 elements.Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains n space-separated elements ai (1 ≤ i ≤ n). If ai  =  ?, then the i-th element of Arthur's sequence was replaced by a question mark.  Otherwise, ai ( - 109 ≤ ai ≤ 109) is the i-th element of Arthur's sequence.

If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes). Otherwise, print n integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.

0 1 2
-10 -9 -8 -7 -6
Incorrect sequence

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

immutable int TODO = 1_234_567_890;

void main ()
{
	int n, k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto a = readln ().split ()
		    .map !(x => x == "?" ? TODO : x.to !(int)).array;
		foreach (s; 0..k)
		{
			a ~= TODO - 1;
		}

		void go (int lo, int hi)
		{
			if (lo >= hi)
			{
				return;
			}
			int blo = lo >= k ? a[lo - k] : -TODO + 1;
			int bhi = a[hi];
			int len = (hi - lo) / k;
			int vlo = -len / 2;
			int vhi = vlo + len - 1;
			if (vlo <= blo)
			{
				vlo = blo + 1;
				vhi = vlo + len - 1;
			}
			if (vhi >= bhi)
			{
				vhi = bhi - 1;
				vlo = vhi - len + 1;
			}
			for (int i = lo; i < hi; i += k)
			{
				a[i] = vlo;
				vlo++;
			}
		}

		foreach (s; 0..k)
		{
			int lo = s;
			int hi = s;
			for (int i = s; i < n + k; i += k)
			{
				if (a[i] == TODO)
				{
					hi = i + k;
				}
				else
				{
					go (lo, hi);
					lo = hi = i + k;
				}
			}
		}

		bool ok = true;
		foreach (i; 0..n)
		{
			ok &= (a[i] < a[i + k]);
		}

		if (ok)
		{
			writefln ("%(%s %)", a[0..n]);
		}
		else
		{
			writeln ("Incorrect sequence");
		}
	}
}


You have a multiset containing several integers. Initially, it contains $$$a_1$$$ elements equal to $$$1$$$, $$$a_2$$$ elements equal to $$$2$$$, ..., $$$a_n$$$ elements equal to $$$n$$$.You may apply two types of operations:  choose two integers $$$l$$$ and $$$r$$$ ($$$l \le r$$$), then remove one occurrence of $$$l$$$, one occurrence of $$$l + 1$$$, ..., one occurrence of $$$r$$$ from the multiset. This operation can be applied only if each number from $$$l$$$ to $$$r$$$ occurs at least once in the multiset;  choose two integers $$$i$$$ and $$$x$$$ ($$$x \ge 1$$$), then remove $$$x$$$ occurrences of $$$i$$$ from the multiset. This operation can be applied only if the multiset contains at least $$$x$$$ occurrences of $$$i$$$. What is the minimum number of operations required to delete all elements from the multiset?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$).

Print one integer — the minimum number of operations required to delete all elements from the multiset.

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

int solve (int [] a)
{
	if (a.empty)
	{
		return 0;
	}
	auto n = a.length.to !(int);
	auto m = a.minElement;
	a[] -= m;
	int lo = 0;
	int res = m;
	foreach (i; 0..n + 1)
	{
		if (i == n || a[i] == 0)
		{
			res += solve (a[lo..i]);
			lo = i + 1;
		}
	}
	return min (res, n);
}

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (solve (a));
	}
}


Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries:  "+ x" — add integer x to multiset A. "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x" — you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.

The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A.

For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.

NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer  — maximum among integers , , ,  and .

import std.stdio;
import std.container;
int sz(t)(ref t x){return cast(int)x.length;}

struct trie{
    int[][] tr;
    int[] c;
    int root=1,cur=1;
    this(int n){
        tr=new int[][](n,2);
        c=new int[n];
        update(0,1);
    }
    void update(int x,int v){
        int n=root;
        c[n]+=v;
        for(int i=29;i>=0;i--){
            int k=(x>>i)&1;
            if(tr[n][k]==0){
                ++cur;
                tr[n][k]=cur;
            }
            n=tr[n][k];
            c[n]+=v;
        }
    }
    int query(int x){
        int n=root,r=0;
        for(int i=29;i>=0;i--){
            int k=(x>>i)&1;
            if(tr[n][k^1]==0 || c[tr[n][k^1]]==0) r=r;
            else{
                r^=(1<<i);
                k^=1;
            }
            n=tr[n][k];
        }
        return r;
    }
}

void main(){
    const int nmax=7_000_001;
    auto tr=new trie(nmax);
    int q,x;
    string s;
    readf!"%d"(q);
    readln;
    while(q--){
        readf!"%s %d"(s,x);
        readln;
        if(s=="+") tr.update(x,1);
        else if(s=="-") tr.update(x,-1);
        else tr.query(x).writeln;
    }
}

import std.stdio;
import std.container;
int sz(t)(ref t x){return cast(int)x.length;}

struct trie{
    int[][] tr;
    int[] c;
    int root=1,cur=1;
    this(int n){
        tr=new int[][](n,2);
        c=new int[n];
        update(0,1);
    }
    void update(int x,int v){
        int n=root;
        c[n]+=v;
        for(int i=29;i>=0;i--){
            int k=(x>>i)&1;
            if(tr[n][k]==0){
                ++cur;
                tr[n][k]=cur;
            }
            n=tr[n][k];
            c[n]+=v;
        }
    }
    int query(int x){
        int n=root,r=0;
        for(int i=29;i>=0;i--){
            int k=(x>>i)&1;
            if(tr[n][k^1]==0 || c[tr[n][k^1]]==0) r=r;
            else{
                r^=(1<<i);
                k^=1;
            }
            n=tr[n][k];
        }
        return r;
    }
}

void main(){
    const int nmax=6_000_001;
    auto tr=new trie(nmax);
    int q,x;
    string s;
    readf!"%d"(q);
    readln;
    while(q--){
        readf!"%s %d"(s,x);
        readln;
        if(s=="+") tr.update(x,1);
        else if(s=="-") tr.update(x,-1);
        else tr.query(x).writeln;
    }
}


Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k ≥ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.

The first line contains string s (1 ≤ |s| ≤ 106), that is the binary representation of number n without leading zeroes (n > 0).

Print a single integer — the minimum amount of beautiful numbers that give a total of n.

NoteIn the first sample n = 2 is a beautiful number.In the second sample n = 7 and Valera can decompose it into sum 23 + ( - 20).In the third sample n = 109 can be decomposed into the sum of four summands as follows: 27 + ( - 24) + ( - 22) + 20.

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

void main(string[] args)
{
  inputFile = stdin;
  auto s = next!string;
  s = '0' ~ s ~ '0';
  auto p = new int[](s.length - 1);
  foreach(i; 0 .. s.length - 1)
    {
      if (s[i..i+2] == "01")
	{
	  p[i] = 1;
	}
      if (s[i..i+2] == "10")
	{
	  p[i] = -1;
	}
    }
  for(int i = 0; i < p.length - 1; i++)
    {
      auto sl = p[i..i+2];
      if (sl[] == [1, -1])
	{
	  sl[] = [0, 1];
	  i++;
	  continue;
	}
      if (sl[] == [-1, 1])
	{
	  sl[] = [0, -1];
	  i++;
	  continue;
	}
    }
  p.count!(pi => pi != 0).writeln;
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  string toString()
  {
    return to!string(rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $$$n$$$ integers, now it's time to distribute them between his friends rationally...Lee has $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in his backpack and he has $$$k$$$ friends. Lee would like to distribute all integers in his backpack between his friends, such that the $$$i$$$-th friend will get exactly $$$w_i$$$ integers and each integer will be handed over to exactly one friend.Let's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.Lee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next $$$3t$$$ lines contain test cases — one per three lines. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — the number of integers Lee has and the number of Lee's friends. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the integers Lee has. The third line contains $$$k$$$ integers $$$w_1, w_2, \ldots, w_k$$$ ($$$1 \le w_i \le n$$$; $$$w_1 + w_2 + \ldots + w_k = n$$$) — the number of integers Lee wants to give to each friend.  It's guaranteed that the sum of $$$n$$$ over test cases is less than or equal to $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum sum of happiness Lee can achieve.

NoteIn the first test case, Lee should give the greatest integer to the first friend (his happiness will be $$$17 + 17$$$) and remaining integers to the second friend (his happiness will be $$$13 + 1$$$).In the second test case, Lee should give $$$\{10, 10, 11\}$$$ to the first friend and to the second friend, so the total happiness will be equal to $$$(11 + 10) + (11 + 10)$$$In the third test case, Lee has four friends and four integers, it doesn't matter how he distributes the integers between his friends.

import std.stdio;
import std.range;
import std.algorithm;

void main() {
	int t;
	scanf("%d", &t);

	while (t--) {
		int n, k;
		scanf("%d%d", &n, &k);

		long[] arr = new long[n];
		foreach (i; iota(n)) scanf("%lld", &arr[i]);

		int[] cnt = new int[k];
		foreach (i; iota(k)) scanf("%d", &cnt[i]);

		sort(arr);
		sort(cnt);

		int largest_index = n - 1;
		int smallest_index = 0;

		long res = 0;

		for (int i = 0; i < n && cnt[i] == 1; i++) {
			res += 2 * arr[largest_index--];
		}

		for (int i = cnt.length - 1; i >= 0 && cnt[i] > 1; i--) {
			res += arr[largest_index--];
			res += arr[smallest_index];
			smallest_index += cnt[i] - 1;
		}

		res.writeln;
	}
}

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, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto w = readln.splitter.map !(to !(int)).array;
		sort (w);
		long res = 0;
		while (!w.empty && w.front == 1)
		{
			res += a[$ - 1] * 2;
			a = a[0..$ - 1];
			w.popFront ();
		}
		reverse (w);
		foreach (c; w)
		{
			res += a[0] + a[$ - 1];
			a = a[c - 1..$ - 1];
		}
		writeln (res);
	}
}

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

DList!string _words;

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

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

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

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

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

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

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

    }
}

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

void main()
{
  int t;
  read(t);
  while(t--)
    {
      long n, k;
      read(n, k);
      auto a = makeArray!long(n, next!long);
      auto w = makeArray!long(k, next!long);
      auto sa = sort(a[]);
      auto sw = sort(w[]);
      size_t i = 0;
      size_t pi = -1;
      long res = 0;
      long[] nw = null;
      foreach(ref wi; sw)
        {
          if (wi == 1)
            {
              res += 2 * sa.back;
              sa.popBack;
            }
          else
            {
              res += sa.back;
              sa.popBack;
              nw ~= wi - 1;
            }
        }
      foreach_reverse(wi; nw)
        {
          res += sa.at(i);
          i += wi;
        }
      writeln(res);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		debug writeln(a);
		a.sort!"a > b";
		w.sort;
		debug writeln(a);
		foreach (i; 0..k)
		{
			debug writeln("w[i]:", w[i], " ", a);
			if (w[i] == 1)
			{
				ans[ti] += a.front * 2; a.popFront;
			}
			else
			{
				ans[ti] += a.front; a.popFront;
			}
			if (w[i] == 2)
			{
				ans[ti] += a.front; a.popFront;
			}
		}
		foreach (i; 0..k)
		{
			debug writeln("w[i]:", w[i], " ", a);
			if (w[i] <= 2) continue;
			foreach (j; 0..w[i]-2)
			{
				a.popFront;
			}
			ans[ti] += a.front; a.popFront;
		}
	}

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


Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.  Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.

The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line.

If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$.

NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto A = new int[][](4, N);
      foreach (x; 0 .. 4) foreach (y; 0 .. N) {
        A[x][y] = readInt();
      }

      auto a = new int[][](4, N);
      foreach (x; 0 .. 4) foreach (y; 0 .. N) {
        a[x][y] = A[x][y];
      }

      int[] xs, ys;
      foreach (y; 0 .. N) {
        xs ~= 1;
        ys ~= y;
      }
      foreach_reverse (y; 0 .. N) {
        xs ~= 2;
        ys ~= y;
      }
      const len = cast(int)(xs.length);

      int[][] ans;

      for (; ; ) {
        bool ok = true;
        foreach (x; [1, 2]) foreach (y; 0 .. N) {
          if (a[x][y] != 0) {
            if (a[x][y] == a[x ^ 1][y]) {
              ans ~= [a[x][y], x ^ 1, y];
              a[x][y] = 0;
            } else {
              ok = false;
            }
          }
        }
        if (ok) {
          break;
        }
        int i0 = -1;
        foreach (i; 0 .. len) {
          if (a[xs[i]][ys[i]] == 0) {
            i0 = i;
            break;
          }
        }
        if (i0 == -1) {
          writeln(-1);
          goto failed;
        }
        foreach (di; 0 .. len - 1) {
          const i = (i0 + di) % len;
          const j = (i0 + di + 1) % len;
          if (a[xs[j]][ys[j]] != 0) {
            assert(a[xs[i]][ys[i]] == 0);
            ans ~= [a[xs[j]][ys[j]], xs[i], ys[i]];
            swap(a[xs[i]][ys[i]], a[xs[j]][ys[j]]);
          }
        }
      }

      writeln(ans.length);
      foreach (move; ans) {
        writeln(move[0], " ", move[1] + 1, " ", move[2] + 1);
      }
     failed:
    }
  } catch (EOFException e) {
  }
}


You are given an array $$$a_1, a_2, \dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ and $$$a_{1 \dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of good subarrays of the array $$$a$$$.

NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ and $$$a_{4 \dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \dots 6}$$$.

// Vicfred
// https://codeforces.com/contest/1398/problem/C
//
import std.conv;
import std.stdio;
import std.string;

void main() {
    long t = readln.chomp.to!long;
    while(t--) {
        long n = readln.chomp.to!long;
        string s = readln.strip;

        long[] a;

        foreach(ch; s)
            a ~= ch - '0';

        long[long] counter;
        counter[0] = 1;

        long cumulative = 0;
        long ans = 0;

        for(int i = 0; i < n; ++i) {
            cumulative += a[i];
            //writefln("cumulative: %s", cumulative);

            long x = cumulative - i - 1;

            //writefln("buscando %s", x);

            if(counter.get(x, -1) == -1)
                counter[x] = 0;
            counter[x] += 1;

            //writefln("counter de %s: %s", x, counter[x]);

            ans += counter[x] - 1;
        }

        ans.writeln;
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.strip.map !(q{a - '0'}).array;
		a[] -= 1;
		int [int] f;
		f[0] = 1;
		int cur = 0;
		long res = 0;
		foreach (ref c; a)
		{
			cur += c;
			f[cur] += 1;
			res += f[cur] - 1;
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		int[int] cnt;
		cnt[0] = 1;
		int x;
		foreach (i; 0..n)
		{
			x += s[i] - '0';
			auto y = x-i-1;
			ans[ti] += cnt.get(y, 0);
			cnt[y] += 1;
			debug writeln(ans[ti]);
		}
	}

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		int[int] cnt;
		cnt[0] = 1;
		int x;
		foreach (i; 0..n)
		{
			x += s[i] - '0';
			auto y = x-i-1;
			ans[ti] += cnt.get(y, 0);
			cnt[y] += 1;
			debug writeln(ans[ti]);
		}
	}

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


Byteland is a beautiful land known because of its beautiful trees.Misha has found a binary tree with $$$n$$$ vertices, numbered from $$$1$$$ to $$$n$$$. A binary tree is an acyclic connected bidirectional graph containing $$$n$$$ vertices and $$$n - 1$$$ edges. Each vertex has a degree at most $$$3$$$, whereas the root is the vertex with the number $$$1$$$ and it has a degree at most $$$2$$$.Unfortunately, the root got infected.The following process happens $$$n$$$ times:  Misha either chooses a non-infected (and not deleted) vertex and deletes it with all edges which have an end in this vertex or just does nothing.  Then, the infection spreads to each vertex that is connected by an edge to an already infected vertex (all already infected vertices remain infected). As Misha does not have much time to think, please tell him what is the maximum number of vertices he can save from the infection (note that deleted vertices are not counted as saved).

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 5000$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2\leq n\leq 3\cdot 10^5$$$) — the number of vertices of the tree.  The $$$i$$$-th of the following $$$n-1$$$ lines in the test case contains two positive integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), meaning that there exists an edge between them in the graph.  It is guaranteed that the graph is a binary tree rooted at $$$1$$$. It is also guaranteed that the sum of $$$n$$$ over all test cases won't exceed $$$3\cdot 10^5$$$.

For each test case, output the maximum number of vertices Misha can save.

NoteIn the first test case, the only possible action is to delete vertex $$$2$$$, after which we save $$$0$$$ vertices in total.In the second test case, if we delete vertex $$$2$$$, we can save vertices $$$3$$$ and $$$4$$$.

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

void solve() {
    int N = readln.chomp.to!int;
    int[][] G = new int[][N];
    foreach (i; 1 .. N) {
        int a, b;
        readf("%d %d\n", &a, &b);
        a--; b--;
        G[a] ~= b;
        G[b] ~= a;
    }

    int[] s = new int[N];
    int calc(int v, int p) {
        int[] next;
        foreach (n; G[v]) {
            if (n == p) continue;
            next ~= n;
        }
        if (next.length == 2) {
            int l = next[0], r = next[1];
            return s[v] = calc(l, v) + calc(r, v) + 1;
        } else if (next.length == 1) {
            int l = next[0];
            return s[v] = calc(l, v) + 1;
        } else {
            return s[v] = 1;
        }
    }
    calc(0, -1);
    //writeln(s);

    int f(int v, int p) {
        int[] next;
        foreach (n; G[v]) {
            if (n == p) continue;
            next ~= n;
        }
        if (next.length == 2) {
            int l = next[0], r = next[1];
            return max(s[l] - 1 + f(r, v), s[r] - 1 + f(l, v));
        } else if (next.length == 1) {
            int l = next[0];
            return s[l] - 1;
        } else {
            return 0;
        }
    }
    writeln(f(0, -1));
}

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


There is a grid with $$$r$$$ rows and $$$c$$$ columns, where the square on the $$$i$$$-th row and $$$j$$$-th column has an integer $$$a_{i, j}$$$ written on it. Initially, all elements are set to $$$0$$$. We are allowed to do the following operation:  Choose indices $$$1 \le i \le r$$$ and $$$1 \le j \le c$$$, then replace all values on the same row or column as $$$(i, j)$$$ with the value xor $$$1$$$. In other words, for all $$$a_{x, y}$$$ where $$$x=i$$$ or $$$y=j$$$ or both, replace $$$a_{x, y}$$$ with $$$a_{x, y}$$$ xor $$$1$$$. You want to form grid $$$b$$$ by doing the above operations a finite number of times. However, some elements of $$$b$$$ are missing and are replaced with '?' instead.Let $$$k$$$ be the number of '?' characters. Among all the $$$2^k$$$ ways of filling up the grid $$$b$$$ by replacing each '?' with '0' or '1', count the number of grids, that can be formed by doing the above operation a finite number of times, starting from the grid filled with $$$0$$$. As this number can be large, output it modulo $$$998244353$$$.

The first line contains two integers $$$r$$$ and $$$c$$$ ($$$1 \le r, c \le 2000$$$)  — the number of rows and columns of the grid respectively. The $$$i$$$-th of the next $$$r$$$ lines contain $$$c$$$ characters $$$b_{i, 1}, b_{i, 2}, \ldots, b_{i, c}$$$ ($$$b_{i, j} \in \{0, 1, ?\}$$$).

Print a single integer representing the number of ways to fill up grid $$$b$$$ modulo $$$998244353$$$.

NoteIn the first test case, the only way to fill in the $$$\texttt{?}$$$s is to fill it in as such: 010111010 This can be accomplished by doing a single operation by choosing $$$(i,j)=(2,2)$$$.In the second test case, it can be shown that there is no sequence of operations that can produce that grid.

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

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

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

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

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

enum MO = 998244353;
alias Mint = ModInt!MO;

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

void main() {
  debug {{
    enum lim = 10;
    foreach (m; 1 .. lim + 1) {
      foreach (n; 1 .. lim + 1) {
        int r;
        if (m % 2 != 0) {
          if (n % 2 != 0) {
            r = m * n - (m - 1) - (n - 1);
          } else {
            r = m * n - (n - 1);
          }
        } else {
          if (n % 2 != 0) {
            r = m * n - (m - 1);
          } else {
            r = m * n;
          }
        }
        write(r, " ");
      }
      writeln;
    }
    // return;
  }}

  try {
    for (; ; ) {
      const M = readInt;
      const N = readInt;
      auto A = new string[M];
      foreach (x; 0 .. M) {
        A[x] = readToken;
      }

      Mint ans;
      if (M % 2 != 0) {
        if (N % 2 != 0) {
          auto uf = new int[M + N];
          uf[] = -1;
          auto rows = new int[M];
          auto cols = new int[N];
          foreach (x; 0 .. M) foreach (y; 0 .. N) {
            if (A[x][y] == '?') {
              uf.connect(x, M + y);
            } else {
              rows[x] ^= (A[x][y] - '0');
              cols[y] ^= (A[x][y] - '0');
            }
          }
          auto es = new int[M + N];
          auto fs = new int[M + N];
          auto gs = new int[M + N];
          auto ss = new int[M + N];
          foreach (x; 0 .. M) foreach (y; 0 .. N) if (A[x][y] == '?') {
            const r = uf.root(x);
            ++es[r];
          }
          foreach (x; 0 .. M) {
            const r = uf.root(x);
            fs[r] ^= 1;
            ss[r] ^= rows[x];
          }
          foreach (y; 0 .. N) {
            const r = uf.root(M + y);
            gs[r] ^= 1;
            ss[r] ^= cols[y];
          }

          foreach (p; 0 .. 2) foreach (q; 0 .. 2) {
            bool ok = true;
            int e;
            foreach (r; 0 .. M + N) if (uf[r] < 0) {
              ok = ok && (((p & fs[r]) ^ (q & gs[r])) == ss[r]);
              e += (es[r] - ((-uf[r]) - 1));
            }
            if (ok) {
              ans += Mint(2)^^e;
            }
          }
        } else {
          Mint[2] nums;
          nums[0] = nums[1] = 1;
          foreach (y; 0 .. N) {
            int cnt, sum;
              foreach (x; 0 .. M) {
              if (A[x][y] == '?') {
                ++cnt;
              } else {
                sum ^= (A[x][y] - '0');
              }
            }
            if (cnt == 0) {
              nums[sum ^ 1] = 0;
            } else {
              const two = Mint(2)^^(cnt - 1);
              nums[0] *= two;
              nums[1] *= two;
            }
          }
          debug {
            writeln("nums = ", nums);
          }
          ans = nums[0] + nums[1];
        }
      } else {
        if (N % 2 != 0) {
          Mint[2] nums;
          nums[0] = nums[1] = 1;
          foreach (x; 0 .. M) {
            int cnt, sum;
            foreach (y; 0 .. N) {
              if (A[x][y] == '?') {
                ++cnt;
              } else {
                sum ^= (A[x][y] - '0');
              }
            }
            if (cnt == 0) {
              nums[sum ^ 1] = 0;
            } else {
              const two = Mint(2)^^(cnt - 1);
              nums[0] *= two;
              nums[1] *= two;
            }
          }
          debug {
            writeln("nums = ", nums);
          }
          ans = nums[0] + nums[1];
        } else {
          int cnt;
          foreach (x; 0 .. M) foreach (y; 0 .. N) if (A[x][y] == '?') {
            ++cnt;
          }
          ans = Mint(2)^^cnt;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}