练习赛补题-------B - Battle Ships

Battle Ships is a new game which is similar to Star Craft. In this game, the enemy builds a defense tower, which has L longevity. The player has a military factory, which can produce N kinds of battle ships. The factory takes ti seconds to produce the i-th battle ship and this battle ship can make the tower loss li longevity every second when it has been produced. If the longevity of the tower lower than or equal to 0, the player wins. Notice that at each time, the factory can choose only one kind of battle ships to produce or do nothing. And producing more than one battle ships of the same kind is acceptable.

Your job is to find out the minimum time the player should spend to win the game.

Input
There are multiple test cases.
The first line of each case contains two integers N(1 ≤ N ≤ 30) and L(1 ≤ L ≤ 330), N is the number of the kinds of Battle Ships, L is the longevity of the Defense Tower. Then the following N lines, each line contains two integers t i(1 ≤ t i ≤ 20) and li(1 ≤ li ≤ 330) indicating the produce time and the lethality of the i-th kind Battle Ships.

Output
Output one line for each test case. An integer indicating the minimum time the player should spend to win the game.

Sample Input
1 1
1 1
2 10
1 1
2 5
3 100
1 10
3 20
10 100

Sample Output
2
4
5

知道可能是完全背包,因为每个武器可重复取,现在可以把时间当成V,造成的伤害当成W,主要看了网上的题解,比较疑惑的是状态转移该怎么办?
dp[i][t]代表前i个武器在前t秒所造成的最大伤害
dp[i][t] = max(dp[i - 1][t] ,dp[i][t - t[i]] + (t - t[i]) * val[i])
为什么呢?如果正向取武器,那么每次取完武器,之后有生产时间不会有作用,对生产时间之后的dp值都会有影响,所以这里需要倒着找武器,找第一个,把它当成选武器的最后一个,每次把当前选的武器作为第一个,那么伤害也就特别好算了,就是(t - t[i])* val[i];
可以化简一下dp状态转移方程,变成一维,dp[j] = max(dp[j],dp[j - t[i]] + (j - t[i]) * val[i]);

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
#define mp make_pair
#define pb push_back
#define fi first
#define se second

int dp[350];
int n,L;
int a[35][2];

int main()
{
    while(~scanf("%d %d",&n,&L)){
        for(int i = 1;i <= n;++i){
            scanf("%d %d",&a[i][0],&a[i][1]);
        }
        memset(dp,0,sizeof(dp));
        for(int i = 1;i <= n;++i){
            for(int j = a[i][0];j <= 345;++j){
                dp[j] = max(dp[j],dp[j - a[i][0]] + (j - a[i][0]) * a[i][1]);
                if(dp[j] >= L){
                    break;
                }
            }
        }
        int ans = 0;
        for(int i = 0;i <= 345;++i){
            if(dp[i] >= L){
                printf("%d\n",i);
                break;
            }
        }
    }
    return 0;
}


发布了269 篇原创文章 · 获赞 33 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36386435/article/details/88863303