题目传送
题意:
给你一个括号序列,现在每一次,你能把一个括号移到最前面或者是最后面,现在问,最少移动几次,使得括号序列合法
思路:
我们先把匹配的序列去掉,那么剩下的就是不合法的,并且不合法的肯定是这种: “)))(((” “))((” “)))))(((((” 这种半分的情况,所以最少移动的次数就是剩下的不合法的括号数量的一半。
AC代码
#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 1e5 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const long long mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
signed main()
{
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
char ss[1000];
cin >> ss;
stack<char>s;
for(int i = 0;i < n;i++)
{
if(s.empty())
s.push(ss[i]);
else if(s.top() == '(' && ss[i] == ')')
s.pop();//去掉匹配的括号
else
s.push(ss[i]);
}
cout << s.size()/2 << endl;
}
}