Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- const int M = 1e9+7;
- const int N = 1e7+5;
- int main() {
- int t;
- cin >> t;
- while (t--) {
- int n;
- cin >> n;
- string s;
- cin >> s;
- string p;
- for(auto c:s){
- if(c=='(') p+='l';
- else p+='r';
- }
- vector<int> suf(n);
- int cnt = 0;
- for (int i = n-1; i >=0; --i)
- {
- if(p[i]=='r'){
- cnt++;
- }
- suf[i]=cnt;
- }
- std::vector<int> lPos;
- for (int i = 0; i < n; ++i)
- {
- if(p[i]=='l') lPos.push_back(i);
- }
- int lCnt = 0, mainCnt=0;
- int maxi = INT_MIN;
- for (int i = 0; i < n; ++i)
- {
- if(p[i]=='l'){
- lCnt++;
- mainCnt++;
- }
- else {
- int l_position = lPos[mainCnt-1]+1;
- if(l_position<n){
- int r_cnt = suf[l_position];
- if(r_cnt>=lCnt){
- maxi = max(maxi , 2*lCnt);
- }
- else lCnt--;
- }
- }
- }
- if(maxi==INT_MIN){
- cout << -1 << '\n';
- }
- else cout << maxi << "\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment