|
| 1 | +//submission link - https://codeforces.com/problemset/submission/1997/355802679 |
| 2 | + |
| 3 | +#include <bits/stdc++.h> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +/* |
| 7 | +Approach: |
| 8 | +--------- |
| 9 | +We need to restore a Regular Bracket Sequence (RBS) by replacing '_' characters |
| 10 | +such that the total cost is minimized. |
| 11 | + |
| 12 | +Key ideas: |
| 13 | +1. A valid RBS has exactly n/2 '(' and n/2 ')'. |
| 14 | +2. To minimize cost, we should close brackets as early as possible |
| 15 | + (i.e., minimize the distance between matching '(' and ')'). |
| 16 | +3. While filling '_': |
| 17 | + - If balance is 0, we MUST place '(' to avoid invalid sequence. |
| 18 | + - Otherwise, prefer placing ')' (to close early and reduce cost), |
| 19 | + unless we still need to place '(' to reach n/2 opens. |
| 20 | + |
| 21 | +Steps: |
| 22 | +1. First pass: |
| 23 | + - Replace '_' greedily while maintaining RBS validity and minimizing nesting. |
| 24 | +2. Second pass: |
| 25 | + - Use a stack to match '(' with ')' |
| 26 | + - Add (closing_index - opening_index) to total cost. |
| 27 | +*/ |
| 28 | + |
| 29 | +int main() { |
| 30 | + ios::sync_with_stdio(false); |
| 31 | + cin.tie(nullptr); |
| 32 | + |
| 33 | + int t; |
| 34 | + cin >> t; |
| 35 | + |
| 36 | + while (t--) { |
| 37 | + int n; |
| 38 | + cin >> n; |
| 39 | + string s; |
| 40 | + cin >> s; |
| 41 | + |
| 42 | + int need_open = n / 2; // total '(' required |
| 43 | + int open_used = 0; // '(' placed so far |
| 44 | + int balance = 0; // current balance |
| 45 | + |
| 46 | + // First pass: decide '_' positions |
| 47 | + for (int i = 0; i < n; i++) { |
| 48 | + if (s[i] == '(') { |
| 49 | + open_used++; |
| 50 | + balance++; |
| 51 | + } |
| 52 | + else if (s[i] == ')') { |
| 53 | + balance--; |
| 54 | + } |
| 55 | + else { // s[i] == '_' |
| 56 | + // If balance is zero, we must place '(' |
| 57 | + if (open_used < need_open && balance == 0) { |
| 58 | + s[i] = '('; |
| 59 | + open_used++; |
| 60 | + balance++; |
| 61 | + } |
| 62 | + // Otherwise, prefer closing early to reduce cost |
| 63 | + else if (open_used < need_open) { |
| 64 | + s[i] = ')'; |
| 65 | + balance--; |
| 66 | + } |
| 67 | + // If all '(' are already used, must place ')' |
| 68 | + else { |
| 69 | + s[i] = ')'; |
| 70 | + balance--; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + // Second pass: calculate total cost |
| 76 | + long long cost = 0; |
| 77 | + stack<int> st; |
| 78 | + |
| 79 | + for (int i = 0; i < n; i++) { |
| 80 | + if (s[i] == '(') { |
| 81 | + st.push(i); |
| 82 | + } else { // ')' |
| 83 | + int open_pos = st.top(); |
| 84 | + st.pop(); |
| 85 | + cost += (i - open_pos); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + cout << cost << "\n"; |
| 90 | + } |
| 91 | + |
| 92 | + return 0; |
| 93 | +} |
| 94 | + |
| 95 | +/* |
| 96 | +Time Complexity: |
| 97 | +O(n) |
| 98 | +Overall Space: O(n) |
| 99 | +*/ |
0 commit comments