题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1171
解题思路:
由母函数可知,数组c1[i]代表i一共有多少种组合,所以c1[i]为0,代表该数没有可行解,从总数的一半开始,往下面找,直到找到一个不为0的i,即为所求。。。
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cstring> using namespace std; int c1[100000],c2[100000]; int a[55],num[55]; int main(){ int n; while(scanf("%d",&n),n > 0){ //然而这里并不能写成n != -1... int sum = 0; int i,j,k; memset(c1,0,sizeof(c1)); memset(c2,0,sizeof(c2)); for(i = 0; i < n; i++){ scanf("%d%d",&a[i],&num[i]); sum += a[i]*num[i]; } int mid = sum/2; for(i = 0; i <= num[0]; i++) c1[i*a[0]] = a[0]; for(i = 1; i < n; i++){ for(j = 0; j <= mid; j++) for(k = 0; k <= num[i] && k*a[i]+j <= mid;k++) c2[k*a[i]+j] += c1[j]; for(j = 0; j <= mid; j++){ c1[j] = c2[j]; c2[j] = 0; } } for(i = mid; i >= 0; i--) if(c1[i]) break; printf("%d %d\n",sum-i,i); } return 0; }