之前学过最简单求解方法为dp法,
规则为:
若a[q]>a[w],dp[q]=max(dp[q],dp[w]+1)
时间复杂度为O(n的平方):
for(int q=0;q<n;q++){
dp[q]=1;
for(int w=0;w<q;w++){
if(a[q]>a[w]){dp[q]=max(dp[q],dp[w]+1);}
}
max=max(max,dp[q]);
}
有一种时间复杂度为O(nlogn)的算法:
二分查找法:
#include <iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100005;
int a[maxn];
int main()
{ memset(a,0,sizeof(a));
int n=0,x;
while(scanf("%d",&x)!=EOF){
a[n++]=x;
}
vector<int>dp;
dp.push_back(a[0]);int len=1,len1=1;
for(int q=1;q<n;q++){
int f=lower_bound(dp.begin(),dp.end(),a[q])-dp.begin();
if(f<=0){dp[0]=a[q];}
else if(f==len){len++;dp.push_back(a[q]);}
else{dp[f]=a[q];}
}
cout<<len;
return 0;
}
这里用函数lower_bound()与upper_bound()的区别在于:
lower_bound(a+i,a+j,x)-a返回的是大于等于x的第一个数的坐标upper_bound(a+i,a+j,x)-a返回的是第一个大于x的数的坐标
ACM每周总结(upper_bound和lower_bound)
简单来说:以序列1 2 2 3为例:
用upper_bound()来寻找最长不下降(包含=的情况)序列;
用lower_bound()来寻找最长上升(不包含=的情况)序列;
以序列1 2 2 3为例:
1)用upper_bound()输出4;
2)用lower_bound()输出3;
P1020 [NOIP1999 普及组] 导弹拦截
解题须知:
Dilworth定理说的是:对于一个偏序集,其最少链划分数等于其最长反链的长度。
Dilworth定理的对偶定理说的是:对于一个偏序集,其最少反链划分数等于其最长链的长度。
简单来说:最少的下降序列个数就等于整个序列最长上升子序列的长度
以该题为例:
dp解法:只能通过50%的样例,因为它的时间复杂度为O(n的平方)
#include<iostream>
#include<algorithm>
#include<vector>
#include<fstream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100005;
int main()
{ int a[maxn],x,n=0,dp[maxn],dp1[maxn],max1=-1,max2=-1;;
memset(a,1,sizeof(a));
while(scanf("%d",&x)!=EOF)
{a[n++]=x;}
for(int q=0;q<n;q++){
dp[q]=1;dp1[q]=1;
for(int w=0;w<q;w++){
if(a[q]<=a[w]){dp[q]=max(dp[q],dp[w]+1);}
else{dp1[q]=max(dp1[q],dp1[w]+1);}
}
max1=max(max1,dp[q]);
max2=max(max2,dp1[q]);
}
printf("%d\n",max1);
printf("%d",max2);
return 0;
}
二分查找法:时间复杂度为O(nlogn)
#include <iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100005;
int a[maxn];
int main()
{ memset(a,0,sizeof(a));
int n=0,x;
while(scanf("%d",&x)!=EOF){
a[n++]=x;
}
vector<int>dp;
vector<int>dp1;
dp.push_back(a[0]);int len=1,len1=1;
for(int q=1;q<n;q++){
int f=lower_bound(dp.begin(),dp.end(),a[q])-dp.begin();
if(f<=0){dp[0]=a[q];}
else if(f==len){len++;dp.push_back(a[q]);}
else{dp[f]=a[q];}
}
dp1.push_back(a[n-1]);
for(int q=n-2;q>=0;q--){
int f=upper_bound(dp1.begin(),dp1.end(),a[q])-dp1.begin();
if(f<=0){dp1[0]=a[q];}
else if(f==len1){len1++;dp1.push_back(a[q]);}
else{dp1[f]=a[q];}
}
cout<<len1<<endl;
cout<<len;
return 0;
}