题目描述:
You are given a bracket sequence \(s\) of length \(n\), where \(n\) is even (divisible by two). The string \(s\) consists of \(\frac{n}{2}\) opening brackets '(' and \(\frac{n}{2}\) closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index \(i\), remove the \(i\)-th character of \(s\) and insert it before or after all remaining characters of \(s\)).
Your task is to find the minimum number of moves required to obtain regular bracket sequence from \(s\). It can be proved that the answer always exists under the given constraints.
Recall what the regular bracket sequence is:
"( )" is regular bracket sequence;
if \(s\) is regular bracket sequence then "(" + \(s\) + ")" is regular bracket sequence;
if \(s\) and \(t\) are regular bracket sequences then \(s + t\) is regular bracket sequence.
For example, "( ) ( )", "( ( ) ) ( )", "( ( ) )" and "( )" are regular bracket sequences, but ") (", "( ) (" and ") ) )" are not.
You have to answer \(t\) independent test cases.
输出描述:
The first line of the input contains one integer \(t\) (\(1≤t≤2000\)) — the number of test cases. Then \(t\) test cases follow.
The first line of the test case contains one integer \(n\) (\(2≤n≤50\)) — the length of \(s\). It is guaranteed that \(n\) is even. The second line of the test case containg the string \(s\) consisting of \(\frac{n}{2}\) opening and \(\frac{n}{2}\) closing brackets.
输出描述:
For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from \(s\). It can be proved that the answer always exists under the given constraints.
题解:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
int T = 1;
int n, m, x;
int a[N];
int b[N];
void solve()
{
cin >> n;
string s;
cin >> s;
int ans = 0, num = 0;
for (int i = 0; i < n; i++) // 贪心的想,若想要移动次数最少,则需要把已经是符合条件的找出来,则剩下的不符合条件的就需要移动
{
if (s[i] == '(') // 从前往后找出 (
num++;
else
{
num--; // 若为 ) 则将 ( 的数量减一
if (num < 0) // 若减一之后的 ( 的数量大于等于0,则代表有 ( 和 ) 匹配,否则则没有
{
ans++; // num 小于0则代表这个 ) 要移动
num = 0; // 随后要置为零,以防影响之后的判断
}
}
}
cout << ans << '\n';
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
// scanf("%d", &T);
cin >> T;
while (T--)
{
solve();
}
return 0;
}
标签:num,sequence,Brackets,Move,int,bracket,test,regular,贪心
From: https://www.cnblogs.com/KSzsh/p/16901152.html