0-1 Knapsack algorithm

前端 未结 6 2088
花落未央
花落未央 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:12

    This can be solved using Dynamic Programming. Below code can help you solve the 0/1 Knapsack problem using Dynamic Programming.

        internal class knapsackProblem
        {
        private int[] weight;
        private int[] profit;
        private int capacity;
        private int itemCount;
        private int[,] data;
    
        internal void GetMaxProfit()
        {
            ItemDetails();
    
            data = new int[itemCount, capacity + 1];
    
            for (int i = 1; i < itemCount; i++)
            {
                for (int j = 1; j < capacity + 1; j++)
                {
                    int q = j - weight[i] >= 0 ? data[i - 1, j - weight[i]] + profit[i] : 0;
    
                    if (data[i - 1, j] > q)
                    {
                        data[i, j] = data[i - 1, j];
                    }
                    else
                    {
                        data[i, j] = q;
                    }
                }
            }
    
            Console.WriteLine($"\nMax profit can be made : {data[itemCount-1, capacity]}");
            IncludedItems();
        }
    
        private void ItemDetails()
        {
            Console.Write("\nEnter the count of items to be inserted : ");
            itemCount = Convert.ToInt32(Console.ReadLine()) + 1;
            Console.WriteLine();
    
            weight = new int[itemCount];
            profit = new int[itemCount];
    
            for (int i = 1; i < itemCount; i++)
            {
                Console.Write($"Enter weight of item {i} : ");
                weight[i] = Convert.ToInt32(Console.ReadLine());
    
                Console.Write($"Enter the profit on the item {i} : ");
                profit[i] = Convert.ToInt32(Console.ReadLine());
    
                Console.WriteLine();
            }
    
            Console.Write("\nEnter the capacity of the knapsack : ");
            capacity = Convert.ToInt32(Console.ReadLine());
        }
    
        private void IncludedItems()
        {
            int i = itemCount - 1;
            int j = capacity;
    
            while(i > 0)
            {
                if(data[i, j] == data[i - 1, j])
                {
                    Console.WriteLine($"Item {i} : Not included");
                    i--;
                }
                else
                {
                    Console.WriteLine($"Item {i} : Included");
                    j = j - weight[i];
                    i--;
                }
            }
        }
    }
    

提交回复
热议问题