1 条题解

  • 0
    @ 2022-11-22 15:05:41
    #include <bits/stdc++.h>
    using namespace std;
    int n, m;
    int a[112345];
    //看看如果每段和都不超过 maxSum,最少分成的段数是否不超过 M。
    bool check(int maxSum)
    {
        int cnt = 1;
        int nowSum = 0;
        for (int i = 1; i <= n; i++)
        {
            if (a[i] > maxSum)
                return false;
            if (nowSum + a[i] <= maxSum)
                nowSum += a[i];
            else
            {
                cnt++;
                nowSum = a[i];
            }
        }
        return cnt <= m;
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin >> n >> m;
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        int l = 0;
        int r = 1000000000;
        int ans = -1;
        while (l <= r)
        {
            int mid = (l + r) / 2;
            if (check(mid))
            {
                ans = mid;
                r = mid - 1; //调整上限,看能不能更小
            }
            else
                l = mid + 1;
        }
        cout << ans << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    655
    时间
    1000ms
    内存
    512MiB
    难度
    5
    标签
    递交数
    84
    已通过
    32
    上传者