C++ 程式來實現裝箱演算法


裝箱問題是一種特殊的裁剪問題。在裝箱問題中,必須將不同體積的物體裝入數量有限的容器或箱子中,每個容器或箱子的體積為 V,並且以最少化使用的容器或箱子的數量的方式裝入。在計算複雜性理論中,這是一個組合 NP 難問題。

當容器或箱子的數量限制為 1,並且每個物品都以體積和價值來表徵時,最大化可以裝入容器或箱子中的物品價值的問題被稱為揹包問題。

演算法

Begin
   Binpacking(pointer, size, no of sets)
   Declare bincount, m, i
   Initialize bincount = 1, m=size
   For i = 0 to number of sets
   if (m - *(a + i) > 0) do
      m = m - *(a + i)
      Continue
   Else
      Increase bincount
      m = size;
      Decrement i
      Print number of bins required
End

示例程式碼

#include<iostream>
using namespace std;
void binPacking(int *a, int size, int n) {
   int binCount = 1;
   int m = size;
   for (int i = 0; i < n; i++) {
      if (m - *(a + i) > 0) {
         m -= *(a + i);
         continue;
      } else {
         binCount++;
         m = size;
         i--;
      }
   }
   cout << "Number of bins required: " << binCount;
}
int main(int argc, char **argv) {
   cout << "Enter the number of items in Set: ";
   int n;
   cin >> n;
   cout << "Enter " << n << " items:";
   int a[n];
   for (int i = 0; i < n; i++)
      cin >> a[i];
   cout << "Enter the bin size: ";
   int size;
   cin >> size;
   binPacking(a, size, n);
}

輸出

Enter the number of items in Set: 3
Enter 3 items:4
6
7
Enter the bin size: 26
Number of bins required: 1

更新日期:2019-07-30

1K+ 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告