Unification(模拟+栈)

时间限制: 1 Sec 内存限制: 128 MB
[提交] [状态]
题目描述
There are N cubes stacked vertically on a desk.
You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.
You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.
At most how many cubes can be removed?

Constraints
·1≤N≤10^5
·|S|=N
·Each character in S is 0 or 1.
输入
Input is given from Standard Input in the following format:
S
输出
Print the maximum number of cubes that can be removed.

样例输入 Copy

0011

样例输出 Copy

4

提示
All four cubes can be removed, by performing the operation as follows:
·Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.
·Remove the first and second cubes from the bottom.
这个题的题意就是求最多有多少对相邻的立方体。如果两个相邻的颜色相异就把它们取出,其余的合并,由此我们可以考虑栈这个数据结构,具体实现过程就是一个个字符压栈(push()),然后判断栈顶(top())字符与当前字符相同(表明是同一种颜色),如果相同,则继续压栈;如果不相同,栈顶字符出栈(pop()),直到要压栈的字符与栈顶字符相同为止。注意栈空时也需要压栈,这个要和栈顶字符与当前字符相同在同一个if语句中判断,还要注意或运算"||"前后元素的顺序应该是为空||栈顶字符与当前字符相同(利用逻辑运算的短路特性)。

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
stack<char>cube;
char s[100005];
int main()
{
    int cnt=0;
    int i;
    scanf("%s",s);
    int len=strlen(s);
    for(i=0;i<=len-1;i++)
    {
        if(cube.empty()||cube.top()==s[i])cube.push(s[i]);//压栈
        else
        {
            cube.pop();//栈顶元素出栈
            cnt+=2;//成对出现
        }
    }
    printf("%d",cnt);
    return 0;
}
/**************************************************************
    Language: C++
    Result: 正确
    Time:12 ms
    Memory:2168 kb
****************************************************************/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值