0/1 knapsack problem of backtracking

Title Description

Known load of a backpack and a M n of items, item number from 0 to n-1. By weight of the i-th items of wi, if the i-th item into the backpack will benefit pi, where, wi> 0, pi> 0,0 <= i <n. The so-called 0/1 knapsack problem is the inability to split the article, only the whole into a bag or case is not loaded, loading seeking a preferred embodiment such that the maximum total revenue.

Note:

1, please solve this problem by backtracking (to use bounding function prune).

2, all the data have been tested by pi / wi descending order.

 

Entry

Line 1 has two positive integers n (n <= 50) and M, expressed n items, the backpack load of M (m <= 100). Then enter the weight of the item number n, the n value of the final input return objects.

 

Export

The total revenue of the optimal loading plan 

c ++ code is as follows:

#include<iostream>
using namespace std;
int n;
int m;
int x[100];
int y[100];
int fp=0;
int Bound( int k, int cp, int cw, int *w, int *p)
{
     int b=cp,c=cw;
     for ( int i=k+1;i<n;i++)
     {
         c+=w[i];
         if (c<m)
             b+=p[i];
         else return (b+(1-(c-m)/w[i])*p[i]);
     }
     return b;
}
void BK( int k, int cp, int cw, int &fp, int *x, int *y, int *w, int *p)
{
     int j;
     int bp;
     if (cw+w[k]<=m)
     {
         y[k]=1;
         if (k<n-1) BK(k+1,cp+p[k],cw+w[k],fp,x,y,w,p);
         if (cp+p[k]>fp&&k==n-1)
         {
             fp=cp+p[k];
             for (j=0;j<=k;j++)
                 x[j]=y[j];
         }
     }
     if (Bound(k,cp,cw,w,p)>=fp)
     {
         y[k]=0;
         if (k<n-1)
             BK(k+1,cp,cw,fp,x,y,w,p);
         if (cp>fp&&k==n-1)
         {
             fp=cp;
             for (j=0;j<=k;j++)
                 x[j]=y[j];
         }
     }
}
int BK( int *x, int *w, int *p)
{
     int y[100]={0};
     int fp;
     BK(0,0,0,fp,x,y,w,p);
     return fp;
}
int main()
{  
     int i;
     int w[100];
     int p[100];
     cin>>n>>m;
     for (i=0;i<n;i++)
         cin>>w[i];
     for (i=0;i<n;i++)
         cin>>p[i];
     cout<<BK(x,w,p);
     return 0;
}
result:

 

Guess you like

Origin www.cnblogs.com/RiverChen/p/10963156.html
Recommended