01背包-入门二题(poj3624 hdu2602)

二维数组 hdu2602

#include <iostream>
#include <cstring>
using namespace std;

const int maxn=4000;

int dp[13000];
int d;
int w;
int n,wl;

int main(){
    memset(dp,0,sizeof(dp));
    cin>>n>>wl;
    for(int i=1;i<=n;i++){//前i种物品 
    cin>>w>>d;
        for(int j=wl;j>=1;j--){//容量为j 
            if(j>=w) dp[j]=max(dp[j],dp[j-w]+d); 
        }
    }
    cout<<dp[wl]<<endl;
    return 0;
}
View Code

一维数组

#include <iostream>
#include <cstring>
using namespace std;

const int maxn=4000;

int dp[13000];
int d[maxn];
int w[maxn];
int n,wl,t;

int main(){

    cin>>t;
    while(t--){
    memset(dp,0,sizeof(dp));
    cin>>n>>wl;
    for(int i=1;i<=n;i++)
    cin>>d[i];
    for(int i=1;i<=n;i++)
    cin>>w[i];
    
    for(int i=1;i<=n;i++){//前i种物品 
        for(int j=wl;j>=0;j--){//容量为j 
            if(j>=w[i]) dp[j]=max(dp[j],dp[j-w[i]]+d[i]); 
        }
    }
    cout<<dp[wl]<<endl;
    }
    return 0;
}
View Code

 

一维数组 poj3624

#include <iostream>
#include <cstring>
using namespace std;

const int maxn=4000;

int dp[13000];
int d;
int w;
int n,wl;

int main(){
    memset(dp,0,sizeof(dp));
    cin>>n>>wl;
    for(int i=1;i<=n;i++){//前i种物品 
    cin>>w>>d;
        for(int j=wl;j>=1;j--){//容量为j 
            if(j>=w) dp[j]=max(dp[j],dp[j-w]+d); 
        }
    }
    cout<<dp[wl]<<endl;
    return 0;
}
View Code

 

 

posted @ 2018-04-11 16:57  柳暗花明_liu  阅读(149)  评论(0编辑  收藏  举报