poj1014Dividing

来源:互联网 发布:caffe 训练自己的模型 编辑:程序博客网 时间:2024/06/08 07:15

这道是比较裸的多重背包,采用背包九讲里边的模式来写,写三个函数同时采用01背包的二分优化,以及一些类似剪枝优化。

#include<stdio.h>#include<iostream>#include<string.h>#include<algorithm>using namespace std;int dp[101000],V;bool flag;void ZeroOnePack(int cost,int weight){    for(int i=V; i>=cost; i--)    {        dp[i]=max(dp[i],dp[i-cost]+weight);        if(dp[i]==V)        {            flag=true;            return;        }    }    return ;}void CompletePack(int cost,int weight){    for(int i=cost; i<=V; i++)    {        dp[i]=max(dp[i],dp[i-cost]+weight);        if(dp[i]==V)        {            flag=true;            return ;        }    }}void MultiplePack(int cost,int weight,int amount){    if(cost*amount>=V)                //判断该类物品总价值是否大于背包容量    {        CompletePack(cost,weight);    //如果大于,即可以看做是完全背包,因为对于背包来说取不完        return ;    }    int k=1;                          //进行01背包二进制优化    while(k<amount)                   //如13可分为1、2、4、6,这四个数即可表示所有13以内的数     {        ZeroOnePack(k*cost,k*weight);        if(flag)                       //优化                             return;        amount-=k;        k*=2;    }    ZeroOnePack(amount*cost,amount*weight); //最后剩余的amount当做一个整体    return ;}int main(){    int n[10],t=0;    while(cin>>n[1]>>n[2]>>n[3]>>n[4]>>n[5]>>n[6])    {        t++;        int sumvalue=0;        for(int i=1; i<=6; i++)            sumvalue+=n[i]*i;        if(sumvalue==0)            break;        if(sumvalue%2==1)                    //如果为奇数不能平分,优化        {            cout<<"Collection #"<<t<<":"<<endl;            cout<<"Can't be divided."<<endl<<endl;            continue;        }        V=sumvalue/2;                        //定义背包容量        memset(dp,0,sizeof(dp));  //        flag=false;        for(int i=1; i<=6; i++)        {            MultiplePack(i,i,n[i]);          //对6类物品进行多重背包            if(flag)                         //如果已经达到背包容量,跳出循环                break;        }        if(flag)        {            cout<<"Collection #"<<t<<":"<<endl;            cout<<"Can be divided."<<endl<<endl;            continue;        }        else        {            cout<<"Collection #"<<t<<":"<<endl;            cout<<"Can't be divided."<<endl<<endl;            continue;        }    }    return 0;}


0 0
原创粉丝点击