USACO货币系统(完全背包解析)

给定 V 种货币(单位:元),每种货币使用的次数不限

不同种类的货币,面值可能是相同的。

现在,要你用这 V 种货币凑出 N 元钱,请问共有多少种不同的凑法。

输入格式
第一行包含两个整数 V 和 N。

接下来的若干行,将一共输出 V 个整数,每个整数表示一种货币的面值。

输出格式
输出一个整数,表示所求总方案数。

数据范围
1≤V≤25,
1≤N≤10000
答案保证在long long范围内。

输入样例:
3 10
1 2 5
输出样例:
10

在这里插入图片描述

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;
const int N = 30, M = 10010;

int n, m;
LL f[N][M];//f[i][j]为1到i物品中总钱数为j的方案

int main()
{
    
    
    cin >> n >> m;
    f[0][0] = 1;
    for (int i = 1; i <= n; i ++ )
    {
    
    
        int v;
        cin >> v;
        for (int j = 0; j <= m; j ++ ){
    
    
            f[i][j]=f[i-1][j];
            if(j>=v)
            f[i][j]+=f[i][j-v];
        }
    }
    cout << f[n][m] << endl;
    return 0;
}

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;
const int N = 30, M = 10010;

int n, m;
LL f[M];

int main()
{
    
    
    cin >> n >> m;
    f[0] = 1;
    for (int i = 1; i <= n; i ++ )
    {
    
    
        int v;
        cin >> v;
        for (int j = v; j <= m; j ++ ){
    
    
            f[j]=f[j]+f[j-v];
        }
    }
    cout << f[m] << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43738331/article/details/113061029