Codeforces 551C GukiZ hates Boxes(二分)

Problem C. GukiZ hates Boxes

Solution:

  假设最后一个非零的位置为K,所有位置上的和为S

      那么答案的范围在[K+1,K+S].

      二分这个答案ans,然后对每个人尽量在ans时间内搬最多的砖.可以得出至少需要多少个人才能搬完.这个可以在O(n)的时间内利用贪心得到

      只要判断需要的人数是否小于等于实际的人数就好了

      时间复杂度O(nlogS)

#include <bits/stdc++.h>
using namespace std;

const int N = 123456;
int a[N];
int n, m, t;
long long s;

inline bool check( long long x )
{
    int k = m;
    long long s = 0;
    for( int i = 1; i <= t; ++i ) {
        s += a[i];
        while( s + i >= x ) {
            s -= x - i;
            if( --k < 0 ) return 0;
        }
    }
    if(k==0) return s<=0;
    return 1;
}

int main()
{
    ios::sync_with_stdio( 0 );
    cin >> n >> m;
    for( int i = 1; i <= n; ++i ) {
        cin >> a[i];
        s += a[i];
        if( a[i] != 0 ) t = i;
    }
    long long  l = t + 1, r = s + t,ans=-1;
    while( l <= r ) {
        long long mid = ( l + r ) >> 1;
        if( check( mid ) ) r = mid - 1,ans=mid;
        else l = mid + 1;
    }
    cout << r + 1 << endl;

}
View Code
原文地址:https://www.cnblogs.com/keam37/p/4576911.html