Skip to content

Commit afdd78f

Browse files
DAY 4 Q1 solved
1 parent 97c6f46 commit afdd78f

1 file changed

Lines changed: 72 additions & 0 deletions

File tree

  • Problems/Data-structures/Day-04/sol/Aiyaan_Mahajan
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
DAY 4
3+
Q1 Even Positions
4+
.*/
5+
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
9+
long long solve_case(string s) {
10+
int n = s.size();
11+
12+
int fixedOpen = 0, fixedClose = 0;
13+
for (char c : s) {
14+
if (c == '(') fixedOpen++;
15+
if (c == ')') fixedClose++;
16+
}
17+
18+
int needOpen = n / 2 - fixedOpen;
19+
int needClose = n / 2 - fixedClose;
20+
21+
int balance = 0;
22+
23+
// restore the string
24+
for (int i = 0; i < n; ++i) {
25+
if (s[i] == '(') balance++;
26+
else if (s[i] == ')') balance--;
27+
else {
28+
// underscore -> choose bracket
29+
if (needClose > 0 && balance > 0) {
30+
s[i] = ')';
31+
needClose--;
32+
balance--;
33+
} else {
34+
s[i] = '(';
35+
needOpen--;
36+
balance++;
37+
}
38+
}
39+
}
40+
41+
// compute cost
42+
long long cost = 0;
43+
stack<int> st;
44+
45+
for (int i = 0; i < n; ++i) {
46+
if (s[i] == '(') st.push(i + 1);
47+
else {
48+
int openIdx = st.top(); st.pop();
49+
cost += (i + 1) - openIdx;
50+
}
51+
}
52+
53+
return cost;
54+
}
55+
56+
int main() {
57+
58+
int t;
59+
cin >> t;
60+
while (t--) {
61+
int n;
62+
string s;
63+
cin >> n >> s;
64+
cout << solve_case(s) << "\n";
65+
}
66+
return 0;
67+
}
68+
69+
//TC =O(n) and SC = O(n)
70+
/*
71+
My submission : https://codeforces.com/contest/1997/submission/355669016
72+
*/

0 commit comments

Comments
 (0)