其他分享
首页 > 其他分享> > 【完全背包问题】AcWing3.完全背包问题——朴素、优化、状压、思维转换

【完全背包问题】AcWing3.完全背包问题——朴素、优化、状压、思维转换

作者:互联网

AcWing3.完全背包问题

题解

朴素写法

#include <iostream>

using namespace std;

const int N = 1010;

int v[N], w[N];
int f[N][N];

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

优化写法

二维

#include <iostream>

using namespace std;

const int N = 1010;

int v[N], w[N];
int f[N][N];

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

一维

#include <iostream>

using namespace std;

const int N = 1010;

int v[N], w[N];
int f[N];

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

思维转换

#include <iostream>

using namespace std;

const int N = 1010;

int v[N], w[N];
int f[N];

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

标签:main,背包,int,状压,namespace,using,include,1010,AcWing3
来源: https://www.cnblogs.com/czy-algorithm/p/16371769.html