📌  相关文章
📜  放置N个项目所需的最小垃圾箱数量(使用最佳拟合算法)

📅  最后修改于: 2021-04-17 15:57:09             🧑  作者: Mango

给定一个由N个项目的权重和代表每个仓位容量的正整数C组成的数组weight [] ,任务是找到所需的最小仓位数,以便将所有项目分配给其中一个仓位。

例子:

方法:可以使用最佳拟合算法解决给定的问题。想法是将下一个项目放在剩余最小最小空间的垃圾箱中。请按照以下步骤解决问题:

  • 初始化一个变量,比如说count0 ,该变量存储所需的最小bin数量。
  • 以降序对给定的数组weight []进行排序。
  • 初始化一个多集,例如M,以存储当前在已占用的垃圾箱中剩余的空白空间。
  • 遍历数组weight [] ,并对每个元素执行以下步骤:
    • 如果在M中存在最小为arr [i]的最小空白空间,则从M删除该空间并将剩余的可用空间插入M。
    • 否则,将计数增加1并将新容器的空白插入M。
  • 完成上述步骤后,将count的值打印为所需的最小纸槽数。

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Function to find the minimum number
// of bins required to fill all items
void bestFit(int arr[], int n, int W)
{
    // Stores the required number
    // of bins
    int count = 0;
  
    // Sort the array in decreasing order
    sort(arr, arr + n, greater());
  
    // Stores the empty spaces in
    // existing bins
    multiset M;
  
    // Traverse the given array
    for (int i = 0; i < n; i++) {
  
        // Check if exact space is
        // present in the set M
        auto x = M.find(arr[i]);
  
        // Store the position of the
        // upperbound of arr[i] in M
        auto y = M.upper_bound(arr[i]);
  
        // If arr[i] is present, then
        // use this space and erase it
        // from the map M
        if (x != M.end()) {
            M.erase(x);
        }
  
        // If upper bound of arr[i] is
        // present, use this space and
        // insert the left space
        else if (y != M.end()) {
            M.insert(*y - arr[i]);
            M.erase(y);
        }
  
        // Otherwise, increment the count
        // of bins and insert the
        // empty space in M
        else {
            count++;
            M.insert(W - arr[i]);
        }
    }
  
    // Print the result
    cout << count;
}
  
// Driver Code
int main()
{
    int items[] = { 4, 8, 1, 4, 2, 1 };
    int W = 10;
    int N = sizeof(items) / sizeof(items[0]);
  
    // Function Call
    bestFit(items, N, W);
  
    return 0;
}


输出:
2

时间复杂度: O(N * log(N))
辅助空间: O(N)