AcWing 4546. 最大和加强加强版
看到数据范围
我们设
左边的东西表示,第
可以显然发现会超时,我们可以在计算左边的东西时,直接用
// #define FILE_INPUT
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
// #define int long long
#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
void Init();
void Solve();
signed main() {
cin.sync_with_stdio(0);
cin.tie(0), cout.tie(0);
#ifdef FILE_INPUT
freopen("input.in", "r", stdin);
#endif
int T = 1;
// cin >> T;
while (T--) {
Init();
Solve();
}
return 0;
}
using LL = long long;
using ULL = unsigned long long;
const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;
const int N = 1e6 + 10, M = 1010;
LL m, n, f[2][M], a[N], g[M];
void Init() {
}
#define max(x, y) (x > y ? x : y) // 少用,递归的时候时间复杂度会爆炸
#define min(x, y) (x < y ? x : y) // 少用,递归的时候时间复杂度会爆炸
void Solve() {
while (cin >> m >> n) {
rep(i, 1, n) cin >> a[i];
memset(f, -0x3f, sizeof(f));
memset(g, -0x3f, sizeof(g));
f[0][0] = f[1][0] = 0;
g[0] = 0;
rep(i, 1, n) {
int t = min(i, m);
per(j, t, 1) {
f[i & 1][j] = max(g[j - 1], f[i - 1 & 1][j]) + a[i];
g[j] = max(g[j], f[i & 1][j]);
}
}
cout << g[m] << "\n";
}
}
然后呢我们还可以再进行优化(虽然没有必要了),用类似于
// #define FILE_INPUT
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
// #define int long long
#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
void Init();
void Solve();
signed main() {
cin.sync_with_stdio(0);
cin.tie(0), cout.tie(0);
#ifdef FILE_INPUT
freopen("input.in", "r", stdin);
#endif
int T = 1;
// cin >> T;
while (T--) {
Init();
Solve();
}
return 0;
}
using LL = long long;
using ULL = unsigned long long;
const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;
const int N = 1e6 + 10, M = 1010;
LL m, n, f[M], a[N], g[M];
void Init() {
}
#define max(x, y) (x > y ? x : y) // 少用,递归的时候时间复杂度会爆炸
#define min(x, y) (x < y ? x : y) // 少用,递归的时候时间复杂度会爆炸
void Solve() {
while (cin >> m >> n) {
rep(i, 1, n) cin >> a[i];
memset(f, -0x3f, sizeof(f));
memset(g, -0x3f, sizeof(g));
f[0] = 0;
g[0] = 0;
rep(i, 1, n) {
int t = min(i, m);
per(j, t, 1) {
f[j] = max(g[j - 1], f[j]) + a[i];
g[j] = max(g[j], f[j]);
}
}
cout << g[m] << "\n";
}
}
注意:
标签:
动态规划
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!