题解:蛋糕工厂产能规划

79 阅读1分钟

题意

工厂日产 m * w,其中m,w分别表示机器和工人的数量 每天的产能可以买机器或者雇佣工人,以提高日产能。给你一个生产指标,问最快多少天可以完成?

思路

  1. 是先提高产能?还是直接开始生产?
  2. 如果要提高产能,提高到什么程度?
  • 以上这些都是未知
  • 但是 假设我们事先知道给我们确定的天数,我们就可以很快地判断出给定的天数能否完成生产。这里就想到了二分答案,具体细节看代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int solution(int m, int w, int p, int n)
{
    auto check = [&](int k) -> bool
    {
        int cake = m * w;
        // 不扩大生产规模就能完成  返回true
        if (cake * k >= n)
            return true;
        int cnt = 1;
        while (cake < n)
        {
            // 可以增加生产资料的数量
            int add = cake / p;
            // 均分
            if (m < w)
                swap(n_m, n_w);
            int diff = m - w;
            if (add <= diff)
                w += add;
            else
            {
                int total = add + n_m + n_w;
                w = total / 2;
                m = total - w;
            }
            // 蛋糕没用完
            cake %= p;
            // 不再扩大生产规模  如果可以在后续时间内完成生产 返回true
            if (cake + (m * w * (k - cnt)) >= n)
                return true;
            // 又过了一天...
            cnt++;
            cake += m * w;
        }
        return cnt <= k;
    };
    // 左开右开
    int l = 0, r = n / (m * w) + 2;
    while (l + 1 < r)
    {
        int mid = (l + r) >> 1;
        if (check(mid))
            r = mid;
        else
            l = mid;
    }
    return r;
}
int main()
{
    //  You can add more test cases here
    cout << solution(3, 1, 2, 12) << endl;
    cout << solution(10, 5, 30, 500) << endl;
    cout << solution(3, 5, 30, 320) << endl;
    std::cout << (solution(3, 1, 2, 12) == 3) << std::endl;
    std::cout << (solution(10, 5, 30, 500) == 8) << std::endl;
    std::cout << (solution(3, 5, 30, 320) == 14) << std::endl;
    return 0;
}