您的位置:首页 > 大数据 > 人工智能

2016 Multi-University Training Contest 8 1011 Rikka with Parenthesis II(模拟)

2016-09-09 12:56 405 查看

题意

给出一堆括号,要求必须交换其中的两个,问交换后是否合法。

思路

很显然,当恰好有一对错位时,交换合法,当原来本身合法 且数量大于4时。可以合法交换,如()是不合法的。扫描的同时记录待匹配的(的个数为cnt,遇到)则减1,若min(cnt) <= -2 则无解。输入为奇数也无解,最后()的数量不匹配也无解。细心模拟就好了

代码

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
char str[maxn];
int main (){
int T;
scanf("%d",&T);
while(T --){
int n;
scanf("%d", &n);
scanf("%s",str);
int cnt = 0;
int cc = 0;
for(int i = 0 ; i < n ; i ++){
if(str[i] == '(')
cnt ++;
else
cnt--;

if(cnt < 0) cc = max(-1*cnt,cc);
}
bool flag = false;
if (cc <= 2 && cnt == 0) flag = true;
if (str[0] == '(' && cnt == 0 && n == 2) flag = false;
if(flag) puts("Yes");
else puts("No");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐