码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-04-29 22:08:38      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:font   can   子序列   namespace   ace   str   []   scan   nbsp   

题目大意:

给定序列列 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);
}

 

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

标签:font   can   子序列   namespace   ace   str   []   scan   nbsp   

原文地址:http://www.cnblogs.com/rir1715/p/6786275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!