HDU - 1786 完全背包大容量求最小价值
Suddenly, Ignatius heard a very very cool voice, and he recognize that it comes from Beelzebub feng5166:“I know that you like bone, and even I know your nick name is wishingbone. Today, I give you a chance to survive: there are N kinds of bones here and the number of each kind bone is enough, their weights are Wi pounds (1<=i<=N), your bag has a volume of M pounds, and I also know that you will spend 3 seconds time when you pick up any one bone. Today, you must fill up your bag as quick as you can, otherwise, the maze is your place of the death!”.
Oh, my god! Can the poor Ignatius survive? Please help him!
Note: You are guarantied that solution always exist for every test case.
InputThe input consists of multiple test cases. The first line of each test case contains two integers N and M (1 < N < 10; 0 < M < 1000000000), which denote the kinds of the bone and the capacity of the bag respectively. The next line give N integers W1…Wn (1<=wi<=100), which indicate the weights of bones
The input is terminated with two 0's. This test case is not to be processed.
OutputFor each test case, print the minimal time Ignatius will spend when he can survive. One line per case.
题目大意:N个东西 重量1-100,数量不限,有一个大小为M的背包,装一个东西要三秒,问填满M大小的背包,所需最少时间。
把每一个的价值看做3,花费为W[i],即要求装满背包价值最小。
令dp[j]为容量j时花的最小的时间。装换为完全背包问题。
得到转移方程:dp[j]=min(dp[j],d[j-w[i]]+3);
又因为M为超大数。因为物体重量最小为1,最大为100,所以,只要某一件物品数量超过100件即可以用最大的代替一部分,又9*100*100=90000,所以大于90000的部分必定可以尽量用最大的代替。
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxm = 900005;
const int maxn = 10+5;
const int inf = 100000000;
int dp[maxm];//dp[j] j重时最少用时。
int w[maxn];
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int N,M,ans;
while(cin>>N>>M)
{
if(N==0&&M==0)
break;
dp[0]=0;
for(int i=1;i<=N;i++)
cin>>w[i];
sort(w+1,w+N+1,cmp);
ans = 0;
if(M>maxm)
{
ans=(M-maxm)/w[1]*3;
M-=(M-maxm)/w[1]*w[1];
}
for(int i=1;i<=M;i++)
dp[i]=inf;
for(int i=1;i<=N;i++)
{
for(int j=w[i];j<=M;j++)
{
dp[j]=min(dp[j],dp[j-w[i]]+3);
}
}
if(dp[M]!=inf)
cout << dp[M]+ans << endl;
}
return 0;
}

浙公网安备 33010602011771号