算法--最长上升子序列
1、最长上升子序列
#include<iostream>
#include<algorithm>
using namespace std;
int a[100];//原始数组
int dp[100];//以x结尾的数组
int main() {
int n;//数组长度
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];//数组中的每个元素
}
for (int i = 1; i <= n; i++) {
dp[i] = 1;
for (int j = 1; j < i; j++) {
if (a[j] < a[i]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
int max_step = 0;
for (int i = 1; i <= n; i++) {
if (dp[i] > max_step) {
max_step = dp[i];
}
}
cout << max_step << endl;
}
2、例题
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6;
int g[N],a[N];
int main()
{
int n;
cin>>n;
int len=0;
for(int i = 1; i <= n; i ++) {
cin>>a[i];
}
for(int i = 1; i <= n; i ++) {
if(a[i] > g[len]){
g[++len] = a[i];
}else {
int pos = upper_bound(g+1,g+1+len,a[i]) - g;
g[pos] = a[i];
}
}
cout<<len;
return 0;
}