AcWing 1371.货币系统

题解:货币系统

题目描述

在这里插入图片描述

题目链接:
https://www.acwing.com/problem/content/description/1373/

思路分析

动态规划
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码描述

二维空间写法

#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];

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_45657288/article/details/113073711