题解
题意:
括号匹配,给一段括号,可以选择一段区间 [ l , r ] [l,r] [l,r],交换其内部括号的位置使得这一段区间的括号是匹配的,代价是区间长度,问要使整个区间都是匹配的最小代价是多少
官方题解:
遇到
(
(
(,就+1,遇到
)
)
),就 -1,找离-1最近的0的位置,就是这一段区间最小的代价
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6 + 10;
int a[N];
int n, m, K;
string s;
int main() {
ios::sync_with_stdio(0);
cin >> n;
cin >> s;
for (int i = 1; i <= n; ++i) {
a[i] = a[i - 1];
if (s[i - 1] == '(') a[i]++;
else a[i]--;
}
if(a[n]) return puts("-1"),0;
int i = 1, ans = 0;
while (i <= n) {
if (a[i] != -1) {
i++;
continue;
}
int j = i;
while (j <= n && a[j]) {
j++;
}
ans += j - i + 1;
i = j;
}
cout <<ans << endl;
return 0;
}