[分治 单调栈] BZOJ 4237 稻草人

x排序 考虑分治

左下角在左半边 右上角在右半边 

两边各维护一个单调栈 然后左边查询在右边二分

细节自行在代码中领会


#include
#include
#include
#include
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
typedef long long ll;

inline char nc()
{
	static char buf[100000],*p1=buf,*p2=buf;
	if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
	return *p1++;
}

inline void read(int &x)
{
	char c=nc(),b=1;
	for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
	for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=200005;

struct abcd{
	int x,y;
	abcd(int x=0,int y=0):x(x),y(y) { }
}P[N],s[N],ql[N],qr[N];
int tl,tr;

inline bool cmpx(abcd A,abcd B){
	return A.xB.y;
}

int n; ll ans;
int tmp[N];

void Solve(int l,int r){
	if (l==r) return;
	int mid=(l+r)>>1,x,y;
	for (int i=l;i<=r;i++) s[i]=P[i];
	sort(s+l,s+mid+1,cmpy);
	sort(s+mid+1,s+r+1,cmpy);
	tr=tl=0;
	qr[0].y=ql[0].y=1<<30; int pnt=mid+1;
	for (int i=l;i<=mid;i++)
	{
		while (pnt<=r && s[pnt].y>s[i].y)
		{
			while (tr && s[pnt].xql[tl].x) tl--;
		ql[++tl]=s[i];
		x=lower_bound(qr+1,qr+tr+1,ql[tl-1],cmpy)-qr;
		y=lower_bound(qr+1,qr+tr+1,ql[tl],cmpy)-qr-1;
		if (x<=y) ans+=y-x+1;
	}
	Solve(l,mid); Solve(mid+1,r);
}

int main()
{
	int ix,iy;
	freopen("t.in","r",stdin);
	freopen("t.out","w",stdout);
	read(n);
	for (int i=1;i<=n;i++)
		read(ix),read(iy),P[i]=abcd(ix,iy);
	sort(P+1,P+n+1,cmpx);
	Solve(1,n);
	printf("%lld\n",ans);
	return 0;
}


你可能感兴趣的:(分治,单调栈)