最长上升子序列最大和模型(离散化 + 树状数组)
题目描述
🔗 https://www.acwing.com/problem/content/3665/
题目分析
首先最初的 动态规划 模型 : 当 N < 1000 时 :
用 dp[i] 来表示 以 nums[i] 结尾的最长上升子序列最大和
则 :
for(int i = 0;i < n;i ++) {
for(int j = i - 1;j >= 0;j --) {
if(nums[i] > nums[j]) dp[i] = max(dp[i],dp[j] + nums[i]);
}
}
时间复杂度 : O(N ^ 2)
空间复杂度 : O(N)
但是题目的 N ~ 1e5 用这种方法会超时
优化
上述的 动态规划 主要需要知道 :
对于 A[i] 往前找到集合 j 使得 A[j] < A[i] 得到 dp[j] 的最大值 然后 + A[i] 即可
离散化 + 树状数组 进行 logN 查询
具体看代码理解即可
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
using LL = long long;
const int N = 100010;
LL A[N];// 用于输入的数组
vector<int> w;// 用于离散化
LL tr[N] = {0};// 树状数组
// tr[i] 前 i 个数字中的 dp 最大值
int nn;// 离散化后的数组长度
int get_p(LL x) {
return lower_bound(w.begin(),w.end(),x) - w.begin() + 1;
}// 离散化后的获得数组位置 因为树状数组中下标从 1 开始
int lowbit(int x) {
return x & -x;
}// 树状数组获得 下标 x 的标识范围
void add(int x,LL v) {
for(int i = x;i <= nn; i += lowbit(i)) {
tr[i] = max(v,tr[i]);
}
return ;
}
LL query(int x) {
LL res = 0;
for(int i = x;i;i -= lowbit(i))
res = max(res,tr[i]);
return res;
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i ++ ) {
scanf("%lld", &A[i]);
w.push_back(A[i]);
}
// 离散化
sort(w.begin(),w.end());
w.erase(unique(w.begin(),w.end()),w.end());
nn = w.size();
LL res = 0;
tr[0] = 0;
for(int i = 0;i < n;i ++) {
int x = get_p(A[i]);
LL v = query(x - 1) + A[i];
// cout<<x<<" "<<v<<endl;
res = max(res,v);
add(x,v);
}
cout<<res<<endl;
return 0;
}