CodeForces - 803D. Magazine Ad【二分】

D. Magazine Ad
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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

Output minimal width of the ad.

Examples
input
Copy
4
garage for sa-le
output
Copy
7
input
Copy
4
Edu-ca-tion-al Ro-unds are so fun
output
Copy
10
Note

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

传送门:http://codeforces.com/problemset/problem/803/D

题意:输入一个k和一个字符串s,最多可以把s分成k行,分割位置只能是-或者空格,求分割后最长一行长度的最小值。

思路:二分答案。用st存放两个可分割点间差距最大的距离(首尾别忘了处理),把[st,s.size()]作为初始二分区间,如果mid切出来的行数大于题目给出的行数k,那么说明每行放的太少了,所以行数会超出,所以需要让左边界等于mid+1.反之也是这样思考。

代码:

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<set>
#include<queue>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxv=1e6+6;

string s;
int k,co,a[maxv],st;

int cnt(int x)
{
	int c=1,sum=0;
	for(int i=0;i<co;i++)
	{
		sum+=a[i];
		if(sum>x)
		{
			c++;
			sum=a[i];
		}
	}
	return c;
}

int main()
{
	cin>>k;
	getchar();
	getline(cin,s);
	int pos=-1;
	int ll=s.size(),i;
	for(i=0;i<ll;i++)
	{
		if(s[i]=='-'||s[i]==' ')
		{
			st=max(st,i-pos);
			a[co++]=i-pos;
			pos=i;
		}
	}
	a[co++]=i-pos-1;
	st=max(st,i-pos-1);
	int l=st,r=ll;
	while(l<=r)
	{
		int mid=(l+r)/2;
		if(cnt(mid)<=k)
			r=mid-1;
		else
			l=mid+1;
	}
	printf("%d\n",l);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39396954/article/details/80961617