题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=2546
根据题目,当只剩下5元的时候,肯定选择最贵的菜。
所以,直接用5元买最贵的菜,剩下的钱没有限制,所以直接用0/1背包解就可以了
/*HDOJ2546
作者:陈佳润
2013-04-17
*/
#include<iostream>
#include<string.h>
using namespace std;
#define max(a,b) (a>b?a:b)
int good[1005];//菜的价格
int dp[50005];//dp数组
int n;//菜的种类数目
int m;//卡的越
void Zero_One_Pack(int value,int weight){//0/1背包
int j;
for(j=m;j>=weight;j--){
dp[j]=max(dp[j],dp[j-weight]+value);
}
}
int main(){
int i,maxIndex,maxValue;
//freopen("1.txt","r",stdin);
while(cin>>n&&n){
for(i=1;i<=n;i++)//读取菜的价格
cin>>good[i];
cin>>m;//读取卡余额
if(m<5){//如果卡不足5元
cout<<m<<endl;
continue;
}
//找出最贵的菜
maxIndex=1;
maxValue=good[1];
for(i=2;i<=n;i++){
if(maxValue<good[i]){
maxValue=good[i];
maxIndex=i;
}
}
good[maxIndex]=0;//选中那个菜,所以让它的价格变成0,相当于删掉它
m-=5;//花了5块去点那个最贵的
memset(dp,0,sizeof(dp));//初始化
for(i=1;i<=n;i++)//背包
Zero_One_Pack(good[i],good[i]);
cout<<m-dp[m]+5-maxValue<<endl;
}
return 0;
}