牛客OI赛制测试赛2 E题

链接:https://www.nowcoder.com/acm/contest/185/E
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述
给定括号长度N,给出一串括号(只包含小括号),计算出最少的交换(两两交换)次数,使整个括号序列匹配。
我们认为一个括号匹配,即对任意一个’)’,在其左侧都有一个’(‘与它匹配,且他们形成一一映射关系。

输入描述:
第一行:整数N,表示括号序列长度
第二行:一个字符串,表示括号

输出描述:
一个整数,表示最少的交换次数

示例1
输入
6
(()))(

输出
1

示例2
输入
6
)))(((

输出
2

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>

#define INF 0x3f3f3f3
using namespace std;
typedef long long LL;
const int maxn=5e6+5;
int N;
char s[maxn];

int main()
{
    int ans=0;
    scanf("%d%s",&N,s+1);
    for(int i=1;s[i];i++)
    {
        if(s[i]=='(')ans++;
        else if(ans)ans--;
    }
    printf("%d\n",(ans+1)/2);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41646772/article/details/82497798