Charm Bracelet poj 3624 (01) 背包问题 c++
2014-08-02 09:16
204 查看
CharmBracelet
TimeLimit:1000MS | MemoryLimit:65536K | |
TotalSubmissions:23076 | Accepted:10383 |
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
*Lines2..N+1:Linei+1describescharmiwithtwospace-separatedintegers:Wiand
Di
Output
*Line1:Asingleintegerthatisthegreatestsumofcharmdesirabilitiesthatcanbeachievedgiventheweightconstraints
SampleInput
46 14 26 312 27
SampleOutput
23
#include<cstdio>
#include<cstring>
#include<cmath>
usingnamespacestd;
intw[5000],v[5000];
intf[14000];
intmax(inta,intb)
{
if(a<b)
returnb;
returna;
}
intmain()
{
inti,j,n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(w,0,sizeof(w));
memset(v,0,sizeof(v));
memset(f,0,sizeof(f));
for(i=1;i<=n;i++)
scanf("%d%d",&w[i],&v[i]);
for(i=1;i<=n;i++)
for(j=m;j>=w[i]&&j>0;j--)
f[j]=max(f[j],f[j-w[i]]+v[i]);
printf("%d\n",f[m]);
}
return0;
}
//第一次做01背包问题,是个入门题,注意数组开的要大一点,还有就是,这个题用二维数组会超内存;
后来和同学讨论的只定义一个数组就可以了,没必要定义三个,代码如下:
#include<cstdio>
#include<cstring>
intmain()
{
inta,b,dp[1100],i,j,v,n;
while(scanf("%d%d",&n,&v),!(n==0&&v==0))
{
memset(dp,0,4400);
for(i=1;i<=n;i++)
{
scanf("%d%d",&a,&b);
for(j=v;j>=a;j--)
if(dp[j]<dp[j-a]+b)
dp[j]=dp[j-a]+b;
}
printf("%d\n",dp[v]);
}
return0;
}
相关文章推荐
- 01背包问题:Charm Bracelet (POJ 3624)(外加一个常数的优化)
- 01背包、完全背包、多重背包问题的C++实现及路径记录
- 01背包问题 及c++ 代码实现
- 简单背包问题——百炼01:Charm Bracelet
- 01背包、完全背包、多重背包问题的C++实现
- 01背包问题的C/C++实现
- 动态规划解背包问题/C++/Knapsack problem
- 0-1背包问题(C++)
- P01:01背包问题(转)
- 用贪心算法求解普通背包问题的C++代码
- 01背包问题-我犯的错误记录
- 01 背包问题
- dynamic programming --knapsack problem 背包问题(c++实现)
- 01背包问题---C源程序
- 01背包问题
- 01背包问题
- 01背包问题动态规划详解(转载)
- 01背包问题动态规划详解
- 01背包问题
- hdu 2602 Bone Collector (01 背包问题)