csu 1909: Perfect Chocolate

1909: Perfect Chocolate

        Time Limit: 3 Sec     Memory Limit: 128 Mb     Submitted: 90     Solved: 42    


Description

There is a chocolate, is composed of black and white small pieces. Xiao Ming is very fond of this chocolate, and the absolute difference between the number of black pieces and the number of white pieces is not more than 1, he think this chocolate is perfect.
Now Xiao Ming has one this chocolate in his hand, maybe it is not perfect.He will cut it into small blocks, making these small blocks are all perfect, he wanted to know how many times he will cut at least.

Input

There are multiple test cases.
For each test case.There is only one string composed of ‘0’ and ‘1’.’0’ is for the white piece while ‘1’ for the black piece.The length of the string for each case is not more than 100000.

Output

For each test case, you output one line “Case #%d:%d”

Sample Input

10011100010000
1

Sample Output

Case #1:3
Case #2:0

Hint

Source

2017年湖南多校对抗赛第8场

Author

HNU

 

题解:这个题目也是一道比较简单的题目   

第一种方法:每一次选从前面断点开始的最长的满足要求的那个位置断开,成为新的断点  一直到最后面为止

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <cstring>
 5 #include <math.h>
 6 
 7 using namespace std;
 8 char x[100005];
 9 int vis[100005];
10 int sum[100005],sumb,sumw;;
11 int main()
12 {
13     int cas=0;
14     while(cin>>x)
15     {
16         sumb=sumw=0;
17         int len = strlen(x);
18         for(int i=0; i<len; ++i)
19         {
20             if(x[i]=='1')sumb++,vis[i]=1;
21             else sumw++,vis[i]=-1;
22         }
23         int ans=0;
24         cout<<"Case #"<<++cas<<":";
25         int now=0;
26         while(now<len)
27         {
28             int sum=0,pos=now;
29             for(int i=now; i<len; i++)
30             {
31                 sum+=vis[i];
32                 if(sum==1||sum==-1||!sum) pos=i;
33             }
34             ans++;
35             now=pos+1;
36         }
37         cout<<ans-1<<endl;
38     }
39 
40     return 0;
41 }

第二种:我以每一块设置一个权值    1多一个权值为1      0多一个为-1          相同为0

我们可以发现  我们分成的每一块  除了不需要分的整个一块1和0的数目相同

其他的情况  我们分出来的每一块的权值一定相同    

因为       1  0  可以合成1        1 -1可以合成0       0和1   0和-1  

如果相邻的俩块权值是不相同  就可以像上面一样合成一块

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <fstream>
 4 #include <string>
 5 #include <cstring>
 6 using namespace std;
 7 const int N = 1e5 + 10;
 8 string str;
 9 int GetAns(){
10     int n = str.length();
11     int sum = 0;
12     for (int i = 0; i < n; i++){
13         if (str[i] == '0') sum++;
14         else               sum--;
15     }
16     if (sum < 0) sum = -sum;
17     if (sum > 0) sum--;
18     return sum;
19 }
20 int main(){
21     int ca = 0;
22     while (cin >> str){
23         ca++;
24         int ans = GetAns();
25         cout << "Case #" << ca << ":" << ans << endl;
26     }
27     return 0;
28 }

 

 

posted @ 2017-09-01 08:13  红雨520  阅读(122)  评论(0编辑  收藏  举报