数组数组-最长上升子序列

题目描述:

给定一个整型数组, 求这个数组的最长严格递增子序列的长度。 譬如序列1 2 2 4 3 的最长严格递增子序列为1,2,4或1,2,3.他们的长度为3。

输入:

输入可能包含多个测试案例。
对于每个测试案例,输入的第一行为一个整数n(1<=n<=100000):代表将要输入的序列长度
输入的第二行包括n个整数,代表这个数组中的数字。整数均在int范围内。

输出:

对于每个测试案例,输出其最长严格递增子序列长度。

样例输入:
4
4 2 1 3
5
1 1 1 1 1
样例输出:
2
1


老题目了,网上有经典的nlogn的算法,不过那个不好写。在二分的时候很容易写错。我用的是数状数组,不过步骤比较多。

我是先离散化,对输入的数据进行重新编号,

比如10 20 30

就变成了0 1 2了。

因为最长上升只子序列长度只和相对大小有关,所以这样做对结果是不会有影响的。

接下来就是从前往后DP了。

统计以当前元素结尾的最大上升子序列长度。

记为dp,本来在O(n*n)算法中是要把所有的0到i-1的DP值扫一遍,其本质上就是求解在第i个位置之前,以元素比a小的,最大值DP是多少。在这里,这个我们就可以用树状数组来做。查询一下比a小的这一段中最大值是多少,就可以了。然后把当前DP值插入到数组中a的位置。

我用了一些STL,所以写起来也不是很长。


#include <cstdio>
#include <string>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <map>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
typedef long long lld;
const int MAX=110000;
 
const int INF=1000000000;
int a[MAX];
int dcre[MAX];
int tree[MAX];
int query(int t)
{
       int ret=0;
       while(t)
       {
              if(tree[t]>ret)ret=tree[t];
              t-=(-t)&t;
       }
       return ret;
}
void ins(int t,int v,int m)
{
       while(t<=m)
       {
              if(v>tree[t])tree[t]=v;
              t+=(-t)&t;
       }
}
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{  
       int T;
       int n,m;
       int last=0;
       int i,j,k;
      
       while(scanf("%d",&n)!=EOF)
       {
              for(i=0;i<n;i++)
              {
                     scanf("%d",&a[i]);
                     dcre[i]=a[i];
              }
              sort(dcre,dcre+n);
              m=unique(dcre,dcre+n)-dcre;
              memset(tree,0,sizeof(int)*(m+2));
              int ans=1,tmp;
              for(i=0;i<n;i++)
              {
                     a[i]=lower_bound(dcre,dcre+m,a[i])-dcre+1;
                     tmp=query(a[i]-1)+1;
                     if(tmp>ans)ans=tmp;
                     ins(a[i],tmp,m);
              }
              printf("%d\n",ans);
       }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值