File tree Expand file tree Collapse file tree
Problems/Data-structures/Day-04/sol/Aaryan Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // link : https://codeforces.com/problemset/submission/1997/355846660
2+
3+ #include < bits/stdc++.h>
4+ using namespace std ;
5+
6+ using ll = long long ;
7+ #define fastio ios::sync_with_stdio (false ); cin.tie(nullptr );
8+
9+ void solve () {
10+ ll n;
11+ cin >> n;
12+ string s;
13+ cin >> s;
14+
15+ s[0 ] = ' (' ;
16+ for (ll i = 1 ; i < n; i++) {
17+ if (i % 2 == 0 ) {
18+ s[i] = (s[i - 1 ] == ' (' ? ' )' : ' (' );
19+ }
20+ }
21+
22+ stack<ll> st;
23+ ll ans = 0 ;
24+
25+ for (ll i = 0 ; i < n; i++) {
26+ if (s[i] == ' (' ) {
27+ st.push (i);
28+ } else {
29+ ans += i - st.top ();
30+ st.pop ();
31+ }
32+ }
33+
34+ cout << ans << ' \n ' ;
35+ }
36+
37+ int main () {
38+ fastio;
39+ int t;
40+ cin >> t;
41+ while (t--) solve ();
42+ return 0 ;
43+ }
44+
45+
46+ /*
47+ Explanation:
48+
49+ We are given a string of length n consisting of '(' and ')'.
50+ First, we fix the string to follow a valid alternating pattern:
51+ - s[0] is always '('
52+ - For every even index i (> 0), we alternate the bracket based on s[i-1]
53+
54+ After this, the string becomes a valid bracket sequence.
55+
56+ To compute the answer:
57+ - Use a stack to store indices of '('
58+ - For every ')', match it with the latest '('
59+ - Add the distance (current index - matched index) to the answer
60+
61+ This distance represents the contribution of that matched pair.
62+
63+ The stack ensures correct pairing and minimal total cost.
64+
65+ Time Complexity:
66+ O(n)
67+
68+ Space Complexity:
69+ O(n)
70+ */
You can’t perform that action at this time.
0 commit comments