C. Unusual Competitions
题意
给定长度为n的字符串,只有左右括号,你可以进行任意次选择连续的k个字符,对他们随意排序需要花费k个精力,问满足题中要求最少要多少个精力
思路
简单括号匹配,碰到右括号进栈,左括号出栈,如果最后栈不为空,输出-1,否则输出ans
代码实现
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 5;
int main(void) {
int n;
cin >> n;
string s;
cin >> s;
int ans = 0;
int l = 0;
for(int i = 0; i < n; i++){
if(s[i]==')') l++;
else{
l--;
if(l>=0) ans++;
}
}
if(l){
cout<<-1<<endl;
}else{
cout<<2*ans<<endl;
}
return 0;
}