0-1 Knapsack algorithm

前端 未结 6 2095
花落未央
花落未央 2021-02-09 12:35

Is the following 0-1 Knapsack problem solvable:

  • \'float\' positive values and
  • \'float\' weights (can be positive or negative)
  • \'float\' capacity
6条回答
  •  攒了一身酷
    2021-02-09 13:08

    import java.util.*;
    class Main{
        static int max(inta,int b)
        {
          if(a>b)
            return a;
          else
            return b;
        }
        public static void main(String args[])
        {
          int n,i,cap,j,t=2,w;
          Scanner sc=new Scanner(System.in);
          System.out.println("Enter the number of values  ");
          n=sc.nextInt();
          int solution[]=new int[n];
          System.out.println("Enter the capacity of the knapsack :- ");
          cap=sc.nextInt();
          int v[]=new int[n+1];
          int wt[]=new int[n+1];
          System.out.println("Enter the values  ");
          for(i=1;i<=n;i++)
          {
            v[i]=sc.nextInt();
          }
          System.out.println("Enter the weights  ");
          for(i=1;i<=n;i++)
          {
            wt[i]=sc.nextInt();
          }
          int knapsack[][]=new int[n+2][cap+1];
          for(i=1;ij)
               {
                 knapsack[i][j]=knapsack[i-1][j];
               }
               else
               {
                  knapsack[i][j]=max(knapsack[i-1][j],v[i]+knapsack[i-1][j-wt[i]]);
               }
             }
        }
        //for displaying the knapsack
         for(i=0;i0;i--)
         {
           if(knapsack[i][j]!=knapsack[i-1][j])
            {
              j=w-wt[i];
              w=j; 
              solution[k]=1;
              System.out.println("k="+k);
              k--;
           }
           else
           {
             solution[k]=0;
             k--;
           }
        }
        System.out.println("Solution for given knapsack is :- ");
        for(i=0;i  "+knapsack[n][cap]);
      }
    }
    

提交回复
热议问题