(可能我蒟蒻,所以觉得不简单)

首先我们可以把它抽象成两个问题 :
一个求最长不上升子序列
一个求最长上升子序列
会了最长上升子序列问题一自然会了
取mx为a[]数组的最大值 ,想象有标号依次为1--mx的桶,
定义t[j](1<=j<=mx)为以数j结尾的最长递增序列长度
每当查询a[i]前面有多少数时,遍历前面的1~a[i],取x = max(t[j])+1(1<=j<a[i]),x即为以a[i]结尾的最长子序列长度
同时遍历a[i]+1~maxi的桶,若该桶的值比x小,则
将其赋值为x。
状态转移方程:t[j] = max(f[j],x) (a[i]+1<=j<=maxi)
时间复杂度为O(n^2),这是可以发现f[]可以用树状数组来优化
查询函数
int query2(int x){
int res = 0;
for(int i = x; i; i -= lowbit(i)){
res = max(res, t[i]);
}
return res;
}
因为t[x]是以数x结尾的最大上升子序列,所以,查询a[i] - 1覆盖的区间中的最大上升子序列长度res
然后判断包含x的这个最长上升子序列是否是所有上升子序列中最长的
然后更新树状数组,因为严格上升,把a[i]放入树状数组
for(int i = 0; i < tot; i++){
int now = query2(a[i] - 1) + 1;
res = max(res, now);
update2(a[i], now);
}
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 500;
int tot, a[maxn];
int t[maxn], mx;
int lowbit(int x){return x & (-x);}
int query1(int x){
int res = 0;
for(int i = x; i <= mx; i += lowbit(i)){
res = max(res, t[i]);
}
return res;
}
void update1(int x, int val){
for(int i = x; i; i -= lowbit(i)){
t[i] = max(t[i], val);
}
}
int query2(int x){
int res = 0;
for(int i = x; i; i -= lowbit(i)){
res = max(res, t[i]);
}
return res;
}
void update2(int x, int val){
for(int i = x; i <= mx; i += lowbit(i)){
t[i] = max(t[i], val);
}
}
void solve1(){
int res = 0;
for(int i = 0; i < tot; i++){
int now = query1(a[i]) + 1;
res = max(res, now);
update1(a[i], now);
}
cout << res << "\n";
}
void solve2(){
memset(t, 0, sizeof(t));
int res = 0;
for(int i = 0; i < tot; i++){
int now = query2(a[i] - 1) + 1;
res = max(res, now);
update2(a[i], now);
}
cout << res << '\n';
}
int main(){
while(scanf("%d", &a[tot]) != EOF){
mx = max(mx, a[tot++]);
}
solve1();
solve2();
return 0;
}
275




被折叠的 条评论
为什么被折叠?



