Backpack problems, 0-1 backpack Problems

Source: Internet
Author: User

Backpack problems, 0-1 backpack Problems

# Include <cstdio> # include <iostream> using namespace std; # define MAX_N 100 # define MAX_W 1000int n, W; // Select part of int rec (int I, int j) {int res; if (I = n) res = 0; whose total weight is less than j from item I; // else if (j <w [I]) res = rec (I + 1, j ); // unable to select this item else res = max (rec (I + 1, j), rec (I + 1, j-w [I]) + v [I]); // select the largest return res in the case of selection or not;} void solve () {printf ("% d \ n", rec (0, w);} int main () {printf ("n W: \ n"); scanf ("% d", & n, & W ); for (int I = 0; I <n; I ++) {printf ("w [% d] v [% d]: \ n", I, I ); scanf ("% d", & w [I], & v [I]);} solve (); return 0 ;}

Optimization-memory-based search

#include <cstdio>#include <iostream>#include <memory.h>using namespace std;#define MAX_N 100#define MAX_W 1000int n,W;int w[MAX_N],v[MAX_N];int dp[MAX_N+1][MAX_W+1];int rec(int i,int j){    if(dp[i][j]>=0)        return dp[i][j];    int res;    if(i==n)        res=0;    else if(j<w[i])        res=rec(i+1,j);    else        res=max(rec(i+1,j),rec(i+1,j-w[i])+v[i]);    return dp[i][j]=res;}void solve(){    memset(dp,-1,sizeof(dp));    printf("%d\n",rec(0,W));}int main(){    printf("n W:\n");    scanf("%d %d",&n,&W);    for(int i=0;i<n;i++)    {        printf("w[%d] v[%d]:\n",i,i);        scanf("%d %d",&w[i],&v[i]);    }    solve();    return 0;}

Dual Loop

#include <cstdio>#include <iostream>using namespace std;#define MAX_N 100#define MAX_W 1000int n,W;int w[MAX_N],v[MAX_N];int dp[MAX_N+1][MAX_W+1];void solve(){    for(int i=n-1;i>=0;i--)    {        for(int j=0;j<=W;j++)        {            if(j<w[i])                dp[i][j]=dp[i+1][j];            else                dp[i][j]=max(dp[i+1][j],dp[i+1][j-w[i]]+v[i]);        }    }    printf("%d\n",dp[0][W]);}int main(){    printf("n W:\n");    scanf("%d %d",&n,&W);    for(int i=0;i<n;i++)    {        printf("w[%d] v[%d]:\n",i,i);        scanf("%d %d",&w[i],&v[i]);    }    solve();    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.