Quantcast
Viewing all articles
Browse latest Browse all 39796

0 1 kanpsack

hey why is that my code gives wrong answer ...:(

//knapsack problem

include<cstdio>

include<iostream>

int main() { int t,a,j,i,k,l,W;

printf("enter the amount of the items\n");
scanf("%d",&t);
int w[t+1],v[t+1];
int b[t+1][t+1];
printf("enter the total weight\n");
scanf("%d",&W);

for(i=1;i<=t;i++)
scanf("%d%d",&w[i],&v[i]);

for(i=0;i<=t;i++)
{

    for(j=0;j<=W;j++)
    {


        if((i==0)||(j==0))
        {b[i][j]=0;}
        else if(w[i]<=j)
        {

            if(b[i-1][j]>b[i-1][j-w[i]]+v[i])
           { b[i][j]=b[i-1][j];}
            else
            {b[i][j]=b[i-1][j-w[i]]+v[i];}
        }
    else if(w[i]>j)
  {b[i][j]=b[i-1][j];}

    }
}
printf("the max value is %d\n",b[t][W]);
system("pause");

}


Viewing all articles
Browse latest Browse all 39796

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>