首页 > 代码库 > 01背包

01背包

#include<iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<queue>#include<vector>#include<cstring>#include<cmath>#include<map>using namespace std;typedef long long ll;#define N 2011111int dp[555555];int main(){    int n,m;    cin>>n>>m;    for(int i=0;i<=m;i++)dp[i]=-1;    dp[0]=0;    //for(int i=0;i<=m;i++)cout<<dp[i]<<" ";cout<<endl;    while(n--){        int w,v;        cin>>w>>v;        for(int i=max(m-w,0);i>=0;i--)if(dp[i]!=-1)dp[i+w]=max(dp[i+w],dp[i]+v);        //for(int i=0;i<=m;i++)cout<<dp[i]<<" ";cout<<endl;    }    int x=0;    for(int i=0;i<=m;i++)x=max(x,dp[i]);    cout<<x<<endl;    return 0;}

 

01背包