跳到正文

题解

题解 P1182 【数列分段Section II】

wowowo!约 2 分钟
原文

这是 2026年2月3日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年2月3日
更新
2026年2月3日
篇幅
约 2 分钟
题目
P1182

版本

  1. v2当前
  2. v1

一道二分答案,比较基础,思路就是先按照套路找中间点,从1~n循环,total(我用来累加的)加上a[i]<=mid的话就加进去否则就分组数++。

C++
#include<cstdio>
using namespace std;
int tmp,total,tot,ans,mid,l,r,minn=0,a[100001],n,m; 
bool pd(int t)
{
    tmp=0;
    total=0;
    for (int i=1;i<=n;i++)
    {
        if (total+a[i]<=t)
          total+=a[i];
        else
        {
          tmp++;
          total=a[i];
        }
    }
    if (tmp+1<=m)//这里需要特别注意,tmp需要加1
      return true;
    return false;
}
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++)
    {
      scanf("%d",&a[i]);
      if (minn<a[i])
        minn=a[i];
      tot+=a[i];
    }
    l=minn;r=tot;
    while (l<=r)
    {
        mid=(l+r)/2;
        if (pd(mid))
          r=(ans=mid)-1;
        else
          l=mid+1;
    }
    printf("%d",ans);
}