使用C ++交付的最小项目数。

问题陈述

给定一个大小数组,N代表存储桶,每个数组索引均包含项。给定K个游览,其中需要交付所有项目。一次旅行只能从一个桶中取物品。任务是告诉每个巡回演出需要运送的物品的最小数量,以便可以在K个巡回演出中运送所有物品。

如果有5个项目= {1、3、5、7、9}的存储桶和10个游览,那么我们可以每次游览交付3个项目通过一次交付3个项目,

  • 第一个铲斗尺寸为1,因此所需行程数= 1

  • 第二个铲斗尺寸为3,因此所需行程数= 1

  • 第三个铲斗尺寸为5,因此所需行程的数量= 2(每次行程3 + 2件物品)

  • 第4个存储桶大小为7,因此所需游览次数= 3(每次游览3 + 3 + 1项目)

  • 第五个存储桶大小为9,因此所需游览次数= 3(每个游览3 + 3 + 3个项目)

游览总数= 10

算法

1. find the minimum number of items to be distributed per delivery
2. iterate from 1 to the maximum value of items in a bucket and calculate the number of tours required for each bucket and find the total number of tours for complete delivery
3. The first such value with tours less than or equals K gives the required number

示例

#include <iostream>
#include <climits>
#include <cmath>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
int minItemsDeliveried(int *arr, int n, int k){
   int maxElement = INT_MIN;
   for (int i = 0; i < n; ++i) {
      maxElement = max(maxElement, arr[i]);
   }
   for (int i = 1; i < maxElement + 1; ++i) {
      int tours = 0;
      for (int j = 0; j < n; ++j) {
         if (arr[i] % i == 0) {
            tours += arr[j] / i;
         } else {
            tours += floor(arr[j] / i) + 1;
         }
      }
      if (tours <= k) {
         return i;
      }
   }
   return 1;
}
int main(){
   int arr[] = {1, 3, 5, 7, 9};
   int k = 10;
   cout << "Minimum items to be delivered = " <<
   minItemsDeliveried(arr, SIZE(arr), k) << endl;
   return 0;
}

输出结果

当您编译并执行上述程序时。它生成以下输出-

Minimum items to be delivered = 3