多重背包转01背包/母函数(1171)

来源:互联网 发布:高速公路机电系统优化 编辑:程序博客网 时间:2024/06/05 14:36

Big Event in HDU

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31953    Accepted Submission(s): 11181


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
210 120 1310 1 20 230 1-1
 

Sample Output
20 1040 40

方法1:多重背包转化为01背包,价值总量的一半作为背包容量。

/*------------------Header Files------------------*/#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <algorithm>#include <cstdlib>#include <ctype.h>#include <cmath>#include <stack>#include <queue>#include <map>#include <vector>#include <limits.h>using namespace std;/*------------------Definitions-------------------*/#define LL long long#define PI acos(-1.0)#define INF 0x3F3F3F3F#define MOD 10E9+7/*---------------------Work-----------------------*/int fac[10000];int dp[100000];void work(){int N;while(cin>>N){if(N<0) break;int cnt=0,sum=0;int V,M;while(N--){scanf("%d%d",&V,&M);for(int i=1;i<=M;i++) fac[cnt++]=V;sum=sum+V*M;}cnt--;memset(dp,0,sizeof(dp));for(int i=0;i<=cnt;i++)for(int j=sum/2;j>=fac[i];j--)dp[j]=max(dp[j],dp[j-fac[i]]+fac[i]);printf("%d %d\n",max(dp[sum/2],sum-dp[sum/2]),min(dp[sum/2],sum-dp[sum/2]));}}/*------------------Main Function------------------*/int main(){//freopen("test.txt","r",stdin);//freopen("cowtour.out","w",stdout);//freopen("cowtour.in","r",stdin);work();return 0;}

方法2:母函数


0 0
原创粉丝点击