要在H小时内检查完所有的产品,求K的最小值
题意
有N堆产品,每堆产品的数量为counts[i],1<=N<=10^4, 0<=i<N, 1=<counts[i]<=10^9;
现给定H个小时来检测所有产品的质量,每小时可以检查K个产品,N<=H<=10^9;
全部检查完一堆产品后才能检查另一堆;
如果一堆产品的总数量或者剩余数量小于K,那么检查这些产品需要的时间将会不足一小时,但是仍然记作一小时。
要在H小时内检查完所有的产品,求K的最小值。
输入:
N H
counts[0] counts[1] … counts[N-1]
输出:
K
示例
输入:
4 8
3 6 7 11
输出:
4
C++实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int findMinK(vector<int>& counts, int h)
{
if (counts.empty())
throw "Invalid arg : counts";
if (h < counts.size())
throw "Invalid arg : h";
sort(counts.begin(), counts.end());
int minK = -1;
for (unsigned i = counts[0]; i <= counts[counts.size() - 1]; ++i)
{
int hours = h;
int k = i;
for (unsigned j = 0; j < counts.size(); ++j)
{
hours -= (int)ceil((double)counts[j] / (double)k);
if (hours < 0)
break;
}
if (0 == hours)
{
minK = k;
break;
}
}
return minK;
}
void test()
{
int n, h;
cin >> n;
if (n < 1 || n > pow(10, 4))
throw "Invalid input : n";
cin >> h;
if (h < n || h > pow(10, 9))
throw "Invalid input : h";
vector<int> counts(n, 0);
for (unsigned i = 0; i < counts.size(); ++i)
{
cin >> counts[i];
if (counts[i] < 1 || counts[i] > pow(10, 9))
throw "Invalid input : item of counts";
}
cout << findMinK(counts, h) << endl;
}
int main()
{
test();
return 0;
}
就这样用暴力法求解了 。