File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-04/sol/Himansh_Arora Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments