C++ 動態規劃經典題 01 背包 (atcoder)

前提是n*W不能太大。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

ll dp[105][100010],v[105],w[105];

int main(){
    ios::sync_with_stdio(0);cin.tie(0);

    int n,W;
    cin>>n>>W;
    for(int i=1;i<=n;i++){
        cin>>w[i]>>v[i];
    }

    for(int i=1;i<=n;i++){
        for(int j=1;j<=W;j++){
            if(w[i]>j) dp[i][j]=dp[i-1][j];
            else{
                dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);
            }
        }
    }
    cout<<dp[n][W];
    return 0; 
}

發佈留言