您的位置:首页 > 其它

动态规划解决POJ 3624

2011-09-23 22:23 246 查看
Description

Bessiehasgonetothemall'sjewelrystoreandspiesacharmbracelet.Ofcourse,she'dliketofillitwiththebestcharmspossiblefromtheN(1≤N≤3,402)availablecharms.EachcharmiinthesuppliedlisthasaweightWi(1≤Wi≤400),a'desirability'factorDi(1≤Di≤100),andcanbeusedatmostonce.BessiecanonlysupportacharmbraceletwhoseweightisnomorethanM(1≤M≤12,880).

Giventhatweightlimitasaconstraintandalistofthecharmswiththeirweightsanddesirabilityrating,deducethemaximumpossiblesumofratings.

Input

*Line1:Twospace-separatedintegers:NandM
*Lines
2..N+1:Linei+1describescharmiwithtwospace-separated
integers:WiandDi

Output

*Line1:Asingleintegerthatisthegreatest
sumofcharmdesirabilitiesthatcanbeachievedgiventheweight
constraints

SampleInput

46
14
26
312
27

SampleOutput

23


ViewCode

#include<iostream>
usingnamespacestd;
intf[12881];//f[k]表示:当背包的容量为k时的最大价值
intmax(inta,intb)
{
returna>b?a:b;
}
intmain()
{
intNum,TotalWeight,i,k,j,weight[12881],value[12881];
cin>>Num>>TotalWeight;
f[0]=0;
for(i=0;i<Num;i++)
cin>>weight[i]>>value[i];
for(i=0;i<Num;i++)
for(k=TotalWeight;k>=weight[i];k--)
{
f[k]=max(f[k],(f[k-weight[i]]+value[i]));
//在max中的两个参数f[k],和f[k-weight[i]]+value[i]都是表示在背包容量为k时的最大价值
//f[k]是这个意思,就不用说了。
//而f[k-weight[i]]+value[i]也表示背包容量为k时的最大价值是为什么呢?
//首先,f[k-weight[i]]表示的是背包容量为k-weight[i]的容量,也就是说f[k-weight[i]]
//表示的是容量还差weiht[i]才到k的价值,+walue[i]恰好弥补了差的这个价值。所以……

//如果你对f[k]=max(f[k],(f[k-weight[i]]+value[i]));这句话不是很清楚,
//下面的这句代码会对你有帮助
//cout<<"i="<<i+1<<"f["<<k<<"]="<<f[k]<<endl;
}
cout<<f[TotalWeight]<<endl;
return0;
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: