时间限制: 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
****************************************************************/