本蒟蒻赛时想到了 01 背包写法,然后看到了官方题解的神奇写法。有没有好心人分析一下为什么可以这么优化?
#include <iostream>
#include <algorithm>
using namespace std;
using LL = long long;
LL f[200'003];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for(int i = 1, x; i <= n; ++i) {
cin >> x;
for(int k = n; k; --k)
if(k & 1)
f[k] = max(f[k], f[k - 1] + x);
else
f[k] = max(f[k], f[k - 1] + x * 2);
}
cout << *max_element(f + 1, f + n + 1) << endl;
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
long long f0 = 0, f1 = -0x3f3f3f3f3f3f3f3f;
for(int i = 1, x; i <= n; ++i) {
cin >> x;
auto t0 = f0;
f0 = max(f0, f1 + x * 2);
f1 = max(f1, t0 + x);
}
cout << max(f0, f1) << endl;
return 0;
}