背包问题

完全背包

#include<bits/stdc++.h>
using namespace std;
const int N=200009;
int n,c,i,w,v,f[N];
int main(){
    cin>>c>>n;
    for(i=1;i<=n;i++){
        cin>>w>>v;
        for(int j=c;j>=w;j--)
            f[j]=max(f[j],f[j-w]+v);
    }
    cout<<f[c]<<endl;
    return 0;
}

01背包

#include<bits/stdc++.h>
using namespace std;
const int N=200009;
int n,c,i,w,v,f[N];
int main(){
    cin>>c>>n;
    for(i=1;i<=n;i++){
        cin>>w>>v;
        for(int j=w;j<=c;j++)
            f[j]=max(f[j],f[j-w]+v);
    }
    cout<<f[c]<<endl;
    return 0;
}
posted @ 2019-11-14 11:37  wased  阅读(67)  评论(0)    收藏  举报