A. Case of the Zeros and Ones(Codeforces Round #310 (Div. 2) 栈)

这篇博客探讨了如何找到一个由零和一组成的字符串,在执行相邻数字互为10或01的消除操作后的最小长度。通过示例解释了如何进行操作,并指出可以使用栈来解决这个问题。

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

A. Case of the Zeros and Ones
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.

Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacentpositions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.

Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

Input

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has.

The second line contains the string of length n consisting only from zeros and ones.

Output

Output the minimum length of the string that may remain after applying the described operations several times.

Sample test(s)
input
4
1100
output
0
input
5
01010
output
1
input
8
11101111
output
6
Note

In the first sample test it is possible to change the string like the following: .

In the second sample test it is possible to change the string like the following: .

In the third sample test it is possible to change the string like the following: .



   题意:有一个n个数字的序列,如果相邻的两个数字是10或者01就可以消除,消

除之后由原来不相邻变为相邻的两个数字符合这种情况同样可以消除,问消除之后这

个序列还剩几个数字

   思路:栈正好就好符合这种特性;



#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stack>

using namespace std;

int n;
char str[200010];
stack<char>q;

int main() {
    while(scanf("%d",&n)!=EOF) {
        scanf("%s",str);
        while(!q.empty()) {
            q.pop();
        }
        for(int i=0; str[i]!='\0'; i++) {
            if(q.empty()) {
                q.push(str[i]);
            } else {
                if((q.top() == '1' && str[i] == '0') || (q.top() == '0' && str[i] == '1')) {
                    q.pop();
                } else {
                    q.push(str[i]);
                }
            }
        }
        printf("%d\n",q.size());
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶孤心丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值