内存检查

题目链接: http://exercise.acmcoder.com/online/online_judge_ques?ques_id=3362&konwledgeId=40

解题思路: 正向求解很难。考虑如果给定一个长度,判断这个长度x是否符合要求是很简单的,只需要贪心对于每个1划分一个长度x的段就可以了。

                   所以可以考虑二分答案。需要注意的一个情况是所有的地方都是0。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long LL;
 5 const int MAXN=100005;
 6 const LL MOD7 = 1e9+7;
 7 char s[MAXN];
 8 int n;
 9 int m;
10 
11 bool check(int x)
12 {
13     int i=0;
14     int cnt=0;
15     while (i<n)
16     {
17         while (i<n && s[i]=='0') ++i;
18         if (i>=n) break;
19         ++cnt;
20         i+=x;
21     }
22     return cnt<=m;
23 }
24 
25 void biSearch()
26 {
27     int l=1;
28     int r=n;
29     int mid;
30     while(l<=r)
31     {
32         mid=(l+r)/2;
33         // printf("l=%d r=%d mid=%d check(%d)=%d\n",l,r,mid, mid, check(mid));
34         if (check(mid)) r=mid-1;
35         else l=mid+1;
36     }
37     printf("%d\n", r+1);
38 }
39 
40 int main()
41 {
42 #ifndef ONLINE_JUDGE
43     freopen("test.txt","r",stdin);
44 #endif // ONLINE_JUDGE
45     int Case;
46     scanf("%d",&Case);
47     for (int t=1;t<=Case;++t)
48     {
49         scanf("%d%d",&n,&m);
50         scanf("%s",s);
51         printf("Case %d: ", t);
52         int flags=0;
53         for (int i=0;s[i];++i)
54         {
55             if (s[i]=='1')
56             {
57                 flags=1;
58                 break;
59             }
60         }
61         if (!flags) printf("0\n");
62         else biSearch();
63     }
64     return 0;
65 }

猜你喜欢

转载自www.cnblogs.com/djingjing/p/8993234.html