memory check

Topic link: http://exercise.acmcoder.com/online/online_judge_ques?ques_id=3362&konwledgeId=40

Problem-solving ideas: It is difficult to solve in the forward direction. Considering that if a length is given, it is very simple to judge whether the length x meets the requirements, and you only need to greedily divide a segment of length x for each 1.

                   So a binary answer can be considered. One case to be aware of is 0 everywhere.

 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 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325299385&siteId=291194637