22分求助
查看原帖
22分求助
822439
lhz2022楼主2023/1/15 21:11

22分求助

#include<iostream>
#include<string>

using namespace std;

const int N=514;
int m,k,sum=0;
int a[N];
bool c(int x){
    int cnt=1;
    int rest=x;
    for(int i=1;i<=m;i++){
        if(a[i]>x){
            return 0;
        }
        if(rest>=a[i]){
            rest-=a[i];
        }
        else{
            cnt++;
            rest=x-a[i];
        }
    }
    return cnt<=k;
}
void s(int i,int x){
    if(i==0) return;
    int sum=0;
    int j;
    for(j=i;j>=1&&sum+a[j]<=x;j--){
        sum+=a[j];
    }
    s(j,x);
    cout<<j+1<<" "<<i<<endl;
}
int main(){
    cin>>m>>k;
    for(int i=0;i<m;i++){
        cin>>a[i];
        sum+=a[i];
    }
    int l=1,r=sum+1,mid;
    while(l<r){
        mid=((l+r)>>1);
        if(c(mid)) r=mid;
        else l=mid+1;
    }
    s(m,l);
    return 0;
}
2023/1/15 21:11
加载中...