POJ 2533 Longest Ordered Subsequence
题目链接:[kuangbin带你飞]专题十二 基础DP1 N - Longest Ordered Subsequence
题意
求最大递增子序列的长度
思路
两种方法
1. dp[i] = max(dp[j]+1) 1<=j<=i-1(n^2)
2. LIS(nlogn)
代码
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
const int N = 1009;
int dp[N], a[N];
int main()
{
int n;
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
int ans = 0;
for(int i=0; i<n; i++)
{
int mmax = 0;
for(int j=0; j<i; j++)
if(a[j]<a[i] && mmax<dp[j])
mmax = dp[j];
dp[i] = mmax+1;
ans = max(ans, dp[i]);
}
cout<<ans<<endl;
return 0;
}
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
const int N = 1009;
int dp[N], a[N];
int binary_search(int len, int x)
{
int start = 0;
while(start < len)
{
int mid = (start + len)/2;
if(dp[mid] == x)
return mid;
else if(dp[mid] > x)
len = mid;
else
start = mid+1;
}
return len;
}
int main()
{
int n;
cin>>n;
for(int i=0; i<n; i++)
cin>>a[i];
int len = 1;
dp[0] = -1;
for(int i=0; i<n; i++)
{
int pos = binary_search(len, a[i]);
if(pos == len)
len++;
dp[pos] = a[i];
}
cout<<len-1<<endl;
return 0;
}