hdu2069 Coin Change(母函数 or 二维完全背包)
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
final int MAXN = 251;
int n;
int[] ans = new int[MAXN];
// int c1, c5, c10, c25, c50;
// for (n = 0; n <= 250; n++) {
// for (c5 = 0; c5 * 5 <= n; c5++) {
// for (c10 = 0; c5 * 5 + c10 * 10 <= n; c10++) {
// for (c25 = 0; c5 * 5 + c10 * 10 + c25 * 25 <= n; c25++) {
// for(c50 = 0; c5 * 5 + c10 * 10 + c25 * 25 + c50 * 50 <= n; c50 ++) {
// c1 = n - (c5 * 5 + c10 * 10 + c25 * 25 + c50 * 50);
// if (c1 + c5 + c10 + c25 + c50 <= 100) ans[n]++;
// }
// }
// }
// }
// }
final int[] coinKinds = { 1, 5, 10, 25, 50 };
int[][] c1 = new int[MAXN][MAXN];
int[][] c2 = new int[MAXN][MAXN];
c1[0][0] = 1;
int i, j, k, l;
n = 250;
for(i = 0; i < 5; i++) {
for(j = 0; j <= n; j++) {
for(k = 0; k * coinKinds[i] + j <= n; k++) {
for(l = 0; l + k <= 100; l++) {
c2[k * coinKinds[i] + j][l+k] += c1[j][l];
}
}
}
for(j = 0; j <= n; j++) {
for(l = 0; l <= 100; l++) {
c1[j][l] = c2[j][l];
c2[j][l] = 0;
}
}
}
for(j = 0; j <= n; j++) {
for(l = 0; l <= 100; l++) {
ans[j] += c1[j][l];
}
}
while (cin.hasNext()) {
n = cin.nextInt();
System.out.println(ans[n]);
}
}
}
//完全背包, 0ms:
//0ms:
#include <stdio.h>
#define MAXN 105
#define MAXM 255
const int weight[5] = { 1, 5, 10, 25, 50 };
int sum, ans[MAXM];
int f[MAXN][MAXM]; //f[i][j]:i个硬币,价值j元的组合数
void CompletePack(int w)
{
int i, j;
for(i = 1; i <= 100; i++)
{
for(j = w; j <= sum; j++)
{
f[i][j] += f[i - 1][j - w];
}
}
}
void init()
{
sum = 250;
f[0][0] = 1;
int i;
for(i = 0; i < 5; i++) CompletePack(weight[i]);
for(i = 0; i <= sum; i++)
{
for(int j = 0; j <= 100; j++)
{
ans[i] += f[j][i];
}
}
}
int main()
{
init();
int n;
while(scanf("%d", &n) != EOF)
{
printf("%d\n", ans[n]);
}
return 0;
}
浙公网安备 33010602011771号