Skip to content

Commit 0df0eb1

Browse files
authored
Merge pull request #376 from Humanshere/main
Solved Day4 Q1
2 parents 3a3a609 + 195f770 commit 0df0eb1

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//Problem Link- https://codeforces.com/problemset/problem/1997/C
2+
//Submission Link- https://codeforces.com/problemset/submission/1997/355848236
3+
//checked greedy pairing of current index with last one in stack
4+
//time complexity- O(n)
5+
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
9+
void solve() {
10+
int n;
11+
string s;
12+
cin>>n>>s;
13+
stack <pair<char,int>> s1;
14+
int cost=0;
15+
for(int i=0;i<n;i++){
16+
if(s1.empty()){
17+
s1.push({s[i],i});
18+
}else{
19+
if(s[i]==')'&&s1.top().first=='_'){
20+
cost+=(i-s1.top().second);
21+
s1.pop();
22+
}else if(s[i]=='('&&s1.top().first=='_'){
23+
s1.push({s[i],i});
24+
}else if(s[i]=='_'&&s1.top().first=='('){
25+
cost+=(i-s1.top().second);
26+
s1.pop();
27+
}
28+
}
29+
}
30+
31+
cout<<cost<<endl;
32+
}
33+
34+
signed main() {
35+
36+
int t;
37+
cin >> t;
38+
39+
while (t--) {
40+
solve();
41+
}
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)