背包相关问题
HDU 2602 Bone Collector
Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?
Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
Output
One integer per line representing the maximum of the total value (this number will be less than 231).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
代码:
#include<stdio.h>
#include<string.h>
#define max(a,b) (a>b?a:b) //自定义函数
int f[2002]; //f[]表示装前n个骨骼的最大价值 (i,j)的指标函数
int main()
{
int t,n,V,i,j;//n表示骨骼的数量 V表示袋子的体积 //i表示骨骼的序号,j表示骨骼的体积
int value[1000],volume[1000]; //value表示每个骨骼的价值,volume表示每个骨骼的体积
scanf("%d",&t); //第一行输入
while(t--){
scanf("%d%d",&n,&V); //第二行输入
for(i=1;i<=n;i++)
scanf("%d",&value[i]); //第三行输入
for(i=1;i<=n;i++)
scanf("%d",&volume[i]);//第四行输入
memset(f,0,sizeof(f)); //初始化
//动态规划法//难点//
for(i=1;i<=n;i++) //
for(j=V;j>=volume[i];j--) //
f[j]=max(f[j],f[j-volume[i]]+value[i]); //核心(状态转移方程)
printf("%d\n",f[V]); //输出
}
return 0;
}
HDU 2546 饭卡
Problem Description
电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。
某天,食堂中有n种菜出售,每种菜可购买一次。已知每种菜的价格以及卡上的余额,问最少可使卡上的余额为多少。
Input
多组数据。对于每组数据:
第一行为正整数n,表示菜的数量。n<=1000。
第二行包括n个正整数,表示每种菜的价格。价格不超过50。
第三行包括一个正整数m,表示卡上的余额。m<=1000。
n=0表示数据结束。
Output
对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
Sample Input
1
50
5
10
1 2 3 2 1 1 2 3 2 1
50
0
Sample Output
-45
32
代码:
#include <iostream>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <stack>
#include <vector>
#include <algorithm>
#define max(a,b) (a>b?a:b)//自定义函数
using namespace std;
int main()
{
int m,n,a[2000];// m表示饭卡余额,n表示菜的种类,a[]表示每种菜的价格
int dp[2000]; // dp[]表示前i种菜最大的费用
int i,j,ans; //i表示所买的菜的序号,j表示第i种菜的价格
while(scanf("%d",&n)&&n) //第一行输入菜的种类
{
memset(dp,0,sizeof(dp)); //初始化
memset(a,0,sizeof(a)) ;
for(i=0;i<n;i++)
scanf("%d",&a[i]); //第二行输入每种菜的价格
scanf("%d",&m); //第三行输入饭卡余额
sort(a,a+n);
//动态规划法//
for(i=0;i<n-1;i++)
for(j=m-5;j>=a[i];j--)
dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
if(m>=5)
ans=m-(dp[m-5]+a[n-1]);
else
ans=m;
printf("%d\n",ans); //输出最低余额
}
return 0;
}
当一个题目中变量比较多时,注释很有用的,可以随时知道自己的思路,保持清晰的思路,以后编程尽量写注释!!!