https://ac.nowcoder.com/acm/contest/3007/G
Title Description
Define the legal sequence brackets are:
1. empty sequence is a sequence legitimate brackets
2. If S is a legitimate parenthesis sequence, then (S) is a sequence of legal brackets
3. If A and B are legal brackets sequence, it is a legitimate bracket sequence AB
Now, given a sequence of parentheses, brackets seeking to get at least a few deleting a bracketed sequence legitimate
Input data set comprising T, each set of data, provided in parentheses sequence length N
1≤T,ΣN≤1,000,000
(Since empty string is legitimate bracket sequences, the answer may be N)
Thinking
Simulation of a stack, if they went into the stack, if they are to determine what, if the stack is empty, a record number, if it is left bracket on top of the stack to pop
#include <bits/stdc++.h>
using namespace std;
int T;
const int N = 1e6 + 10;
char s[N];
char st[N];
int top;
int n;
int ans() {
top = 0;
int res = 0;
for (int i = 1; i <= n; i++) {
if (s[i] == '(') {
st[++top] = '(';
}
else {
if (top == 0) ++res;
else if (st[top] == '(') {
top--;
}
}
}
res += top;
return res;
}
int main()
{
ios::sync_with_stdio(0);
cin >> T;
while (T--) {
cin >> n;
cin >> s + 1;
cout << ans() << "\n";
}
return 0;
}