HDU 1171 母函数或者01背包变形

Big Event in HDU

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


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
 

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 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
 

Author
lcy


题意:给出每个物体的价值和物体的数量,如何分使得A,B所得价值最接近并且A的价值不能小于B

下面有两种解法:

母函数解法:

#include
#include
#include
using namespace std;
int c1[1111115],c2[1111115];
int a[55];//硬币的价值
int n[55];//硬币的个数
int main()
{
    int i,j,k,m,T;
    while(~scanf("%d",&T)&&T>0)
    {
        m=0;
        for(i=1;i<=T;i++)
        {
            scanf("%d %d",&a[i],&n[i]);
            m+=a[i]*n[i];
        }
        memset(c1,0,sizeof(c1));
        memset(c2,0,sizeof(c2));
        for(i=0;i<=n[1]*a[1];i+=a[1])
        c1[i]=1;
        for(i=2;i<=T;i++)//i表示硬币价值的集合
        {
            for(j=0;j<=m;j++)
                for(k=0;k<=n[i]&&k*a[i]+j<=m;k++)
            {
                c2[k*a[i]+j]+=c1[j];
            }
            for(j=0;j<=m;j++)
            {
                c1[j]=c2[j];
                c2[j]=0;
            }
        }
        for(i=m/2;i>=0;i--)
        {
            if(c1[i]!=0) break;
        }
        cout<

01背包解法:

#include 
#include 
#include 
using namespace std;
int main()
{
    int n;
    int v1[20000],dp[300000];
    while(~scanf("%d",&n))
    {
        if(n<0)
            break;
        int v,t,sum = 0,k = 0;
        memset(dp,0,sizeof(dp));
        memset(v1,0,sizeof(v1));
        for(int i = 1; i <= n; i++)
        {
            scanf("%d%d",&v,&t);
            while(t--)
            {
                v1[k] = v;
                sum+=v;
                k++;
            }
        }
        for(int i = 0; i < k; i++)
            for(int j = sum/2; j >= v1[i]; j--)
             dp[j] = max(dp[j],dp[j-v1[i]]+v1[i]);
        printf("%d %d\n",sum-dp[sum/2],dp[sum/2]);
    }
    return 0;
}


你可能感兴趣的:(动态规划,母函数)