BZOJ3126 单调队列DP

记录一下每个位置包含它的区间最左端在哪里还有和他前面的不包含他的区间最右端 然后单调队列跑DP

#include
#define N 200003
using namespace std;
int n,m,L[N],R[N];
int head,tail,q[N],f[N];
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n+1;i++) R[i]=i-1;
    for (int i=1;i<=m;i++) {
        int x,y; scanf("%d%d",&x,&y);
        R[y]=min(R[y],x-1);
        L[y+1]=max(L[y+1],x);
    }
    for (int i=n;i>=1;i--) R[i]=min(R[i+1],R[i]);
    for (int i=2;i<=n+1;i++) L[i]=max(L[i-1],L[i]);
    int j=1; head=tail=1; q[1]=0;
    for (int i=1;i<=n+1;i++) {
        while (j<=R[i]&&j<=n) {
            if (f[j]==-1) {
                j++;
                continue;
            }
            while (f[j]>f[q[tail]]&&head<=tail) tail--;
            q[++tail]=j;
            j++;
        }
        while (q[head]if (head<=tail) f[i]=f[q[head]]+(i!=n+1?1:0);
        else f[i]=-1;
    }
    printf("%d\n",f[n+1]);
}

你可能感兴趣的:(DP)