母函数,先要算搞清楚组合数可能的最大值。非常大。N种设备的最大VAL*最大数量。
#include <stdio.h>
#include <string.h> #define MAXNUM 500000 typedef struct {
int val, num;
} fac_st; fac_st facs[];
int c1[MAXNUM], c2[MAXNUM]; int main() {
int n, sum, tmp;
int i, j, k; while (scanf("%d", &n) != EOF && (n>=)) {
sum = ;
for (i=; i<=n; ++i) {
scanf("%d %d", &facs[i].val, &facs[i].num);
sum += facs[i].val * facs[i].num;
}
memset(c1, , sizeof(c1));
memset(c2, , sizeof(c2));
for (i=, j=; i<=facs[].num; ++i, j+=facs[].val)
c1[j] = ;
for (i=; i<=n; ++i) {
for (j=; j<=sum; ++j) {
tmp = facs[i].val * facs[i].num;
for (k=; k<=tmp && (k+j)<=sum; k+=facs[i].val)
c2[k+j] += c1[j];
}
for (j=; j<=sum; ++j) {
c1[j] = c2[j];
c2[j] = ;
}
}
k = sum/;
if (c1[k])
printf("%d %d\n", sum-k, k);
else {
for (i=k+; i<=sum; ++i)
if (c1[i]) {
printf("%d %d\n", i, sum-i);
break;
}
}
} return ;
}