您的位置:首页 > 其它

最大上升子序列

2013-09-07 12:05 302 查看
O(n^2)的算法:

#include "iostream"
#include "cstring"
#include "algorithm"
#include "cmath"
#include "cstdio"
#include "sstream"
#include "queue"
#include "vector"
#include "string"
#include "stack"
#include "cstdlib"
#include "deque"
#include "fstream"
#include "map"
using namespace std;
typedef long long LL;
const int INF = 0x1fffffff;
const int MAXN = 1000;

int a[1010];
int dp[1010];
int n;

int main()
{
while(cin >> n && n)
{
for(int i = 0 ; i < n ; i++)
scanf("%d",&a[i]);

fill(dp,dp+n,1);

int maxc = -1;
for(int i = 0 ; i < n ; i++)
{
for(int j = i ; j >= 0 ; j--)
if(a[j] < a[i] && dp[j]+1 > dp[i])
dp[i] = dp[j]+1;
maxc = max(maxc,dp[i]);
}

cout << maxc << endl;
}

return 0;
}

O(nlog(n))的算法(C++):

#include "iostream"
#include "cstring"
#include "algorithm"
#include "cmath"
#include "cstdio"
#include "sstream"
#include "queue"
#include "vector"
#include "string"
#include "stack"
#include "cstdlib"
#include "deque"
#include "fstream"
#include "map"
using namespace std;
typedef long long LL;
const int INF = 0xfffffff;

int a[100000+10];
int dp[100000+10];
int n;

int main()
{
cin >> n;

int lis=0;

for(int i = 0 ; i < n ; i++)
{
cin >> a[i];
int p = lower_bound(dp,dp+lis,a[i])-dp; //lower_bound获取一个有序数列中能插入a[i]的迭代器,最大时则插入末尾
dp[p]=a[i]; //覆盖原数,使子序列潜力更大,如1,3,6;插入2时,会把3取代掉,变成1,2,6
if(p == lis) //p最大了,子序列size增大
lis++;
}

cout << lis << endl; //lis是最大上升子序列的长度,dp内存着其中一个最大上升子序列

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  最大上升子序列