Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

多重背包,16MS过。以下是思想及代码!

Posted by qihongqi at 2012-12-25 17:43:32 on Problem 1014
计算total value如果为奇数则不可分;
否则平分total value 记做V,转化为多重背包cost和weight相等都为i(1..6),数量为输入的数据记为n[i];背包的容量为V。然后利用多重背包的优化算法(转化为0,1和完全背包)计算是否能装满容量为V的背包。在这里装满的条件是在初始化的时候对f(记录最优值的数组)有f[0]=0,其他都等于一个大的负数。最后如果F[v]=V则可以分解。以下是代码:
#include <iostream>

using namespace std;
const int MAX=120000;
const int len=7;
int f[MAX];
int n[len];
int V;
const int init=-9999;
int max(int a,int b)
{
    return a>b?a:b;
}
void zeroOnePack(int cw)
{
    for(int v=V;v>=cw;v--)
    f[v]=max(f[v],f[v-cw]+cw);
}
void completePack(int cw)
{
    for(int v=cw;v<=V;v++)
    f[v]=max(f[v],f[v-cw]+cw);
}
void multiplePack(int cw,int amount)
{
    if(cw*amount>V)
    {
        completePack(cw);
        return;
    }
    int k=1;
    while(k<amount)
    {
        zeroOnePack(k*cw);
        amount=amount-k;
        k=k*2;
    }
    zeroOnePack(amount*cw);
}
int main()
{
    int count=0;
    while(1)
    {
        count++;
        int i;
        int bin=0;
        int sum=0;
        for(i=1;i<len;i++)
        {cin>>n[i]; bin|=n[i];sum+=i*n[i];}
        if(bin==0) break;
        if(sum%2!=0)
        cout<<"Collection #"<<count<<":\n"<<"Can't be divided."<<endl<<endl;
        else
        {
            sum/=2;
            V=sum;
            f[0]=0;
            for(i=1;i<=V;i++)
                f[i]=init;//f的初始化要考虑是否装满背包
            for(i=1;i<len;i++)
            multiplePack(i,n[i]);
            if(f[V]!=V)
             cout<<"Collection #"<<count<<":\n"<<"Can't be divided."<<endl<<endl;
            else
             cout<<"Collection #"<<count<<":\n"<<"Can be divided."<<endl<<endl;
        }

    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator