本文主要是介绍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<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
#include<math.h>#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;
}
这篇关于hdu1171(母函数或多重背包)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!