hdu1171 Big Event in HDU(生成函数)

来源:互联网 发布:js一句话木马 编辑:程序博客网 时间:2024/05/17 01:19

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

 Statistic | Submit | Discuss | Note


分析:
生成函数
我们可以得到一个生成函数
(就拿第二个输入样例来说吧)
(1+x^10)(1+x^20+x^40)(1+x^30)
因为数据范围小,所以我们可以直接计算出每一个x^n的系数

记s为能够付的最大钱数
因为我们要把钱分成两部分,使得两部分尽量接近
所以我们从s/2开始,一个一个检查系数是否为0
遇到的第一个非零项a就是答案:a,s-a

tip

我一开始在模拟计算系数的时候,只用了一个数组,但是这样是不行的
实际上这道题也可以用背包(dp)做
我们计算系数的时候,就是用背包的思想

对于每个物品,我们需要一个一个添加(第i个物品需要添加num[i]次)
为什么要这样呢?
因为我们在进行01背包的时候,是逆序进行的,避免的就是重复计算
我们用两个数组也是这个作用
(虽然我发现用一个数组,每个元素一个一个添加也是可以A的,但是这样是有风险的)

最后的结束标志是一个负数(negative integer)

//这里写代码片#include<cstdio>#include<cstring>#include<iostream>using namespace std;int c1[1000010],c2[1000010];int a[55],num[55];int n;int main(){    while (scanf("%d",&n)!=EOF)    {        if (n<0) break;        memset(c1,0,sizeof(c1));        memset(c2,0,sizeof(c2));        int s=0;        for (int i=1;i<=n;i++)        {            scanf("%d%d",&a[i],&num[i]);            s+=a[i]*num[i];          //最大价值         }        for (int i=0;i<=num[1];i++) c1[a[1]*i]=1;        for (int i=2;i<=n;i++)       //两个多项式c1 c2相乘         {            for (int j=0;j<=s;j++)            if (c1[j])               //选取c1[]多项式中的第j个元素(系数存在)             {                for (int k=0;k<=num[i]*a[i]&&k<=s;k+=a[i])                     if (j+k<=s)                       c2[k+j]=c1[j];             }            for (int j=0;j<=s;j++)   //更新             {                c1[j]=c2[j];                c2[j]=0;            }        }        int i,j;            if (s%2==0) i=s/2;          else i=s/2+1;        for (j=i;;j++)            if (c1[j]) {                printf("%d %d\n",j,s-j);                break;            }    }    return 0;}
原创粉丝点击