题目大意:有面值 1,2,5的硬币 n 1 , n 2 , n 5 n_1,n_2,n_5 n1,n2,n5枚,输出不能用这些硬币凑出的金额中最小的金额。
有两种做法,一种是直接转01背包,由于数据范围较小可以直接暴力转,复杂度为
(
3000
∗
8000
)
(3000 * 8000)
(3000∗8000)
另一种做法:
e
1
+
2
∗
e
2
+
5
∗
e
5
=
i
e_1 + 2*e2 + 5 * e_5 = i
e1+2∗e2+5∗e5=i
构造生成函数:
(
1
+
x
+
x
2
+
x
3
+
.
.
.
+
x
n
1
)
∗
(
1
+
x
2
+
x
4
+
.
.
+
x
n
2
∗
2
)
∗
1
+
x
5
+
x
10
+
.
.
.
+
x
5
∗
n
3
(1 + x + x^2 + x^3 +... + x^{n_1}) * (1 + x^2 + x^4 + .. + x ^ {n_2 * 2}) * {1 + x^5 + x^{10} + ... + x^{5 * n_3}}
(1+x+x2+x3+...+xn1)∗(1+x2+x4+..+xn2∗2)∗1+x5+x10+...+x5∗n3最小的系数为0的项就是答案
暴力拆解,复杂度也是
O
(
3000
∗
8000
)
O(3000 * 8000)
O(3000∗8000)
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e4 + 10;
int n[4];
int tot;
int g1[maxn],g2[maxn];
int v[4] = {0,1,2,5};
int main() {
while(scanf("%d%d%d",&n[1],&n[2],&n[3])) {
if(!n[1] && !n[2] && !n[3]) break;
tot = n[1] + 2 * n[2] + 5 * n[3];
for(int i = 0; i <= tot; i++) g1[i] = g2[i] = 0;
for(int i = 0; i <= n[1]; i++) g1[i] = 1;
for(int i = 2; i <= 3; i++) {
for(int j = 0; j <= tot; j++)
for(int k = 0; k * v[i] + j <= tot && k <= n[i]; k++)
g2[k * v[i] + j] += g1[j];
for(int j = 0; j <= tot; j++)
g1[j] = g2[j],g2[j] = 0;
}
bool f = true;
for(int i = 0; i <= tot; i++) {
if(!g1[i]) {
f = false;
printf("%d\n",i);
break;
}
}
if(f) printf("%d\n",tot + 1);
}
return 0;
}