The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen.
It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word.
When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.
The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.
You should write a program that will find minimal width of the ad.
The first line contains number k (1 ≤ k ≤ 105).
The second line contains the text of the ad — non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters.
Output minimal width of the ad.
4 garage for sa-le
7
4 Edu-ca-tion-al Ro-unds are so fun
10
Here all spaces are replaced with dots.
In the first example one of possible results after all word wraps looks like this:
garage. for. sa- le
The second example:
Edu-ca- tion-al. Ro-unds. are.so.fun
一看到这种长篇大论就头疼。。。
题意:给出一个数字k,和字符串,字符串中有空格以及分隔符-,字符串可以在遇到空格或分隔符时选择换行,空格和分隔符保留在此行末尾。要求最多分出n行,求分完后的宽度最小。宽度是指分割后的几个字符串中最长字符串的长度。 保证首尾没有分隔符和空格。
思路:事先记录分隔符与空格分开的每一断字符的长度。 先将字符串平均分成k段,分割后的长度为l。l即为可能的最小长度。原字符串长度r可能为最大长度。然后在l和r之间进行二分,搜索符合条件的最小值。 具体如何判断,看代码吧!
#include<stdio.h>
#include<vector>
#include<iostream>
using namespace std;
int k;
vector<int> v;
string s;
bool check(int x)
{
int cnt=0;
int len=0;
int i;
for(i=0;i<v.size();i++)
{
if(v[i]>x)
return 0;
if(v[i]+len>x)
{
cnt++;
len=v[i];
}
else if(v[i]+len==x)
{
cnt++;
len=0;
}
else if(v[i]+len<x)
{
len+=v[i];
}
}
if(len)
cnt++;
return cnt<=k;
}
void slove()
{
int r=s.size(),l=r/k;
int mid=0;
while(r-l>0)
{
mid=(l+r)/2;
if(check(mid))
r=mid;
else
l=mid+1;
}
printf("%d\n",l);
}
int main()
{
while(scanf("%d",&k)!=EOF)
{
v.clear();
getchar();
getline(cin,s);
int i,j;
for(i=0,j=0;i<s.size();i++)
{
if(s[i]==' '||s[i]=='-')
{
v.push_back(j+1);
j=0;
}
else
j++;
}
v.push_back(j);
slove();
}
}