AcWing 3. 完全背包问题

AcWing 3. 完全背包问题

 

 

朴素

#include<iostream>
#include<algorithm>
using namespace std ;
const int N=1010;
int n,m;
int v[N],w[N];
int f[N][N];
int main() {
    cin>>n>>m;//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++)
            for(int k=0; k*v[i]<=j; k++)//选k个第i个物品   
                f[i][j]=max(f[i][j],f[i-1][j-v[i]*k]+k*w[i]);
    cout<<f[n][m]<<endl;
    return 0;
}

 

优化二维

//01背包从i-1转移过来   而完全背包是从第

 

i层转移过来
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[N][N];
int main() {
    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 ++ )
            for(int k=0; k*v[i]<=j; k++)
                f[i][j] = max(f[i][j], f[i-1][j - v[i]*k] + w[i]*k);
    cout << f[n][m] << endl;
    return 0;
}

 

 

 

 

 

终极一维

//一维
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[N];
int main() {
    cin >> n >> m;//n是数量,m是体积 
    for (int i = 1; i <= n; i ++ )
        cin >> v[i] >> w[i];
    for (int i = 1; i <= n; i ++ )
        for (int j = v[i]; j <= m; j ++ )
            f[j] = max(f[j], f[j - v[i]] + w[i]);
    cout << f[m] << endl;
    return 0;
}

 

 

 

 

 

 

 

AcWing 3. 完全背包问题

上一篇:ACwing95 费解的开关 bfs


下一篇:ACwing98 分形之城 分形图