最长上升子序列 这道题采用DP做法的时间复杂度是O(n2)会超时所以采用O(nlogn)的算法
O(n2)算法
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>
#include <string.h>
#include <cmath>
#include <sstream>
#include <set>
#include <map>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 100010;
int arr[maxn], dp[maxn];
int n, res;
int main()
{
while (cin >> n&&n != 0)
{
res = -1;
for (int i = 0; i < n; i++)
cin >> arr[i];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < n; i++)
{
dp[i] = 1;
for (int j = 0; j < i; j++)
{
if (arr[i] > arr[j])
dp[i] = max(dp[i], dp[j] + 1);
}
res = max(res, dp[i]);
}
cout << res << endl;
}
}
O(nlogn)算法 一种二分的思想
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <string>
#include <string.h>
#include <cmath>
#include <sstream>
#include <set>
#include <map>
#include <functional>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 100010;
int arr[maxn], d[maxn];
int n, res, pos;
int main()
{
while (cin >> n&&n != 0)
{
res = -1, pos = 0;
for (int i = 0; i < n; i++)
cin >> arr[i];
d[0] = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] > d[pos])
{
d[++pos] = arr[i];
}
else
*lower_bound(d, d + pos, arr[i]) = arr[i];
}
cout << pos<< endl;
}
}