Codeforces 803D Magazine Ad 题解

来源:互联网 发布:sql查询分析器解析 编辑:程序博客网 时间:2024/05/29 02:28

题意

给一些词(可能带连接符),要求排版最多不超过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
原创粉丝点击