题解:P17795 [入门赛 #53] 新能源之旅

· · 题解

二分答案,然后按题意模拟即可,如果可充电电池还够,就用,不然就换一个全新的备用电池。如果新的也不够,或者没有新的了,就说明不可行。 :::success[Code]

#include<bits/stdc++.h>
#define int long long
#define endl '\n'
#define fi first
#define se second
using namespace std;
const int maxn=2e5+10;
int n,K;
int a[maxn],b[maxn];
bool check(int x){
    bool fl=0;
    int rest=x,mx=K;
    for(int i=1;i<=n;i++){
        if(!fl){
            if(rest>=a[i]) rest-=a[i],rest+=b[i],rest=min(rest,x);
            else{
                rest=x,mx--;
                if(rest<a[i]||mx<0) return 0;
                rest-=a[i]; fl=1;
            }
        }
        else{
            if(rest>=a[i]) rest-=a[i];
            else{
                rest=x,mx--;
                if(rest<a[i]||mx<0) return 0;
                rest-=a[i];
            }
        }
    }
    return 1;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    cin>>n>>K;
    for(int i=1;i<=n;i++) cin>>a[i]>>b[i];
    int l=0,r=1e18,ans=0;
    while(l<=r){
        int mid=(l+r)>>1;
        if(check(mid)) r=mid-1,ans=mid;
        else l=mid+1;
    }
    cout<<ans;
    return 0;
}

:::