codeforces 803D Magazine Ad(二分+贪心)

Magazine Ad

题目链接:http://codeforces.com/contest/803/problem/D

              ——每天在线,欢迎留言谈论。

题目大意:

给你一个数字k,和一行字符 例:

4
garage for sa-le

其中这行字符串能够在 ' '与'-'的后面分割。例如分割为:(点代表空格)

garage.

for.

sa-

le

求:分割成不超过k行的情况下的最小宽度。(宽度:最大行的字符个数)

思路:

答案一定在 1所给字符串长度 之间

①通过二分宽度 来逼近最小宽度。

判断每行宽度<=m 并在k行内完成分割时

②贪心地把每行填的不能再填为止。

AC代码:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 using namespace std;
 5 string ss;
 6 int n;
 7 bool isok(int k)//是否能在k宽度下满足条件
 8 {
 9     int a(1),b1(0),b2(0);//a行数  b 宽度
10     for(int i=0;i<ss.size();i++)
11     {
12         if(i!=ss.size()-1)
13             b2++;
14         if(ss[i]==' '||ss[i]=='-')
15         {
16             if(b2>k)
17                 return false;
18             if(b1+b2<=k)
19             {
20                 b1=b1+b2;b2=0;
21 
22             }
23             else
24             {
25                 b1=b2;b2=0;a++;
26                 if(a>n)
27                     return false;
28             }
29         }
30     }
31     if(a>n)
32         return false;
33     return true;
34 }
35 int main()
36 {
37     cin>>n;getchar();
38     getline(cin,ss);
39     ss+=' ';
40     int i=0,j=ss.size(),k;//[i,j)
41     while(i<j)
42     {
43         k=(i+j)/2;
44         if(isok(k))
45             j=k;
46         else
47             i=k+1;
48     }
49     if(i==ss.size()&&isok(i))
50     {cout<<i<<endl;return 0;}
51     cout<<i<<endl;return 0;
52 }

2017-05-06 22:03:30

posted @ 2017-05-06 22:05  Wei_Xiong  阅读(318)  评论(0编辑  收藏  举报
WX:我是来搞笑的