D(1909)Perfect Chocolate

本文介绍了一个有趣的算法问题——如何将一块由黑白小块组成的巧克力分割成若干完美的小块,每块巧克力中小块的颜色数量相差不超过1。通过遍历字符串并计算累积和的方法,实现了最小切割次数的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




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

Author

HNU



题意:当黑色小块与白色小块的个数相差的绝对值不大于1,就是一块Perfect Chocolate,给出的巧克力可能不是Perfect的,问最少切几下可以让所有的巧克力都是Perfect

思路:白的为-1,黑的为1,将待分割的这块巧克力最大化,找到能到达的最大值pos,并将pos+1作为下一块巧克力的起点

#include<iostream>
#include<cmath>
#include<string>
using namespace std;
int c[100005],sumb,sumw;
int main(){
    string str;int cas=0;
    while(cin>>str){
        int len=str.length();
        sumb=sumw=0;
        for(int i=0;i<len;i++){
            if(str[i]=='1') sumb++,c[i]=1;
            else            sumw++,c[i]=-1;
        }
        int ans=0;
        cout<<"Case #"<<++cas<<":";
        if(abs(sumb-sumw)<=1) {cout<<ans<<endl;continue;}
        int now=0;
        while(now<len){
            int sum=0,pos=now;
            for(int i=now;i<len;i++){
                sum+=c[i];
                if(sum==1||sum==-1||!sum) pos=i;
            }
            ans++;
            now=pos+1;
        }
        cout<<ans-1<<endl;
    }
}

#include <cstdio>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
string str;
int GetAns(){
    int n = str.length();
    int sum = 0;
    for (int i = 0; i < n; i++){
        if (str[i] == '0') sum++;
        else               sum--;
    }
    if (sum < 0) sum = -sum;
    if (sum > 0) sum--;
    return sum;
}
int main(){
    int ca = 0;
    while (cin >> str){
        ca++;
        int ans = GetAns();
        cout << "Case #" << ca << ":" << ans << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值