hdu1171(母函数或多重背包)

题意:把物品分成两份,使得价值最接近
可以用背包,或者是母函数来解,母函数(1 + x^v+x^2v+.....+x^num*v)(1 + x^v+x^2v+.....+x^num*v)(1 + x^v+x^2v+.....+x^num*v)

其中指数为价值,每一项的数目为(该物品数+1)个

代码如下:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define  N 250000 + 5
#define inf 0x7ffffff
#define eps 1e-9
#define pi acos(-1.0)
#define P system("pause")
using namespace std;
struct node
{
    int num,v;
}s[100];
int c1[N],c2[N];
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
    int n;
    while(scanf("%d",&n) && n > 0)
    {
        int i, j, k,z,sum = 0;
        for(i = 0; i < n; i++)
        {
            scanf("%d%d",&s[i].v,&s[i].num);
            sum += s[i].v*s[i].num;
        }
        memset(c1,0,sizeof(c1));
        memset(c2,0,sizeof(c2));
        c1[0] = 1;
        for(i = 0; i < n; i++)//遍历每一项
        {
            for(j = 0; j <= sum/2; j++)//多项式相乘
                for(k = 0,z = 0; j+k <= sum/2; z++,k += s[i].v)
                {

                    c2[j+k] += c1[j];
                    if(z == s[i].num)
                        break;
                }
            for(j = 0; j <= sum/2; j++)
            {
                c1[j] = c2[j];
                c2[j] = 0;
            }
        }
        int res ;
        for(i = sum/2; i >= 0; i--)
            if(c1[i]){
                res = i;
                break;
            }
        printf("%d %d\n",sum - res,res);


    }
    return 0;
}


你可能感兴趣的:(acm之母函数)