HZAU 1199: Little Red Riding Hood 01背包

题目链接:1199: Little Red Riding Hood

思路:dp(i)表示前i朵花能取得的最大价值,每一朵花有两种选择,摘与不摘,摘了第i朵花后第i-k到i+k的花全部枯萎,那么摘的话dp(i) = dp(i-k-1) + a[i],不摘就是dp(i) = dp(i-1),因此转移方程就是dp(i) = max(dp(i-k-1) + a[i], dp(i-1))。

AC代码

#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 1e5 + 5;
int a[maxn], dp[maxn];
int main() {
	int T, n, k;
	scanf("%d", &T);
	while(T--) {
		scanf("%d%d", &n, &k);
		for(int i = 1; i <= n; ++i) {
			scanf("%d", &a[i]);
		}
		dp[0] = 0;
		for(int i = 1; i <= n; ++i) {
			dp[i] = dp[i-1];
			int w;
			if(i - k - 1 <= 0) w = 0;
			else w = dp[i-k-1];
			dp[i] = max(dp[i], w + a[i]);
		}
		printf("%d\n", dp[n]);
	}
	return 0;
} 

如有不当之处欢迎指出!


上一篇:天朝git的使用


下一篇:python 常见异常