-
题目描述:
-
给定一个整型数组, 求这个数组的最长严格递增子序列的长度。 譬如序列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;
}