動態規劃——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距離之內的花就會枯萎,也就是魅力值變爲0,問要取花的魅力值最大,問最大魅力值是多少?
解題思路:
標準的動態規劃,從左往右從第一朵花開始取,每一次取花都更新,更新爲倒數第k+1個花的最大魅力值加上當前花朵的最大魅力值,也就是每次存儲的是取到當前花朵的最大魅力值,求到最後即爲最大魅力值。

代碼:

#include<stdio.h>
int max(int x,int y)
{
    if(x>y)return x;
    return y;
}
int a[101010],dp[101010];
int main()
{
    int t,m,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;i<n;i++)scanf("%d",&a[i]);
        int s;
        dp[0]=a[0];
        for(int i=1;i<n;i++)
        {
            if(i-m-1>=0)
                s=dp[i-m-1];
            else
                s=0;
            dp[i]=max(dp[i-1],s+a[i]);
        }
        printf("%d\n",dp[n-1]);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章