关于 ABC D
  • 板块学术版
  • 楼主TigerTanWQY
  • 当前回复6
  • 已保存回复6
  • 发布时间2024/8/31 22:18
  • 上次更新2024/9/1 11:31:52
查看原帖
关于 ABC D
617314
TigerTanWQY楼主2024/8/31 22:18

本蒟蒻赛时想到了 01 背包写法,然后看到了官方题解的神奇写法。有没有好心人分析一下为什么可以这么优化?

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;
}
2024/8/31 22:18
加载中...