程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> HDU1171:Big Event in HDU(多重背包)

HDU1171:Big Event in HDU(多重背包)

編輯:C++入門知識

Problem Description
Nowadays, we all know that Computer College is the biggest department in HDU. But, maybe you don't know that Computer College had ever been split into Computer College and Software College in 2002.
The splitting is absolutely a big event in HDU! At the same time, it is a trouble thing too. All facilities must go halves. First, all facilities are assessed, and two facilities are thought to be same if they have the same value. It is assumed that there is N (0<N<1000) kinds of facilities (different value, different kinds).

 


Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 50 -- the total number of different facilities). The next N lines contain an integer V (0<V<=50 --value of facility) and an integer M (0<M<=100 --corresponding number of the facilities) each. You can assume that all V are different.
A test case starting with a negative integer terminates input and this test case is not to be processed.

 


Output
For each case, print one line containing two integers A and B which denote the value of Computer College and Software College will get respectively. A and B should be as equal as possible. At the same time, you should guarantee that A is not less than B.

 


Sample Input
2
10 1
20 1
3
10 1
20 2
30 1
-1


Sample Output
20 10
40 40

 

之前用01背包做過,這次再用多重背包做一次

 

 

#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;

const int MAX=100000;
int dp[MAX];
int c[MAX],w[MAX];
int v;

void ZeroOnePack(int cost,int wei)//01
{
    int i;
    for(i = v; i>=cost; i--)
    {
        dp[i] = max(dp[i],dp[i-cost]+wei);
    }
}

void CompletePack(int cost,int wei)//完全
{
    int i;
    for(i = cost; i<=v; i++)
    {
        dp[i] = max(dp[i],dp[i-cost]+wei);
    }
}

void MultiplePack(int cost,int wei,int cnt)//多重
{
    if(v<=cnt*cost)//如果總容量比這個物品的容量要小,那麼這個物品可以直到取完,相當於完全背包
    {
        CompletePack(cost,wei);
        return ;
    }
    else//否則就將多重背包轉化為01背包
    {
        int k = 1;
        while(k<=cnt)
        {
            ZeroOnePack(k*cost,k*wei);
            cnt = cnt-k;
            k = 2*k;
        }
        ZeroOnePack(cnt*cost,cnt*wei);
    }
}

int main()
{
    int n;
    while(~scanf("%d",&n),n>0)
    {
        int i,sum;
        v = 0;
        for(i = 0; i<n; i++)
        {
            scanf("%d%d",&c[i],&w[i]);
            v+=c[i]*w[i];
        }
        sum = v;
        v = v/2;
        memset(dp,0,sizeof(dp));
        for(i = 0; i<n; i++)
        {
            MultiplePack(c[i],c[i],w[i]);
        }
        printf("%d %d\n",sum-dp[v],dp[v]);
    }
    return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved