【单调栈】最长不下降子序列变式

题目大意:

给定序列列 a[],最少修改多少个位置可以令其变成最长上升子序列

分析:

这道题看似非常奇怪,然而细想一下很容易发现我们可以通过令 a’[i] = a[i] - i

对 a’[i] 求最长上升子序列,可以得到最多有多少个位置保持不不变

然后用n去减它,就是要修改的个数

代码如下:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

int n,top=1,h[1000101],a[1000101];

void add(int x)
{
    int l=1,r=top,m;
    while(l<=r)
    {
        m=(l+r)>>1;
        if(x>=h[m]) l=m+1;
        else r=m-1;
    }
    h[l]=x;
}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
    {
        scanf("%d",&a[i]);
        a[i]-=i;
    }
    for(int i=1;i<=n;++i)
    {
        if(a[i]>=h[top]&&i!=1) h[++top]=a[i];
        else add(a[i]);
    }
    printf("%d",n-top);
}

 

posted @ 2017-04-29 21:05  减维  阅读(204)  评论(0编辑  收藏  举报