读书人

旅行准备解决方法

发布时间: 2012-04-19 14:36:43 作者: rapoo

旅行准备
由于你出色的完成了上面一题,你的地理老师十分高兴(地理老师也十分嫉妒生物老
师),决定带你到新疆阿克苏旅行,你很高兴的开始准备旅行。
现在你有M元钱,可以采购N种物品,每种物品最多可以购买Ai件(也可以不购买),
每购买一件会花费Ci元,并能产生Vi的价值。请算出你能买的物品的最大价值和。
【输入】
输入文件名为prepare.in。
第一行,两个整数M,N用空格隔开。后面N行,每行三个整数用空格隔开Ai、Ci、Vi
【输出】
输出文件名为prepare.out。
一个整数,能买的物品的最大价值和
【输入输出样例】
prepare.inprepare.out
40 4
1 20 5
2 10 7
3 15 19
4 5 1 45


[解决办法]
背包问题中 的 多重背包问题 :
楼主看下 背包九讲:
http://wenku.baidu.com/view/8b3c0d778e9951e79b892755.html
[解决办法]

C/C++ code
#include <iostream>using namespace std;struct Goods{    int totalNumber;    int singlePrice;    int singleValue;    float rate;//类似于性价比};void sort(int n,Goods *dataGroup)//pop sort by rate{    int i,j;    Goods temp;        for (i=n-2;i>=0;i--)    {        for (j=0;j<=i;j++)        {            if (dataGroup[j].rate>dataGroup[j+1].rate)            {                temp=dataGroup[j];                dataGroup[j]=dataGroup[j+1];                dataGroup[j+1]=temp;            }        }    }}int f(int n,Goods *dataGroup,int M){    int totalValue=0;    int index=n-1;    int i;    while (M>0 && index>=0)    {        for (i=0;i<dataGroup[index].totalNumber;i++)        {            if (M-dataGroup[index].singlePrice>=0)            {                totalValue+=dataGroup[index].singleValue;                M-=dataGroup[index].singlePrice;            }            else            {                break;            }        }        index--;    }    return totalValue;}int main(){    int M,n;    cin>>M;    cin>>n;    //input    int i;    Goods *dataGroup=new Goods[n];    for (i=0;i<n;i++)    {        cin>>dataGroup[i].totalNumber;        cin>>dataGroup[i].singlePrice;        cin>>dataGroup[i].singleValue;        dataGroup[i].rate=(float)dataGroup[i].singleValue/dataGroup[i].singlePrice;    }    sort(n,dataGroup);    int MaxValue=f(n,dataGroup,M);    cout<<MaxValue<<endl;    delete[]dataGroup;    return 0;} 

读书人网 >C语言

热点推荐