Skip to content

Commit e0071a8

Browse files
authored
Merge pull request #386 from Aaryan-Degama/main
d4q1 done
2 parents 46e8ce6 + 105139a commit e0071a8

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
*/

0 commit comments

Comments
 (0)