DP入门--背包问题

01背包

#include
using namespace std;

const int maxn = 505;
const int maxm = 1e5+5;

int n, m, f[maxn][maxm], need[maxn], value[maxn];

int main(){
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> need[i] >> value[i];
    }
    memset(f, 0, sizeof f);
    //初试状态
    for(int i = 0; i < n; i++){
        for(int j = 0; j <= m; j++){
            if(j < need[i]){
                f[i+1][j] = f[i][j];
            }
            else{
                f[i+1][j] = max(f[i][j], f[i][j-need[i]] + value[i]);
            }
        }
    }
    cout << f[n][m] << endl;
    return 0;
}

01背包--一维数组

#include
using namespace std;

const int maxn = 505;
const int maxm = 1e5+10;

int n, m, f[maxm], need[maxn], value[maxn];

int main(){
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> need[i] >> value[i];
    }
    memset(f, 0, sizeof f);
    for(int i = 0; i < n; i++){
        for(int j = m; j >= need[i]; j--){
            f[j] = max(f[j], f[j-need[i]] + value[i]);
        }
    }
    cout << f[m] << endl;
    return 0;
}

完全背包

#include
using namespace std;

const int maxn = 505;
const int maxm = 1e5+5;

int n, m, f[maxn][maxm], need[maxn], value[maxn];

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

完全背包--一维数组

#include
using namespace std;

const int maxn = 505;
const int maxm = 1e5+5;

int n, m, f[maxm], need[maxn], value[maxn];

int main(){
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> need[i] >> value[i];
    }
    memset(f, 0, sizeof f);
    for(int i = 0; i < n; i++){
        for(int j = need[i]; j <= m; j++){
            f[j] = max(f[j], f[j-need[i]] + value[i]);
        }
    }
    cout << f[m] << endl;
    return 0;
}

 

你可能感兴趣的:(dp)