HDU-2182 Forg 动态规划DP 题解

● 本题解会有详细的分析,适合初学者阅读
## 原题

Problem Description

A little frog named Fog is on his way home. The path’s length is N (1 <= N <= 100), and there are many insects along the way. Suppose the
original coordinate of Fog is 0. Fog can stay still or jump forward T units, A <= T <= B. Fog will eat up all the insects wherever he stays, but he will
get tired after K jumps and can not jump any more. The number of insects (always less than 10000) in each position of the path is given.
How many insects can Fog eat at most?
Note that Fog can only jump within the range [0, N), and whenever he jumps, his coordinate increases.

Input

The input consists of several test cases.
The first line contains an integer T indicating the number of test cases.
For each test case:
The first line contains four integers N, A, B(1 <= A <= B <= N), K (K >= 1).
The next line contains N integers, describing the number of insects in each position of the path.

Output

each test case:
Output one line containing an integer - the maximal number of insects that Fog can eat.

Sample Input

1
4 1 2 2 
1 2 3 4 

Sample Output

8

题目翻译

Problem Description

一只名叫Frog的大蛤蟆正在回家的路上。这条路的长度是N(1<=N<=100),沿途有许多昆虫。假设Frog的原始坐标为0。Frog可以保持静止或向前跳跃T单位,A<=T<=B。无论他呆在哪里,Frog都会吃掉所有的昆虫,但他会的K跳后累了,不能再跳了。给出了路径中每个位置的昆虫数量(始终小于10000)。Frog最多能吃多少昆虫?

请注意,Forg只能在[0,N]范围内跳跃,每当他跳跃时,他的坐标就会增加.

Input

输入由几个测试用例组成。
第一行包含一个整数T,表示测试用例的数量。
对于每个测试用例:
第一行包含四个整数N,A,B(1<=A<=B<=N),K(K>=1)。
下一行包含N个整数,描述路径中每个位置的虫子数量。

Output

对于每组测试样例,输出一行,包含一个整数,表示Fog能吃到虫子数量的最大值

题目分析

这真的是DP大水题了,打个二维滚动数组就出来了。

青蛙在长度为N的道路上跳K次,每次跳的单位为T。在这里插一句,如果这个T为1,那么这题就是一个0-1背包了…

首先,设 d p [ i ] [ j ] dp[i][j] dp[i][j]表示Fog跳 j j j次到达 i i i坐标处可以吃到的最多的虫子数,那么状态转移方程:

d p [ i ] [ j ] = m a x ( d p [ i ] [ j ] , d p [ t ] [ j − 1 ] + a r r [ i ] ) dp[i][j]=max(dp[i][j],dp[t][j-1]+arr[i]) dp[i][j]=max(dp[i][j],dp[t][j1]+arr[i])

记得在最后答案里加上初始位置的虫子数,我们从初始位置开始滚动时是无法将初始位置的昆虫数目加入dp数组的

AC Code

#include <bits/stdc++.h>
using namespace std;
const int N = 100;
int arr[N], dp[N][N];

int main(){
    
    
    ios::sync_with_stdio(0);
    int t = 0; cin >> t;
    while(t--){
    
    
        int n, a, b, k; cin >> n >> a >> b >> k;
        for(int i = 1; i <= n; i++) cin >> arr[i];
        for(int i = 1; i <= n; i++){
    
    
            for(int j = 1; j <= k; j++){
    
    
                for(int k = i + a; k <= i + b && k <= n; k++){
    
    			//枚举跳到的位置
                    dp[k][j] = max(dp[k][j], dp[i][j - 1] + arr[k]);
                }
            }
        }
        cout << dp[n][k] + arr[1] << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yanweiqi1754989931/article/details/113092744