http://acm.hdu.edu.cn/showproblem.php?pid=1085
题意:有三个硬币面值分别是1,2,5。输入三个硬币的个数,要求出这三个硬币不能组成的最小的面值。
思路:可以用母函数或者多重背包。
母函数代码(171ms):
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int coin[3] = {1, 2, 5};
int nex[8005],temp[8005];
int main()
{
int num[3];
while(cin>>num[0]>>num[1]>>num[2] && (num[0] || num[1] || num[2]))
{
int maxn = num[0] * 1 + num[1] * 2 + num[2] * 5; //最高次幂
memset(nex, 0, sizeof(nex));
memset(temp, 0, sizeof(temp));
for(int i = 0; i <= num[0]; i++){
nex[i] = 1;
}
//母函数为(1+x+x^2+...x^num[0])(1+x^2+x^4+....x^2*num[1])(1+x^5+x^10+...+x^5*num[2])
for(int i = 1; i < 3; i++) //一共三项
{
for(int j = 0; j <= maxn; j++) //x^j
{
for(int k = 0; k + j <= maxn && k <= coin[i] * num[i]; k += coin[i]){ //x^k
temp[k+j] += nex[j]; //相乘后x^(k+j)的系数加上x^k的系数乘以x^j的系数
}
}
//更新
for(int j = 0; j <= maxn; j++){
nex[j] = temp[j];
temp[j] = 0;
}
}
for(int i = 0; i <= maxn+1; i++){
if(nex[i] == 0)
{
cout<<i<<endl;
break;
}
}
}
return 0;
}
多重背包(0ms):
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int dp[8005];
void ZeroOnePack(int volume, int val, int vol) //01背包
{
for(int i = volume; i >= vol; i--){
dp[i] = dp[i-vol] + val;
}
}
void CompletelyPack(int volume, int val, int vol) //完全背包
{
for(int i = vol; i <= volume; i++){
dp[i] = dp[i-vol] + val;
}
}
void MultiplePack(int volume, int val, int vol, int counts)//多重背包
{
if(vol * counts > volume){ //装不下当前物体,看作完全背包
CompletelyPack(volume, val, vol);
} else{
int mid = 1;
while(mid <= counts){ //将物体拆成1,2,4,..... 然后当成01背包
ZeroOnePack(volume, val*mid, vol*mid);
counts = counts - mid;
mid = mid << 1;
}
if(counts){
ZeroOnePack(volume, val*counts, vol*counts); //剩下的
}
}
}
int main()
{
int x, y, z;
while(cin>>x>>y>>z && (x || y || z))
{
memset(dp, 0, sizeof(dp));
int volume = x + 2 * y + 5 * z;
MultiplePack(volume, 1, 1, x);
MultiplePack(volume, 2, 2, y);
MultiplePack(volume, 5, 5, z);
for(int i = 1; i <= volume+1; i++){
if(dp[i] != i){
cout<<i<<endl;
break;
}
}
}
return 0;
}