Files
python/TangDou/AcWing/Statemachine/1049_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

31 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
int f[N];//DP数组,抢前i个店铺可以获取到的最大价值是多少
int a[N];//抢劫第i个店铺可以获取到的利益w[i]
//线性DP解法
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
memset(f, 0, sizeof f);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
//base case
f[0] = 0; //还没开始抢,那么利益必须是0
f[1] = a[1]; //抢了第一个,只能是利益为w[1]
//从第二个开始,有递推关系存在,以抢与不抢第i个为理由进行分类
for (int i = 2; i <= n; i++)
//f[i-1]表示不抢第i个,那么利益就是f[i-1]
//如果抢了第i个,那么获取到w[i]的利益,同时,前面的只能依赖于f[i-2]
//max表示决策,到底抢两个中的哪个合适呢?
f[i] = max(f[i - 1], f[i - 2] + a[i]);
//输出结果
printf("%d\n", f[n]);
}
return 0;
}