The Poor Giant (区间dp)

On a table, there are n apples, the i-th apple has the weight k + i (1 ≤ i ≤ n). Exactly one of the
apples is sweet, lighter apples are all bitter, while heavier apples are all sour. The giant wants to know
which one is sweet, the only thing he can do is to eat apples. He hates bitter apples and sour apples,
what should he do?
For examples, n = 4, k = 0, the apples are of weight 1, 2, 3, 4. The giant can first eat apple #2.
• if #2 is sweet, the answer is #2
• if #2 is sour, the answer is #1
• if #2 is bitter, the answer might be #3 or #4, then he eats #3, he’ll know the answer regardless
of the taste of #3
The poor giant should be prepared to eat some bad apples in order to know which one is sweet.
Let’s compute the total weight of apples he must eat in all cases.
• #1 is sweet: 2
• #2 is sweet: 2
• #3 is sweet: 2 + 3 = 5
• #4 is sweet: 2 + 3 = 5
The total weights = 2 + 2 + 5 + 5 = 14.
This is not optimal. If he eats apple #1, then he eats total weight of 1, 3, 3, 3 when apple #1, #2,
#3 and #4 are sweet respectively. This yields a solution of 1 + 3 + 3 + 3 = 13, beating 14.
What is the minimal total weight of apples in all cases?
Input
The first line of input contains a single integer t (1 ≤ t ≤ 100), the number of test cases. The following
t lines each contains a positive integer n and a non-negative k (1 ≤ n + k ≤ 500).
Output
For each test case, output the minimal total weight in all cases as shown in the sample output.
Sample Input
5
2 0
3 0
4 0
5 0
10 20
Sample Output
Case 1: 2
Case 2: 6
Case 3: 13
Case 4: 22
Case 5: 605

题目大概:

给出n个苹果,每个苹果的重量为它的序号i+k。里面有一个苹果是甜的,比它轻的是苦的,比它重的是酸的。但不知道哪一个是甜的。现在需要吃这些苹果,来确定哪一个是甜的,开始吃之后就必须都吃完。在所有的情况中(即1 2 3或4....是甜的),需要吃的苹果重量总和最小为多少。

思路:

n个苹果中,如果随便吃了一个。如果这个苹果是甜的,找出甜的,需要吃这个苹果,如果是苦的,那么就向右边找,如果是酸的,就向左边找甜的,都需要吃点这个苹果才知道,同样,到了下一个区间同样如此,但随便选的这个苹果,不一定是最好的,需要枚举,所以,很容易想到用区间dp。

dp【i】【j】表示,i到j的所有情况的最小重量,那么

dp【i】【j】=min(dp【i+1】【k】+dp【k+1】【j】+(j-i)*(权值),dp【i】【j】)。

这个转移方程,很容易得出,只需要试着枚举几个试试就可以了。

代码:

#include <bits/stdc++.h>

using namespace std;
const int maxn=550;
const int INF=0x3f3f3f3f;
int dp[maxn][maxn];
//
int main()
{
    int t;
    scanf("%d",&t);
    for(int p=1;p<=t;p++)
    {
        int n,k1;
        scanf("%d%d",&n,&k1);
        memset(dp,0,sizeof(dp));

        for(int v=2;v<=n;v++)
        {
            for(int l=1;l<=n-v+1;l++)
            {
                int r=l+v-1;
                dp[l][r]=INF;
                for(int k=l;k<=r;k++)
                {
                    dp[l][r]=min(dp[l][r],dp[l][k-1]+dp[k+1][r]+v*(k+k1));
                }
            }
        }
        printf("Case %d: %d\n",p,dp[1][n]);
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值