Codeforces 1323C Unusual Competitions
本题可以贪心,假设满足条件, 遍历串, 当'('的数量大于')'时, 接下来一定能够不交换合法, 如果')'数量大于'('时, 就一定需要交换顺序, 注意特判')('这种情况即可
#include<bits/stdc++.h>
using namespace std;
#define ms(x,y) memset(x, y, sizeof(x))
#define lowbit(x) ((x)&(-x))
typedef long long LL;
typedef pair<int,int> pii;
const int maxn = 1e6+7;
char str[maxn];
void run_case() {
int n;
cin >> n >> (str+1);
int sum = 0, ans = 0;
for(int i = 1; i <= n; ++i) {
if(str[i] == '(') sum++;
else sum--;
if(sum < 0) ans++;
if(sum == -1 && str[i] == ')') ans++;
}
if(sum) {
cout << -1;
return;
}
cout << ans;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
cout.flags(ios::fixed);cout.precision(2);
//int t; cin >> t;
//while(t--)
run_case();
cout.flush();
return 0;
}