Codeforces 803D Magazine Ad 题解

题意
给一些词(可能带连接符),要求排版最多不超过k行,问每行最少要多少字符
思路
二分答案,判断是否可行是在不超过一行的字符限制的时候尽量放,放不下就换行,看最后行数是否不超过k,如果出现一行开始的一个词就超过了长度限制,就直接判断为不可行
代码
#include <cstdio>
#include <iostream>
using namespace std;
int cnt[1000001];
int e,k;
bool judge(int x)
{
    int c=0,temp=0,t=0;
    for(int i=0;i<e;i++)
    {
        if(t==0)
        {
            t++;
            temp=cnt[i];
            if(temp>x)
                return false;
        }
        else
        {
            if(temp+cnt[i]<=x)
                temp+=cnt[i];
            else
            {
                temp=0;
                c++;
                t=0;
                i--;
            }
        }
    }
    if(c+1>k)
        return false;
    return true;
}
int binary_search(int l,int r)
{
    //printf("%d %d\n",l,r);
    int mid=(l+r)/2;
    if(l==r)
        return l;
    else if(r-l==1)
    {
        if(judge(l))
            return l;
        else return r;
    }
    else
    {
        if(judge(mid))
            return binary_search(l,mid);
        else return binary_search(mid+1,r);
    }
}
int main()
{
    int t;
    string s;
    cin>>k;
    e=0;
    while(cin>>s)
    {
        t=0;
        for(int i=0;i<s.length();i++)
            if(s[i]=='-')
            {
                cnt[e]=t+1;
                e++;
                t=0;
            }
            else t++;
        cnt[e]=t+1;
        e++;
    }
    cnt[e-1]--;
    printf("%d\n",binary_search(1,1000000));
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值