这个有三个板子,分别是 d p dp dp做法,二分+贪心做法和树状数组优化 d p dp dp,树状数组这个我后面学了之后再补上哈
题目描述
给定 n n n个元素,要求找到最长上升子序列的长度
d p dp dp做法
#include<bits/stdc++.h>
using namespace std;
int a[1005], p[1005];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;cin >> n;
for (int i = 1;i <= n;i++) {
cin >> a[i];
p[i] = 1;
}
for (int i = 1;i <= n;i++)
for (int j = 1;j <= i;j++)
if (a[j] < a[i])p[i] = max(p[j] + 1, p[i]);
int mi = 0;
for (int i = 1;i <= n;i++)mi = max(mi, p[i]);
cout << mi;
return 0;
}
二分+贪心做法
#include<bits/stdc++.h>
using namespace std;
int a[1005];
int dp[1005];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;cin >> n;
int len = 1;
for (int i = 1;i <= n;i++) {
cin >> a[i];
dp[i] = INT_MIN;
}
dp[1] = a[1];
for (int i = 2;i <= n;i++) {
if (a[i] > dp[len])dp[++len] = a[i];
else {
int pl = lower_bound(dp + 1, dp + 1 + len, a[i]) - dp;
dp[pl] = a[i];
}
}
cout << len;
return 0;
}