Little Red Riding Hood(动态规划)

题目描述

    Once upon a time, there was a little girl. Her name was Little Red Riding Hood. One day, her grandma was ill. Little Red Riding Hood went to visit her. On the way, she met a big wolf. “That's a good idea.”,the big wolf thought. And he said to the Little Red Riding Hood, “Little Red Riding Hood, the flowers are so beautiful. Why not pick some to your grandma?” “Why didn't I think of that? Thank you.” Little Red Riding Hood said.

    Then Little Red Riding Hood went to the grove to pick flowers. There were n flowers, each flower had a beauty degree a[i]. These flowers arrayed one by one in a row. The magic was that after Little Red Riding Hood pick a flower, the flowers which were exactly or less than d distances to it are quickly wither and fall, in other words, the beauty degrees of those flowers changed to zero. Little Red Riding Hood was very smart, and soon she took the most beautiful flowers to her grandma’s house, although she didn’t know the big wolf was waiting for her. Do you know the sum of beauty degrees of those flowers which Little Red Riding Hood pick? 

输入

    The first line input a positive integer T (1≤T≤100), indicates the number of test cases. Next, each test case occupies two lines. The first line of them input two positive integer n and

k (2 <= n <= 10^5 ) ,1 <=  k <= n ), the second line of them input n positive integers a (1<=a <=10^5)

输出

    Each group of outputs occupies one line and there are one number indicates the sum of the largest beauty degrees of flowers Little Red Riding Hood can pick. 

样例输入

1 
3 1 
2 1 3

样例输出

5

当k>=n时,在n个里面选出最大的一个。

当k<n时,dp[i]=max(dp[i-1],dp[i-k-1]+a[i]);

#include<stdio.h>
#include<string.h>
#define N 100020
int a[N];
int dp[N];
int max(int a,int b)
{
	return a>b?a:b;
}
int main()
{
	int t,n,i,k;
	scanf("%d",&t);
	while(t--)
	{
		memset(dp,0,sizeof(dp));
		scanf("%d%d",&n,&k);
		for(i=1;i<=n;i++)
			scanf("%d",&a[i]);
		for(i=1;i<=k;i++)
			dp[i]=max(dp[i-1],a[i]);
		for(i=k+1;i<=n;i++)
			dp[i]=max(dp[i-1],dp[i-k-1]+a[i]);
		printf("%d
",dp[n]);
	}
	return 0;
} 
原文地址:https://www.cnblogs.com/zyq1758043090/p/10056593.html