一个很不错的二分答案题目
需要特判一下 a[i]>mid fales;
还有后面的逆序输出需要注意。
//#pragma GCC optimize(2)
//#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
#define inf 0x7fffffff
//#define ll long long
#define int long long
//#define double long double
#define re int
#define void inline void
#define eps 1e-8
//#define mod 1e9+7
#define ls(p) p<<1
#define rs(p) p<<1|1
#define pi acos(-1.0)
#define pb push_back
#define P pair < int , int >
#define mk make_pair
using namespace std;
const int mod=998244353;
const int M=5e6;
const int maxn=4;
const int len=4;
const int N=2e5+5;//?????????? 4e8
int a[505];
int m,k;
int ans[505];
bool check(int mid)
{
int sz=0;
int group=0;
memset(ans,0,sizeof(ans));
for(int i=1;i<=m;i++)
{
if(a[i]>mid)return false;
if(sz+a[i]>mid)
{
sz=a[i];
group++;
ans[group]++;
}
else {
sz+=a[i];
ans[group]++;
}
}
if(group<k) return true;
return false;
}
int ans1[505],ans2[505];
void solve()
{
cin>>m>>k;
for(int i=1;i<=m;i++)cin>>a[i];
int l=0,r=1e9;
while(l<r)
{
int mid=(l+r)/2;
if(check(mid)) r=mid;
else l=mid+1;
}
int num=k;ans1[1]=1,ans2[k]=m;
for(int i=m,cnt=0;i>=1;--i) {
if(cnt+a[i]>l) {
ans1[num]=i+1;
ans2[--num]=i;
cnt=a[i];
}else cnt+=a[i];
}
for(int i=1;i<=k;++i) printf("%lld %lld\n",ans1[i],ans2[i]);
}
signed main()
{
int T=1;
for(int index=1;index<=T;index++)
{
solve();
}
return 0;
}
/*
*/