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

📅  最后修改于: 2021-09-06 06:38:04             🧑  作者: Mango

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

例子:

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

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

下面是上述方法的实现:

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)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live