[Gym-102346M] 二分答案

https://vjudge.net/problem/Gym-102346M

一般来说, 若题目要求输出一个确定的数( 比如最小天数,最大个数之类 ),用二分来枚举答案试试。

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

const int maxn = 1e5+500;
int a[maxn];
int n,t,c;

int check(long long tim){
    int cnt=1;
    long long now=0;
    long long tot = tim*c;
    for(int i=1; i<=n; i++){
        if(tot < a[i]) return t+1;
        if(now + a[i] <= tot ){
            now += a[i];
        }
        else{
            now = a[i];
            cnt++;
        }
    }
    if( now > tot) return t+1;
    return cnt;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>t>>c;
    long long sum=0;
    for(int i=1; i<=n; i++){
        cin>>a[i];
        sum += a[i];
    }
    long long l=1,r=sum;
    long long mid,ans=sum;
    while(l<=r){
        mid = (l+r)>>1;
        if( check(mid)>t ){
            l = mid+1;
        }
        else{
            ans = mid;    //这个很重要
            r = mid-1;
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/-Zzz-/p/11784882.html