[USACO13OPEN]照片Photo [动态规划 单调队列]

[USACO13OPEN]照片Photo
这题好烧脑...

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rg register
#define Max(x,y) ((x)>(y)?(x):(y))
#define Min(x,y) ((x)>(y)?(y):(x))
const int N=2e5+5,M=1e5+5,inf=0x3f3f3f3f,P=19650827;
int n,m,mxl[N],mnl[N],q[N],f[N];
template <class t>void rd(t &x){
    x=0;int w=0;char ch=0;
    while(!isdigit(ch)) w|=ch=='-',ch=getchar();
    while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    x=w?-x:x;
}

int main(){
	freopen("in2.txt","r",stdin);
	//freopen("xor.out","w",stdout);
	rd(n),rd(m);
	for(int i=1;i<=n+1;++i) mnl[i]=i-1;
	for(int i=1,l,r;i<=m;++i)
		rd(l),rd(r),mnl[r]=Min(mnl[r],l-1),mxl[r+1]=Max(mxl[r+1],l);
	for(int i=n;i;--i) mnl[i]=Min(mnl[i],mnl[i+1]);
	for(int i=2;i<=n+1;++i) mxl[i]=Max(mxl[i],mxl[i-1]);
	int h=1,t=1,j=1;
	for(int i=1;i<=n+1;++i){
		while(j<=mnl[i]&&j<=n){
			if(f[j]==-1){++j;continue;}
			while(f[j]>f[q[t]]&&t>=h) --t;
			q[++t]=j++;
		}
		while(q[h]<mxl[i]&&h<=t) ++h;
		if(h<=t) f[i]=f[q[h]]+(i!=n+1?1:0);
		else f[i]=-1;
	}
	printf("%d",f[n+1]);
	return 0;
}
posted @ 2019-08-19 22:14  委屈的咸鱼鱼鱼鱼  阅读(137)  评论(0编辑  收藏  举报