This is yet another problem on regular bracket sequences.
A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.
For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
Input
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
Output
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.
Print -1, if there is no answer. If the answer is not unique, print any of them.
Examples
Input
(??)
1 2
2 8
Output
4
()()
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve: Given a pattern string s of length n (even, up to 5e4), containing '(', ')', '?'. For each ? position i (in order of appearance), we have costs a_i (cost to set '(') and b_i (cost to set ')'). We must replace each ? with either '(' or ')' such that the final string is a regular bracket sequence. Among all possibilities, choose one minimizing total cost. Output total cost and the sequence; if impossible, output -1.
We need to produce any optimal sequence.
This is a classic problem: "Regular bracket sequence with minimum cost replacement" often solved using greedy approach: treat each ? as initially closing bracket (since we need to maintain balance?), but actually we need to decide.
Think: For a string to be a regular bracket sequence, it must have equal number of '(' and ')', length n even. Also any prefix must have number of '(' >= number of ')', and total '(' = total ')'. So constraints.
We have costs for each choice. This can be modeled as a min-cost assignment under balancing constraints. Could be solved by converting to min-cost flow or DP, but n up to 5e4, need O(n log n) perhaps.
Recall known problem: "Minimum cost to make a string a correct bracket sequence" from Codeforces (CF 3D Least Cost Bracket Sequence?). Actually there is a problem: "Least Cost Bracket Sequence" (CF 3D?) where you have string with ? and costs for '(' and ')', you need to produce correct bracket sequence min cost. I think the solution: Initially treat all ? as ')'. Then we need to ensure prefix condition. Use a priority queue to flip some ? from ')' to '(' to fix deficits. But careful: that problem's constraints: each ? must be either ( or ), costs given. The greedy algorithm: Process left to right, maintain current balance (open - close). For each ?, initially choose ')', but that reduces balance? Actually for correct bracket sequence, we need any prefix: #open >= #close. So as we go, we need to have enough opens. The greedy: Start with 0 balance. For each character:
If '(' => balance++.
If ')' => balance--; if balance becomes negative => impossible (but we can flip previous ? to '(' to increase balance).
If '?' => we have choice. The algorithm: Initially, we can tentatively choose ')', balance--, and also we can later change to '(' if needed. But to ensure no negative, we can use a priority queue to store potential benefit of flipping a ? from ')' to '(' (i.e., cost increase? Actually initial choice of ')' costs b_i; flipping to '(' would cost a_i instead, so net change = a_i - b_i (could be negative or positive). We want to minimize total cost while maintaining balance >=0 at all steps. The greedy: For each ?, we initially choose ')', subtract cost b_i, and push (a_i - b_i) into a min-heap. But then we also need to maintain that after choosing ')', balance may become negative? Actually after processing as ')', we do balance--. If balance becomes negative, it means we need to convert one of the previously chosen ')' (from a ?) to '(' to increase balance by 2? Wait: Changing a ? from ')' to '(' increases balance by 2 (since originally we decreased by 1, changing to '(' would increase by 1 relative to that? Let's step carefully.
Standard solution for CF problem 3D "Least Cost Bracket Sequence":
Given string s with '(' , ')' , '?'. For each ? we have costs a (for '(') and b (for ')'), and we need to replace each ? to get a correct bracket sequence with minimum total cost. The greedy:
Initialize answer = 0.
Process left to right.
Keep a variable balance = 0.
Maintain a priority queue (min-heap) of pairs (delta, index) where delta = a_i - b_i (cost if we change from ')' to '(') - note: we initially assign all ? as ')', and we will later possibly flip some to '(' to fix balance. But we must also ensure final total '(' = total ')'. Actually the algorithm also counts total number of '(' needed = n/2.
More precisely:
Let count of '(' needed in final string = n/2.
Let number of fixed '(' in the pattern be open_fixed. So we need to choose exactly (n/2 - open_fixed) of the ? to be '(' (the rest ')').
Also the prefix condition must hold.
The greedy algorithm:
Initialize total_cost = 0.
Create an empty priority queue (min-heap) of costs (actually store the "extra cost" to change a chosen ')' to '(': delta = a_i - b_i, which could be negative or positive).
Iterate over characters i=1..n:
If s[i] == '(':
balance++.
Else if s[i] == ')':
balance--.
Else if s[i] == '?':
// We will initially assign it as ')', paying cost b_i
total_cost += b_i.
balance--.
Push (a_i - b_i) into heap (or push tuple with delta and maybe index).
// Now, to maintain the possibility of having enough '(' eventually, we may need to flip some ? to '(' to keep balance non-negative and also ensure final counts match.
// But we also need exactly needed '(' count.
But wait, we need to ensure that at each step balance never goes negative. However, after assigning ')', we might get negative balance. The standard solution says: if balance < 0, then we need to change one of the previously chosen ')' (from a ?) to '(' (since that would increase balance by 2). Specifically, if balance < 0, we take from the heap the smallest delta (since we want to minimize cost increase) and apply it: total_cost += delta (i.e., we now pay a_i instead of b_i, effectively converting that ? to '('), and then balance += 2 (because originally we counted as ')' decreasing by 1, now as '(' increasing by 1, net change +2). Also we need to mark that ? as '('.
After processing all characters, we also need to ensure that the final total number of '(' equals n/2. Since we only flipped some ? to '(' when balance went negative, we might not have exactly n/2 '(' yet. The typical solution also requires that after the whole scan, the number of '(' we have assigned equals n/2. In the algorithm above, we are not enforcing that explicitly; we rely on the fact that if a valid bracket sequence exists, then after processing all positions and ensuring balance never negative, the final balance (which equals number of '(' - number of ')' ) should be 0. Wait, balance at the end after all characters should be 0 for a correct bracket sequence. But after the algorithm, does it ensure final balance 0? Not necessarily. In many versions, they also process from the right side? Actually the known problem (CF 3D) typically uses two passes? Let me recall: In the editorial for CF 3D, they do:
Initialize balance = 0, total cost = 0, a min heap.
For each character:
if '(' : balance++.
elif ')': balance--.
else: // '?'
read a,b.
total_cost += b.
balance--.
push (a - b) into heap.
if balance < 0:
if heap empty: impossible.
total_cost += heap.pop() (min)
balance += 2.
After loop, if balance != 0: impossible.
That's it! Because if we ensure that at each prefix balance >=0 and final balance =0, then the sequence is a regular bracket sequence. And the number of '(' is automatically n/2 because total '(' = total ')', since length even. So this greedy works.
But is it always optimal? Yes, it's a classic application of min-cost flow converted to greedy with priority queue. The intuition: We must decide for each ? either '(' or ')'. The prefix condition can be seen as: At each position, the number of ')' so far cannot exceed the number of '(' so far. This is similar to matching parentheses. Each time we hit a '?', we have a decision. By initially choosing ')', we create a "debt". If the debt becomes too much (balance negative), we must have previously selected some ')' to convert to '(' to fix it. The best is to pick the one with minimal extra cost.
One must be careful: The initial assignment of all ? to ')' is arbitrary but works because any solution can be transformed: In an optimal solution, the set of ? chosen as '(' must be such that after processing, prefix condition holds. Consider we start with all ? as ')', which yields some total cost sum(b_i). Then we flip some to '('; flipping a ? from ')' to '(' increases cost by (a_i - b_i) and increases balance by 2 (since we effectively remove a ')' and add a '('). The requirement that after flips, all prefixes have balance >=0 translates to: after each position, the cumulative number of flips among ? up to that position must be enough to keep balance non-negative. The greedy that flips the cheapest delta when needed ensures feasibility with minimal added cost.
Moreover, we also need final balance = 0, i.e., total number of '(' = total number of ')' = n/2. Starting from all ')', the total balance at end would be: (#fixed '(' - #fixed ')') - (#?). Actually if we assign all ? as ')', the balance would be: (fixed '(') - (fixed ')' + #?) = open_fixed - (close_fixed + m) = (open_fixed - close_fixed) - m. Since total length n = open_fixed + close_fixed + m, and n is even. For a valid solution, we need to flip exactly k = (n/2 - open_fixed) ?'s to '(' (since we need total opens = n/2). Flipping a ? from ')' to '(' increases balance by 2. So after flipping k ?'s, the final balance becomes: initial balance + 2k = 0. Therefore k is determined: k = -initial_balance/2, provided initial_balance is even and negative. The greedy ensures that we flip exactly that many? The algorithm flips when balance<0, and at the end if balance !=0 -> impossible. But could it flip more than needed? Each flip adds +2 to balance. Starting from some negative initial balance, each time we flip, balance increases by 2. We keep flipping until balance >=0 at each step. At the end, we might have balance >0? Actually the algorithm only flips when balance becomes negative. It ensures that after processing, balance >=0 always; but at the final step, balance may be >0 if we flipped too many? Let's see: In the loop, we only flip when balance < 0. So after flipping, balance becomes balance+2 which could become positive. However, later we may encounter more '(' that increase balance further, possibly making final balance >0. But since we never flip when balance >=0, we only flip to rescue negative condition. So total number of flips is not predetermined; it's the minimum number to keep balance non-negative. But does that guarantee final balance = 0? Not necessarily. However, if the string can be turned into a correct bracket sequence, then after the whole process, the final balance should automatically be 0. Why? Because we ensure balance >=0 throughout, and at the end we check if balance == 0. If not, it's impossible. So the algorithm yields a valid sequence only if balance ends at 0.
But wait, does the greedy always achieve the minimal total cost? I think yes, it's a classic solution. The reasoning: The problem can be reduced to a min-cost flow on a line. The greedy is optimal because it's equivalent to using a priority queue to cover deficits.
Thus we can implement this. However, we must be careful about indexing: The input gives the pattern string first, then m lines where m is number of '?'. Those lines correspond to the '?' in order of appearance in the string. So we need to read the pattern, identify the positions of '?', then for each such position read a_i and b_i.
We need to output the final string with the choices for '?'.
So algorithm:
Read pattern s (string), length n.
Initialize:
total_cost = 0 (maybe long long, up to 5e4 * 1e6 = 5e10, so use 64-bit)
balance = 0
min-heap (priority queue) of pairs (delta, index) where delta = a - b. We need to store also the index of the '?' to know which ones we finally set as '(' or ')' to output the string. Also we need to remember the initial decision: we start as ')', but if we later flip, we change to '('.
Also we need an array result (list of chars) initially copy of s, but for '?' we will decide later.
We'll iterate over i from 0 to n-1, char c = s[i].
Keep a variable q_index to count '?'s encountered.
For each char:
if c == '(':
balance += 1
result[i] = '('
else if c == ')':
balance -= 1
result[i] = ')'
if balance < 0? Actually we might need to check if balance becomes negative due to fixed ')'. In the algorithm, after processing a fixed ')', we also need to check if balance < 0; but if it becomes negative, we cannot flip anything because we have no '?' to change? However, we could have flipped some previous '?'? But we already processed them; the algorithm handles this by flipping a previous '?' when balance < 0 after processing any character (including fixed ')'). So after a fixed ')', balance may become negative. Then we need to pop from heap (which contains deltas of previous '?' that were initially set as ')') and flip one to '(' to increase balance by 2. But is that allowed? Yes, because we can change a previously assigned '?' (which we initially assumed as ')') to '('; that will affect the balance from that point onward (increase by 2). So even after a fixed ')', we can correct deficit by flipping a prior '?'. This is exactly what the algorithm does: after each step, if balance < 0, then we need to convert some previous ? from ')' to '(' (i.e., pop from heap) to increase balance by 2. However, there is a nuance: If the deficit occurs due to a fixed ')', and there is no '?' before to flip, then it's impossible. That's correct.
else: // '?'
read a_i and b_i (we have them from input list; we can read as we go, but easier: read all cost pairs into an array in order of '?' appearance. But we are reading sequentially; we can just read the next pair from input inside the loop. Since the problem statement says: Then there follow m lines, each containing ai and bi. So we can pre-read all costs into vectors, but we also need to know them as we process. I'll read all costs into two arrays as I encounter '?', but we need to know m. Better: first count number of '?' in s. Then read m pairs and store them in an array (maybe using list). Then while iterating over s, maintain an index j for the cost array. That's straightforward.
code
After the loop:
if balance != 0: impossible -> print -1.
Otherwise, output total_cost and the result string.
But is this enough? Let's test on examples.
Example:
Input:
(??)
1 2
2 8
s="(??)", n=4. The costs: first ?: a=1,b=2; second ?: a=2,b=8.
Processing:
i=0: '(' -> balance=1.
i=1: '?' -> a1=1,b1=2. total_cost=2, result[1]=')', balance=0, push delta=-1 (1-2=-1). Check balance>=0, ok.
i=2: '?' -> a2=2,b2=8. total_cost+=8 => 10, result[2]=')', balance=-1, push delta=-6 (2-8=-6). Now balance = -1 <0, so pop smallest delta: heap contains -1 and -6; smallest is -6. Pop: delta=-6, idx=2. total_cost += -6 => 4. balance +=2 => 1. Mark result[2]='('.
Now heap still has -1 (for idx1).
After this, balance=1.
i=3: char ')'? Actually s[3] is ')' (pattern ends with ')'). Process: fixed ')': balance-- => 0, result[3]=')'. Check balance>=0 (0). End loop, balance=0. Output cost 4 and string: result[0]='(', result[1]=')'? Wait we set result[1] initially ')', not flipped, so it's ')', result[2]='(', result[3]=')' => "()()" which is correct. Cost = 4 matches example.
So algorithm works on example.
But there is nuance: In the algorithm, after we pop a ? from heap and flip it to '(', we do not consider it for future flips again. That's correct: each ? can be flipped at most once (from initial ')' to '('). And we might need to flip multiple times if balance becomes negative multiple times? Actually each time balance < 0, we flip one previous ?. That could happen multiple times, each time converting a different ? to '(' (or possibly the same? But we pop from heap, so each popped element is removed; we never push it back. So each ? can be flipped at most once. That's fine.
Now, does this algorithm always yield a valid bracket sequence if possible? I recall that it does, provided that we also enforce that the number of '(' in final is exactly n/2. But in the algorithm we only ensure prefix condition and final balance = 0, which implies total opens = total closes. Since length n is even, opens = n/2. So yes.
But is there any scenario where the algorithm ends with balance=0 but the sequence is not a valid bracket sequence? Prefix condition is maintained because we ensure balance never negative throughout the loop (by fixing when <0). So yes it's valid.
Thus the solution seems straightforward.
Complexities: O(n log n) due to heap operations, n up to 5e4 fine.
Now we need to implement careful reading: The pattern length up to 5e4, number of ? m up to n. Input: first line pattern (might have whitespace? It says non-empty pattern, even length, consisting of characters. Probably it's a string without spaces. We'll read using cin >> s. Then for each ? we read two integers. However, the pattern may contain spaces? Typically it's a string without spaces. Use getline? We'll just read as string.
Edge Cases:
If pattern already contains more '(' than allowed? But algorithm will detect impossibility if final balance cannot be zero.
Costs can be up to 1e6, sum up to 5e10, use long long.
The heap will store (delta, index). Since we need to later flip the result at that index to '(', we need to know the index. So we push a tuple (delta, index). Use min-heap (lowest delta first). In C++, priority_queue by default is max-heap; we can use priority_queue<pair<int64_t, int>, vector<...>, greater<...>> for min-heap, but careful: delta can be negative; we want smallest delta (most negative). Using greater<> will compare pairs lexicographically; we want to compare based on delta first. So we can store as pair<long long, int> and use greater<> to have min-heap on first element.
Alternatively, we can store as pair of (delta, index) and use priority_queue< pair<long long, int> , vector<...>, greater<...> > to get min on delta. However, if two deltas equal, it uses index to break; that's fine.
But we might also consider using negative delta and max-heap; simpler: push (-(a-b), index)? Actually we want smallest delta, so we could push negative delta into max-heap: that would prioritize the most negative delta as largest negative? For delta negative, -delta is positive; but if delta positive, -delta negative. That might not give correct ordering. Better to use min-heap directly.
Implementation details:
We'll have vector<char> res(n).
We'll read costs into vectors a and b of size m, but we need to map each '?' to a cost pair. We can simply maintain a counter j=0, and for each '?' we encounter, we read a[j], b[j] from the list (pre-read or read on the fly). Since we need to read m lines after the pattern, we can first read pattern, then read m pairs into two arrays or a vector of pairs. But we need to know m: we can count '?' in s, then read that many pairs. However, the input format says: "Then there follow m lines, where m is the number of characters "?" in the pattern." So we can count '?' first. Then we can read m pairs. But we need to ensure we read them correctly even if there are extra whitespaces. So after reading pattern, we can read integer pairs accordingly.
Alternative: We can read pattern, then while we have not read all costs, we read pairs, storing them in a vector. But we need to know exactly m; we can compute m = count of '?' in s. So we read pattern, compute m, then allocate vector of pairs of size m, and then loop to read m pairs.
After we have costs, we process s with index j for costs.
Pseudo:
string s;
cin >> s;
int n = s.size();
int m = count(s.begin(), s.end(), '?');
vector a(m), b(m);
for (int i=0; i<m; ++i) {
cin >> a[i] >> b[i];
}
vector res(n);
long long total_cost = 0;
int balance = 0;
int cost_idx = 0;
using P = pair<long long, int>; // delta, index
priority_queue<P, vector, greater> pq; // min-heap on delta
for (int i=0; i<n; ++i) {
if (s[i] == '(') {
res[i] = '(';
balance++;
} else if (s[i] == ')') {
res[i] = ')';
balance--;
} else { // '?'
// use costs at cost_idx
long long ai = a[cost_idx], bi = b[cost_idx];
total_cost += bi;
res[i] = ')'; // tentative
balance--;
pq.push({ai - bi, i});
cost_idx++;
}
// After processing, fix balance if negative
if (balance < 0) {
if (pq.empty()) {
// impossible
cout << -1 << endl;
return 0;
}
P top = pq.top(); pq.pop();
long long delta = top.first;
int idx = top.second;
total_cost += delta; // effectively change to '('
balance += 2;
res[idx] = '(';
// Note: The flipped element might be the current one? Possibly. That's fine.
}
}
Consider pattern: "?)(?" something? Actually pattern may start with ')', that may be impossible unless there is a '?' before that can be flipped to '(' but we process left to right: at first char if it's ')', balance becomes -1, then we check balance<0, but heap is empty (since no '?' processed yet), so we output impossible. That's correct because a regular bracket sequence cannot start with ')'.
Consider pattern: "??". n=2, m=2. Costs: first ?: ( cost 5, ) cost 3; second ?: ( cost 2, ) cost 10. Let's see what algorithm does:
i=0: '?', a1=5,b1=3 => total=3, res[0]=')', balance=-1, push delta=2 (5-3=2). balance<0: pop top (delta=2, idx=0). total+=2=5, balance+=2 => 1, res[0]='('.
i=1: '?', a2=2,b2=10 => total=15, res[1]=')', balance=0, push delta=-8 (2-10=-8). balance=0 ok.
End: balance=0. Output total=15? But is that minimal? Let's find optimal: We need one '(' and one ')'. Options: first '(' (cost5) and second ')' (cost10) => total15; first ')' (cost3) and second '(' (cost2) => total5. The latter is better: " ) ( " but that yields string ")(", which is not a regular bracket sequence because prefix has more ')'. So that sequence is invalid. The only valid regular bracket sequences of length 2 are "()" so exactly first '(' and second ')'. So indeed total 15 is minimal. Our algorithm gave 15, correct.
Consider pattern: "?()?" something? Actually we need to check scenario where we have fixed '(' and ')', and we need to choose parentheses for '?'. Works.
Now consider a more tricky case: pattern: "???". n=3? But even length required; so n=4 perhaps. Let's test pattern "?()?" (n=4): positions: 0:'?',1:'(',2:')',3:'?' . m=2. Suppose costs: ?1: ( cost 1, ) cost 100; ?2: ( cost 100, ) cost 1. We expect optimal: need total 2 '(' and 2 ')' because n=4 and there is one fixed '(' and one fixed ')', so we need exactly one more '(' and one more ')'. The valid sequences: position0 must be '(' (since if it is ')', prefix would be ")" -> invalid). So ?0 must be '('; ?3 then must be ')'. So cost = 1 + 1 = 2. Our algorithm:
a: cost_idx0: a=1,b=100; cost_idx1: a=100,b=1.
Processing:
i0: '?' -> total+=100, res=')', balance=-1, push delta=-99 (1-100). balance<0: pop delta=-99, idx0 -> total+= -99 => 1, balance+=2=>1, res[0]='('.
i1: '(' -> balance=2.
i2: ')' -> balance=1.
i3: '?' -> total+=1 => total=2, res=')', balance=0, push delta=99 (100-1). balance=0 OK. End balance=0. total=2. res = '(' '(' ')' ')'? Wait res[0]='(', i1='(', i2=')', i3=')' => "(())"? Actually that yields "(())", which is valid, but has two '(' and two ')', good. But our solution: ?3 is ')', cost 1; total 2. So it's correct.
Now consider pattern: "?)?("? Not even? Not relevant.
Thus algorithm seems correct.
But wait: Is there any scenario where flipping a ? that is earlier could be better but the greedy picks a later one? The algorithm picks the smallest delta among all currently available ? that were assigned ')'. This is optimal because each flip increases balance by 2 and costs delta. When we need to fix a negative balance, we need to flip exactly one previous ? (since each flip adds 2, enough to bring balance to >=0, but maybe we need more than one flip? Actually when balance <0, the deficit is at most -1? But after processing a character, balance could be -k (k>1). Could that happen? Since each step changes balance by ±1, balance can only decrease by 1 per step. So after each character, balance can be at most previous balance -1. So the first time balance becomes negative is -1. But if we flip one, balance becomes +1 (since -1+2=1). So after flipping, balance becomes >=0, potentially >0. So we never need to flip more than one at a time. However, if we later get another negative balance, we will flip again. So overall the number of flips equals the number of times we encounter balance<0 (each time one flip). That seems consistent with maintaining prefix condition.
But is there a scenario where we need to flip two at once because balance becomes -2? For balance to become -2, it would have been -1 before, and then we processed another character that decreased balance. But after we saw balance -1 earlier, we would have flipped one, bringing balance to +1. So after that, if we get another decrease, balance could become 0, then -1 later. So we might have multiple flips but one at a time. So the greedy handles it.
Now consider if delta is positive, flipping increases cost. But we may have to flip anyway to maintain balance. Choosing the smallest delta (even if positive) is optimal.
Thus algorithm stands.
Now, I recall that the CF problem 3D also requires to output the sequence. Our algorithm as described will output a sequence because we update res when we flip.
But need to be careful: When we flip a ? that we initially set as ')', we update its result to '(' at that moment. But what about later flips? Could we flip the same ? again? No because we pop from heap; each ? appears at most once in heap; after we pop, it's removed.
Now, the algorithm uses heap of (delta, index). But note: When we flip a ? that is earlier, we change its character. That might affect the balance historically? However, our algorithm maintains a running balance that assumes initial assignment of ')' for ? and then adjusts as we flip. Since we update balance after flipping (by adding 2), this effectively corrects the balance from that point forward. That's valid because flipping a previous ? from ')' to '(' means that from that point on, the net balance is increased by 2 compared to the earlier simulation. Since we adjust balance immediately, it's as if we had assigned '(' from the start for that ?. So it's consistent.
One more nuance: After we flip a ? at index idx, we have already processed that index earlier. The result stored at idx is updated to '('; but for later positions, the balance is correctly accounted because we added 2 to balance at the moment of flipping. However, the algorithm does not revisit earlier positions; that's fine.
Now, ensure that the total number of '(' among ? flipped equals exactly the number needed. Since final balance = 0, the total number of flips is k such that initial balance + 2k = 0. initial balance is: fixed '(' - fixed ')' - m. So k = (fixed ')' + m - fixed '(')/2 = (n/2 - fixed '(') ? Let's compute: total length n = fixed '(' + fixed ')' + m. Need total '(' = n/2. So number of '(' from ? must be n/2 - fixed '('. So k = that number. And initial balance B0 = fixed '(' - fixed ')' - m. Since n = f_open + f_close + m, and n even. Then n/2 = f_open + need_open. So need_open = n/2 - f_open. After flipping need_open ?'s, final balance becomes B0 + 2need_open = (f_open - f_close - m) + 2(n/2 - f_open) = f_open - f_close - m + n - 2 f_open = -f_open - f_close - m + n = -(f_open + f_close + m) + n = -n + n = 0. So indeed flipping exactly need_open gives balance 0. The greedy will flip exactly that many if it succeeds. Because each flip adds 2, and we flip when balance negative, and eventually balance becomes 0. But could it flip more than need_open? Suppose we flip an extra ? that later forces balance to become positive and final balance >0, but algorithm would not have flipped that extra because it only flips when balance < 0. So if we flip an extra, then after flipping, balance becomes larger; later we might have many ')' and it might become negative again requiring another flip, but total flips may exceed need_open? Actually need_open is determined by the required number of '(' from ?. If we flip more than need_open, final balance would be positive. But algorithm would still check final balance; if final balance >0, it would deem impossible? But wait, if we flip more than needed, final balance >0, but we could potentially flip back? No, we can't flip back from '(' to ')'. So the algorithm would only flip when forced by negative balance. Could flipping more than needed happen? Suppose after some flips, balance becomes high, then later many ')' come, causing balance to drop, but not below zero, final balance might still be zero if number of ')' is appropriate. However, if we flip an extra, then total '(' from ? would be need_open+1, then total '(' would be f_open+need_open+1 = n/2+1, leading to final balance 2 (since total '(' - total ')' = 2). That would be positive. The algorithm's final check would then detect balance != 0, thus output -1. But could the algorithm still produce such an extra flip? It only flips when balance < 0. If after flipping enough to satisfy the required number, balance never becomes negative again, then no extra flip. If it becomes negative later, it flips again, which might be necessary to meet the required number? Actually need_open is fixed; if we haven't flipped enough by some point, balance would become negative and we flip more. The number of flips made equals the number of times balance went negative. Could that be more than need_open? Suppose initial balance B0 is negative. The minimal number of flips needed to keep balance non-negative throughout and also achieve final balance 0 is exactly need_open. The greedy flips exactly when balance goes negative; each flip adds 2. Starting from B0, after k flips, the effective balance at each step is something. The number of flips made will be exactly the number of times the cumulative balance (based on initial assignment) dips below 0 after considering previous flips. It's known that this greedy yields the minimal cost and results in exactly the needed number of flips (if possible). Because if you could achieve with fewer flips, you'd have a moment where balance <0. So the greedy will flip exactly need_open times, provided the sequence is possible. So final balance should be 0.
Thus algorithm is correct.
Edge Cases to test:
Pattern with no '?': We must check if it's already a regular bracket sequence. Our algorithm will process without any heap. After processing, balance must be 0 and never negative. If at any point balance < 0 (due to fixed ')'), we check heap empty -> impossible. So we output -1 correctly if the fixed pattern is not regular. If it is regular, cost = 0 (since no replacements), and we output the pattern. But note: In input, if m=0, there are no lines after the pattern. So we need to handle that. Our code reads m = count of '?', and if m=0, we will not read any costs. That's fine; the vectors a,b will be size 0; loop will process without encountering '?' case. So works.
Pattern with m>0 but impossible: e.g., s = "?)(" maybe length 3? But even; let's take "?)()" length 4: positions: 0:'?',1:')',2:'(',3:')'. Fixed parentheses: one '(' at index2, two ')' at indices1,3. So we need total '(' = 2. Fixed '(' =1, so need 1 '(' from ?. But can we assign? If we set ? as '(' at index0, the prefix after index1 would be: '(' (index0), ')' (index1) -> balance 0; then '(' (index2) ->1; then ')' ->0 -> valid. So it is possible. But what about "?))("? Actually length 4: indices 0:'?',1:')',2:')',3:'(' . Fixed: '(' at index3, ')' at 1,2. Need 2 '(' total, so need 1 '(' from ?, at index0. Check prefix: index0 '(' ->1; index1 ')' ->0; index2 ')' -> -1 => invalid. So impossible. Algorithm: i0: ? -> treat as ')': total+=b, balance=-1; push delta; balance<0: flip that same ? to '(' if delta negative? Actually we flip immediate: after processing ? at i0, balance=-1, then we pop the heap (contains delta for i0) and flip to '('; total_cost becomes b+(a-b)=a; balance+=2 =>1. Then i1:')' -> balance=0; i2:')' -> balance=-1; balance<0 -> but heap is empty now (since we popped the only ?). So we get impossible. That's correct.
Another impossible: total number of '(' available cannot reach n/2. For example, pattern "??", but with only one '?'? Actually length 2: both '?', need one '(' and one ')'. That's possible. But if pattern "())?" length 4: fixed: '(' at 0, ')' at 1, ')' at 2, ? at 3. Fixed '(' count=1, fixed ')' count=2, so need total '(' =2 => need 1 '(' from ?. Check prefix: after i0 '(' ->1; i1 ')' ->0; i2 ')' -> -1 => invalid even before ?. So impossible. Algorithm: i0: '(' ->1; i1:')' ->0; i2:')' -> -1; after processing i2, balance=-1, heap empty (since ? not processed yet), so impossible. Correct.
What about the case where total number of fixed '(' is already > n/2? Then impossible because we would need fewer '(' but can't change fixed '(' to ')'. For example: pattern "(()?" length 4: fixed: '(' at0, '(' at1, ')' at2, ? at3. Fixed '(' count=2, n/2=2, so we need exactly 0 '(' from ? => ? must be ')'. Check prefix: i0 '(' ->1; i1 '(' ->2; i2 ')' ->1; i3 ? must be ')': then balance 0 -> valid. So it's possible. But if fixed '(' > n/2: pattern "((?" length 3? Even length required; say "((??" length 4: fixed '(' count=2, need total '(' =2, so need 0 '(' from ?. That's possible if ? are both ')'. But prefix after i0 '('->1; i1 '('->2; i2 ? as ')' ->1; i3 ? as ')' ->0 -> valid. So fixed '(' can be exactly n/2. If fixed '(' > n/2, say "((()" length 4? Actually "((()" has 3 '(' and 1 ')', fixed '('=3 >2, can't reduce, so impossible. Algorithm will detect because after processing some characters, balance will be too high and eventually final balance >0. For instance s="((()" (no '?'), length 4, fixed. Process: i0 '(' ->1; i1 '(' ->2; i2 '(' ->3; i3 ')' ->2; final balance=2 !=0 -> impossible. So output -1. Good.
Now, one more nuance: The algorithm ensures prefix condition but not the total count until final. However, there is also a known variant where we need to also check from right to left to ensure that there are not too many '('? Actually the prefix condition is sufficient: For a sequence of parentheses of even length, having prefix condition and total balance zero implies it's a regular bracket sequence. So it's fine.
Now, about output: Print the cost on first line, then the sequence on second line. If -1, just print -1.
Now, potential pitfalls:
The pattern length up to 5e4, but the costs may be up to 1e6, total cost up to 5e10 fits in 64-bit. Use long long (int64_t).
The heap stores deltas that can be up to 1e6 - 1e6 = 0? Actually a_i,b_i up to 1e6, so delta within -1e6 to 1e6, but the sum of deltas can be large, but each delta individually fits in int. But we'll use long long to be safe.
We need to store the index of the character for flipping. That's int.
The priority queue: if using greater<pair<long long, int>>, it will compare first element (delta) then index. That's okay.
However, note: When we push a delta for a ?, we might later pop it to flip. But what if the current ? is the one that caused balance negative and we pop its own delta immediately after pushing? That's allowed. In the code, after processing the character (including push), we check if balance<0 and then pop. So if the current ? caused negative balance, we will pop from heap which includes the just-pushed element. That's fine.
But what about the case where we have multiple negatives? We only pop one. If after popping, balance may become 0 or positive. If it's still negative? Could balance become -2? Let's simulate: Before check, balance is updated by -1. So if balance before processing was 0, after it becomes -1. That's the only case where it becomes negative initially. But after popping and adding 2, balance becomes 1. So not negative. So it's fine. However, if before processing, balance was -1 (already negative) but we would have already fixed it in previous step? Actually our algorithm ensures that after each step we restore balance to >=0 by immediate fix. So before processing next character, balance >=0. So each time we only get at most -1 after a single decrement. So only one flip needed at a time.
Thus the algorithm works.
Now, let's also consider potential scenario: The pattern may have many '?' and fixed parentheses, and the algorithm may flip some '?' to '(' later in the process, but what about the cost? The greedy is proven optimal.
One more nuance: When we push a delta into the heap, it is based on the current index. But later, when we pop and flip that index, we update the result. However, the heap does not contain the current status of the character; it's okay because we only pop once.
Implementation details: We must read input correctly. Possibly there are blank lines? Usually not. So we can read pattern with cin >> s. Then we compute m = count of '?'. Then we read m pairs using for loop.
But caution: The pattern may contain spaces? Usually bracket sequences are strings without spaces. So it's safe.
Alternatively, we could read using getline to include possible whitespace? The problem says "non-empty pattern of even length, consisting of characters '(', ')' and '?'." So it's a single token. So cin >> s is fine.
Edge case: Pattern length maybe up to 5e4, but reading with cin is okay.
Now test with more examples.
Example from CF 3D perhaps:
Input:
(?
1 2
Expected? But length 2? pattern "(?" length 2, m=1. Need one '(' and one ')'. Fixed '(' at pos0, so ? must be ')', cost 2. Output cost 2 and "()". Our algorithm: i0 '(' => bal=1; i1 '?' => ai=1,bi=2 => total=2, bal=0, push delta=-1; bal=0 OK; final bal=0 => output 2 and "()". Works.
Input:
??
1 2
3 4
Need one '(' one ')'. Algorithm: i0 '?' => total=2, bal=-1, push delta=-1 (1-2=-1), bal<0 pop delta=-1, total=1, bal=1, res[0]='('; i1 '?' => total+=4=5, bal=0, push delta=-1 (3-4=-1). End bal=0, total=5. But is this optimal? The valid sequences: either first '(' second ')' -> cost 1+4=5; or first ')' second '(' -> cost 2+3=5. Both equal? Actually second: cost 2+3=5. So both cost 5. So algorithm output 5, which is correct.
If costs are different: first (1,100), second (100,1). Then algorithm: i0: total=100, bal=-1, push -99, pop -99 => total=1, bal=1, res[0]='('; i1: total+=1=2, bal=0, push 99; total=2. That yields cost 2, but is that valid? The sequence is "()", cost 1+1? Wait first '(' cost 1, second ')' cost 1? Actually first ? was changed to '(' (cost 1), second ? as ')' (cost 1) total 2. That's valid. But alternative: first ')' cost100, second '(' cost100 total200, worse. So optimum is 2. So algorithm gives correct.
Now, consider scenario where initial assignment all ')' yields balance that goes negative multiple times, and we flip different '?' with varying deltas. The algorithm picks cheapest each time.
Now, important: The greedy algorithm is optimal, but we need to ensure that the total cost is minimized, and that any solution is feasible.
Potential pitfalls: Because we treat all '?' initially as ')', we are effectively forcing them to be ')' unless we flip. But what if the optimal solution has a '?' as ')' but we later flip it to '(' because of negative balance? That would change it to '(' which might be suboptimal? Actually we only flip when forced; if we flip when not needed, it would increase cost (or maybe decrease if delta negative). But note: If delta is negative, flipping actually reduces total cost! That means that assigning '(' is cheaper than assigning ')', so even if not forced by balance, we might want to flip it to '(' to reduce cost. However, our algorithm only flips when balance becomes negative; it may not flip all beneficial ones. But the initial assignment of all ')' might lead to higher cost if some '(' are cheaper; but we might want to flip those cheaper ones even if not forced, to reduce total cost. But does the algorithm capture that? Actually if a '(' is cheaper (delta negative), we might want to change it to '(' even if balance remains non-negative, because it reduces cost. But would that cause balance to become too high? Changing a ')' to '(' increases balance by 2; that could potentially cause final balance >0 if we flip too many. But we need exactly the required number of '(' (n/2 - fixed '('). If we flip a ')' to '(' that is cheaper, we increase total '(' count. To keep total '(' count correct, we would need to flip another '(' to ')' somewhere else, but we can't flip from '(' to ')' because we started from all ')', and flipping only goes one direction. So the algorithm cannot arbitrarily flip a ')' to '(' if not needed for balance because it would increase the number of '(' beyond needed and break final balance. But if we flip an extra one, we would have to also flip some other '(' to ')' to keep total '(' count correct, but that would require a two-way change, which is not allowed in this greedy. However, the greedy as described is known to be optimal, implying that any solution can be represented as starting from all ')', flipping a subset to '(' such that the set of flipped indices exactly corresponds to those chosen as '(' in the optimal solution, and the flipping order must respect prefix condition. The algorithm ensures that we flip exactly the needed number (n/2 - fixed '(') and those flips are chosen to minimize cost while maintaining prefix condition. So if a '(' is cheaper than a ')', it should be selected as '(' in optimal solution unless constraints force it to be ')'. But the greedy flipping when forced will eventually flip all needed '(' positions, but not necessarily the cheapest globally? But it picks the cheapest delta among all available when it needs to fix a deficit. Over the whole process, the set of flipped positions will be exactly the ones popped from heap. Since we always pop the smallest delta among those seen so far when we need a flip, the set of flips (which become '(') will consist of the cheapest deltas among those that appear before the points where deficits occur. However, could it be that a cheap delta appears after all deficits have been resolved, and we never flip it, but it would be beneficial to flip it and flip some other more expensive one back? But we cannot flip back. In the optimal solution, the set of '(' positions among ? must satisfy that at each prefix, #open >= #close. This is a combinatorial constraint. The greedy algorithm that processes left to right, maintaining a heap of candidates and flipping the cheapest when needed, yields the minimal cost among all valid assignments. I think it's proven by exchange argument.
Actually the classic solution to CF 3D works exactly as described. So I trust it.
Thus implementation is ready.
Now, one more nuance: The pattern length is up to 5e4, but there might be up to 5e4 '?', so heap operations are O(n log n). Good.
Now, we must output the resulting sequence. We have res array; we update when flipping. Note: For '?' that we never flip, they remain ')'. That's correct.
Now, test some random cases to ensure no bug.
Let's implement a small checker in mind: For the output sequence, it must be a regular bracket sequence. Our algorithm ensures that by final balance=0 and never negative. So fine.
Now, we need to ensure that we properly handle the case when we read the pattern and the costs. But note: The input format: first line contains pattern. Then m lines of costs. The pattern might be given on its own line, and there may be no newline after pattern? We'll read with cin >> s. After that, we need to read m integer pairs. That's fine.
But what if the pattern contains spaces? Not likely.
Potential pitfalls: The pattern length might be up to 5e4, but using getline could be safer if the pattern might have spaces? The problem says it consists of characters '(', ')', '?', so no spaces. So cin >> s is fine.
Now, about reading m: we can compute m = count(s.begin(), s.end(), '?'). Then we read exactly m lines. But what if there are extra whitespaces or blank lines? Usually not.
Now, final output: If -1, print -1 (and maybe only one line). The problem says "Print -1, if there is no answer." So just -1.
Now, confirm complexity: O(n log n) time, O(n) memory.
Now, code.
But we should also consider the possibility that the algorithm might need to handle large numbers: total cost as long long.
Edge Cases:
When we flip a '?', we update res at that index. However, if we later encounter another '?' and push it into heap, then later flip it, we update again. That's fine.
We need to be careful about the index: when we push, we push the delta and index i. When we pop, we get idx. We then set res[idx] = '('.
But what if we pop an index that is the same as the current '?'? That's possible if we immediately flip it. In that case, we set res[i] = '(' after having set it to ')' earlier. That's fine.
Now, let's test a case where flipping early might affect later decisions. For example, pattern: "?()?)?" something. Not needed.
Now, I want to test a scenario where the greedy might need to flip not the globally smallest delta because of ordering constraints? Example: suppose we have two '?', with deltas: first delta = +5 (meaning a_i - b_i = +5, so '(' is more expensive than ')'), second delta = -10 ( '(' is much cheaper). The deficits: need exactly one '('? Actually need number of '(' depends. Let's construct a scenario where the first '?' appears before the second, and we need to flip exactly one '?' to '(' to satisfy the balance. The greedy algorithm will initially assign both as ')'. It will encounter the first '?', push delta=5, balance-- => maybe negative? Suppose before first '?', balance is 0. After first '?', balance=-1. Then we need to flip one. The heap contains only delta=5. So we flip first, cost increased by 5, total cost becomes b1 +5 = a1, which is more expensive than if we could flip the second (which is cheaper) but second not yet seen? However, second '?' is not yet in the heap because we haven't processed it. So we cannot flip it. But could the optimal solution flip the second instead? That would mean the first '?' remains ')', second becomes '('. But would that satisfy the prefix condition? Let's simulate: pattern: positions: [0]'?', [1] something, [2]'?'. Need to ensure that after position0, balance is non-negative. If we set first as ')', then after position0, balance would be -1 (if starting from 0). That's invalid. So any valid sequence must have first '?' as '(' to keep balance non-negative at prefix of length 1. Therefore, the greedy flipping the first is forced, even though its delta is positive and the second is cheaper, but second cannot compensate for the early deficit. So the greedy is correct.
Now, what about a scenario where the deficit occurs later, after we have seen both deltas. Then we can choose the smallest among all seen. So it's fine.
Now, could there be a case where we have multiple deficits and we flip a delta that is not the absolute smallest overall but due to ordering? Each time we flip, we pick the smallest among those seen so far. That is optimal because at the moment we need to fix a deficit, we must flip some previously seen ? (since future ? haven't been processed yet and cannot affect past balance). So it's optimal to pick the cheapest among those available.
Thus algorithm is optimal.
Now, implementation details:
We'll store costs in vectors. But we also need to remember the cost pair for each '?' to compute delta. But we can compute delta as a_i - b_i.
We'll also need to store something to output the final string. We'll set res[i] accordingly.
Now, let's write code.
Pseudo-code in C++:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
string s;
cin >> s;
int n = s.size();
int m = count(s.begin(), s.end(), '?');
vector<ll> a(m), b(m);
for (int i = 0; i < m; ++i) {
cin >> a[i] >> b[i];
}
vector<char> res(n);
ll total_cost = 0;
int balance = 0;
int q_idx = 0;
// min-heap of (delta, index)
priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;
for (int i = 0; i < n; ++i) {
if (s[i] == '(') {
res[i] = '(';
++balance;
} else if (s[i] == ')') {
res[i] = ')';
--balance;
} else { // '?'
// use costs at q_idx
ll ai = a[q_idx], bi = b[q_idx];
total_cost += bi;
res[i] = ')';
--balance;
pq.push({ai - bi, i});
++q_idx;
}
// fix deficit
if (balance < 0) {
if (pq.empty()) {
cout << "-1\n";
return 0;
}
auto top = pq.top();
pq.pop();
ll delta = top.first;
int idx = top.second;
total_cost += delta;
balance += 2;
res[idx] = '(';
}
}
if (balance != 0) {
cout << "-1\n";
return 0;
}
cout << total_cost << '\n';
cout << string(res.begin(), res.end()) << '\n';
return 0;
}
But we need to be careful: When we pop from heap, we might pop an element that corresponds to a '?' that we have already flipped? But we only push each '?' once, and we pop it at most once, and after popping we never push again. So no double pops.
Now, double-check that we correctly set the result for '?' that remain ')': we set res[i] = ')' in the '?' case; if we later flip that same index (by popping it), we set it to '(' again. So final assignment is correct.
Now, need to ensure that we have read exactly m cost pairs. Our loop uses q_idx to index into a and b vectors. That's correct.
Now, test with a more complex case where flipping earlier may later cause a deficit that could be fixed by flipping later, but that's fine.
Now, consider pattern: "?()?". Earlier we did it.
Now, consider pattern: "??(??"? Not balanced length? But length even.
Edge Cases: When m=0, the for loop will never push into heap; balance checks will happen; if at some point balance < 0, pq.empty() -> impossible. That's fine.
Now, consider pattern: "((()))" (valid). No '?', balance ends 0. Output cost 0 and string.
Now, we should test a case where after processing all, balance >0, due to too many '(' fixed. Output -1.
Now, memory: n up to 5e4, res array of char, fine.
Now, one more nuance: The algorithm above uses int for balance. Balance can be at most n, so int is fine.
Now, confirm the correctness of using greater<pair<ll,int>>: That sorts by first ascending, then second ascending. That's okay.
Now, potential issue: The delta values could be large positive, and we might pop a delta that is positive but we need to flip because balance negative. That's okay; we must flip to fix deficit even if it increases cost. But could there be a scenario where we have a choice between flipping a positive delta now or flipping a negative delta later? Actually when we have a deficit, we must flip now. If we have multiple candidates in heap, we pick the smallest delta (which could be negative or positive). That minimizes cost. So it's optimal.
Now, one more nuance: When we pop a delta, we effectively change that '?' to '(' from this point onward. However, could it be that we later wish we hadn't flipped that one because some later cheap '(' becomes available? But the decision is irrevocable. However, using exchange argument, one can show that it's optimal to flip the cheapest available when needed.
Now, confirm with a known counterexample? I recall a known problem "Minimum Cost to Make a String Valid" (parentheses) and the greedy with priority queue is standard.
Thus solution is ready.
Now, consider the possibility that the pattern length is odd? The problem says even length, but might not be guaranteed in input? Probably it's guaranteed. But just in case, if odd, it's impossible anyway because regular bracket sequence must have even length. But we could check: if n%2 != 0, print -1. However, problem statement says even length. I'll skip explicit check, but it's safe to include: if n%2 != 0, impossible (since any regular bracket sequence has even length). But we can also let algorithm detect: because if n odd, total '(' would be non-integer, so impossible. But algorithm may still try; but since n odd, required n/2 not integer, so final balance can't be 0? Actually final balance is total '(' - total ')'. Since length odd, there is no way to have balance 0 if we assign all ')' and flip? But initial balance would be fixed '(' - fixed ')' - m. Since n odd, maybe balance could be 0? Example: pattern "?" length 1 odd, but we could assign '(' or ')' but can't have regular bracket sequence because length odd; so impossible. Our algorithm: n=1, m=1, process: i0 '?': total+=b, balance=-1; then balance<0: pop its own delta, total+=a-b => total=a, balance+=2 =>1; final balance=1 !=0, so prints -1. So okay.
But to be safe, we may add a quick check if n%2!=0 -> -1. But it's not necessary.
Now, about printing: If -1, we just print -1 (without newline? with newline). The examples show -1 as only output. So it's fine.
Now, think about any trick: The pattern might be empty? It says non-empty.
Now, we should ensure that the reading of the pattern doesn't skip whitespace and read an empty string. cin >> s should be fine.
Now, consider that the pattern might be large, but we can handle.
Now, there is also the known alternative: Using two priority queues: one for '(' and one for ')', but this one is simpler.
Now, I'm going to implement in C++.
Now, I'm thinking: Is it possible that the greedy algorithm fails because we always initially assign ')' and then only flip to '('? Could there be an optimal solution where a '?' is '(' but we never flip it because we never needed to? Actually if a '?' should be '(' in optimal, then in our initial all-')' assignment, that position is incorrectly set as ')'. To achieve optimal, we must flip it to '('. Our algorithm flips when needed to maintain balance, but what if the optimal solution has a '?' as '(' that is not needed to fix any prefix deficit? For example, consider a pattern where there are many '?' and fixed '(' such that we have exactly the needed number of '(' even without flipping that particular '?', but flipping it would increase the number of '(' beyond needed, making total '(' > n/2, so it cannot be '(' if it's not needed. So any '(' in optimal must be among the needed number. So the set of '(' among ? is exactly the needed number. So they must be chosen. Our algorithm flips exactly that many times because final balance becomes 0. So it will flip that many '?' to '(' over the whole run. So any optimal '(' will be among the flips. The algorithm's choice of which to flip is determined by when deficits occur. However, could there be an optimal solution where a '?' that should be '(' never gets flipped because deficits never forced it, but we still need it to be '(' to meet the total count? Let's analyze: The number of flips equals needed number because final balance=0. So we will flip exactly needed number of '?' to '(' (since each flip increases net balance by 2 and we start with some negative balance). So the algorithm does select a set of exactly needed size. It chooses which ones to flip based on when deficits occur. But is it possible that the optimal set of '(' includes a '?' that appears after the last deficit, and we never have a deficit after that, so we never flip it? But we still need to flip some to reach needed count; if we never have a deficit after some point, it means our balance is >=0 throughout the rest, but we might still need more '(' to meet the total count. However, if we haven't flipped enough by the end, final balance would be >0? Actually need to reason: The number of flips we perform is equal to the number of times we encountered balance < 0. Could it be less than needed? Then final balance would be negative (since we need more '(' to bring balance to 0). But the algorithm ensures that after processing all characters, final balance is 0, else output -1. So if there is a valid solution, the number of deficits encountered should be exactly needed? Actually it's possible that we flip exactly needed number and final balance 0. But could it be that the algorithm flips fewer than needed, but still final balance 0? No, because initial balance + 2*flips = final balance. So if final balance 0, flips = -initial_balance/2 = needed. So number of flips is forced by the final condition; if algorithm ends with balance=0, then it must have flipped exactly needed number. Therefore, the algorithm will indeed flip exactly the needed number of '?' to '('.
Now, could there be a case where the algorithm flips a '?' that should be '(' but it flips a different one that is more expensive, missing a cheaper one that appears later and never gets flipped because deficits stop? Suppose we have many '?' and deficits occur early, we flip some early ones. Later, we may encounter cheaper deltas, but if we never have a deficit after that, we wouldn't flip them. However, we still need to flip a certain number overall; the early flips already account for some of the needed '('; we might not need to flip later ones because we already have enough '('? Actually the total number of '(' needed is fixed. If we flip early ones, that's okay; later cheaper ones might be left as ')', which is fine. But if a later cheap '(' is cheaper than an early expensive one we flipped, maybe we could have waited and flipped the cheap one instead of the expensive one, but would that keep prefix condition? Possibly not, because the early deficit needed an '(' at or before that point. So the early flip must be from among those seen up to that point. So it's optimal to pick the cheapest among those seen. So algorithm picks cheapest at that time. Later cheaper ones cannot be used to fix earlier deficit, so it's okay.
Now, consider scenario: We have two deficits: one early and one later. For early deficit, we flip the cheapest among seen so far. Later, when second deficit occurs, we have a pool of remaining '?' (including those seen after the first flip) and we pick cheapest among them. This yields that the set of flips consists of the k cheapest deltas that are "available" respecting the ordering constraints. This is exactly the optimal selection known from the matroid greedy or Dilworth? So it's optimal.
Hence, algorithm correct.
Now, we need to be careful about reading costs: The m lines correspond to the order of appearance of '?' in the pattern. We have ensured by iterating in order and using q_idx.
Now, let's test with a more complex random case via reasoning.
Suppose pattern: "?)?" length 3? even? Let's do length 6: "?)?(??". Actually let's create a more systematic test: s = "? ? ) ( ? ?". Better to just code a test but mentally.
However, I think it's fine.
Now, maybe we should also consider the possibility of overflow when computing delta as a_i - b_i: both up to 1e6, difference within -1e6 to 1e6, fits in int. But we use long long.
Now, about the priority queue: we push pair<long long, int>. The delta may be negative, but min-heap works fine.
Now, we should also note that after we flip a '?', we don't need to keep track of it further.
Now, implement.
Potential issue: When we pop from heap, we add delta to total_cost. But delta could be negative, making total_cost smaller. That's fine. But we initially added b_i, then add delta, so net cost becomes a_i. So indeed that ? now contributes a_i.
Now, verify that total_cost after all processing equals sum over ? of (if chosen '('? a_i : b_i). That matches.
Now, check for integer overflow: total_cost could be up to 5e4 * 1e6 = 5e10, fits in 64-bit.
Now, final step: output. We'll construct string from res vector.
Now, about the case when there is no answer: we output -1 and return.
Now, confirm with the sample.
Now, edge: pattern may have leading/trailing spaces? No.
Now, consider that the input might be large; using fast I/O (ios::sync_with_stdio(false); cin.tie(0);) helps.
Now, code.
But wait: There is a known variant where the problem requires to also consider that the string must be a regular bracket sequence, and the costs are for converting '?' to '(' or ')'. The greedy algorithm I described is for "Least Cost Bracket Sequence" (CF 3D). I recall that in that problem, the string length up to 5e4, and solution is O(n log n). So it's the same problem.
Thus final answer.
But I'd like to double-check the proof of correctness: In many editorial, they treat the problem as: we need to choose exactly N/2 '(' among positions. For each position i with '?', assign a weight: cost '(' = a_i, cost ')' = b_i. They define delta_i = a_i - b_i. Starting with all ')', total cost = sum b_i. Changing a position to '(' increases cost by delta_i and also increases balance by 2. The prefix condition: at each position, the number of '(' among first i positions must be at least ceil(i/2?) Actually it's: let pref be number of '(' among fixed and selected up to i minus number of ')' up to i. This must be >=0. The condition can be expressed as: for each prefix, the number of selected '(' among ? up to that point must be at least some required minimum. This yields a lower bound. The greedy that flips when necessary with cheapest delta is optimal.
Given that, I'm confident.
Now, implement.
Potential pitfalls: The pattern length can be up to 5e4, but we used vector of chars for res. That's fine.
Now, check for memory: also vectors a, b of size m up to 5e4, fine.
Now, one more nuance: When we push into heap, we store index i. But later, when we pop and set res[idx] = '(', we must ensure that idx corresponds to a '?'. It does because we only push for '?'.
Now, test a scenario where after flipping some, the heap still contains entries for other '?' that remain as ')'. That's fine.
Now, final check: After the loop, we have the res array fully assigned. It's a regular bracket sequence.
Now, we output.
Now, I will consider a random test using a small script mentally.
Take pattern: "?()?)". Let's compute length: positions: 0 '?',1 '(',2 ')',3 '?',4 ')'. n=5? odd, but let's adjust: maybe "?()?)"? Not even. Let's do even: "?()?)?"? n=6? 0 '?',1 '(',2 ')',3 '?',4 ')',5 '?'? That's length 6, fixed: '(' at1, ')' at2 and4. So fixed '(' count=1, fixed ')' count=2, m=3, need total '(' =3, so need 2 '(' from ?. Check if possible. The greedy will find.
But not needed.
Now, there is also a possibility of using two priority queues: one for '(' and one for ')', but as described.
Now, note: In the loop, after processing a fixed ')', we might have balance negative. Then we pop from heap if possible. This corresponds to flipping a previous '?' to '(' to compensate. That is allowed because we can change earlier '?' to '(' to increase past balance.
Now, consider pattern: ")?" (length 2). This should be impossible because starting with ')', cannot fix because no previous '?'. Our algorithm: i0=')': balance=-1; after processing, balance<0, heap empty -> -1. correct.
Now, pattern: "?)?(" length 4? Actually let's do: s = "?)?(": positions 0 '?',1 ')',2 '?',3 '(' . n=4, fixed: ')' at1, '(' at3. Fixed '(' count=1, fixed ')' count=1, m=2, need total '(' =2 => need 1 '(' from ?. Check feasibility: if we set ?0='(', ?2=')'? Then sequence: '(' , ')', ')', '(' -> prefix: after 1:1, after2:0, after3: -1? Actually after i1: '(' (i0) and ')' (i1) => balance 0; after i2: second ')' => balance -1; invalid. If set ?0=')', ?2='(' => sequence: ')', ')', '(', '(' -> after i0: -1 invalid. So impossible. Our algorithm: i0: '?' -> total+=b0, balance=-1, push delta0, balance<0 pop delta0 => flip i0 to '(', total+=delta0 => a0, balance+=2 =>1; i1: ')' -> balance=0; i2: '?' -> total+=b2, balance=-1, push delta2; balance<0 pop delta2 => flip i2 to '(', total+=delta2 => a2, balance+=2 =>1; i3: '(' -> balance=2; final balance=2 !=0 -> -1. So outputs -1. correct.
Now, pattern: "(?)?" length 4: positions: 0 '(',1 '?',2 ')',3 '?' . Fixed: '(' at0, ')' at2. fixed '('=1, fixed ')'=1, m=2, need total '('=2 => need 1 '(' from ?. Check valid sequences: If we set ?1='(', ?3=')' -> "(())" valid? Sequence: (, (, ), ) -> after i1: balance=2, i2:1, i3:0 -> valid. If set ?1=')', ?3='(' -> "()()" -> after i1:0, i2:-1 invalid. So only first is valid. So we need exactly one '(' from either ?1 or ?3, but must be ?1 because if ?1 is ')', we get negative after i2. So optimal cost: choose cheaper '(' among ?1 and ?3, but must be ?1. So if cost for ?1 '(' is high and ?3 '(' is low, we still must pick ?1 '('; but we can't pick ?3 '(' because that would require ?1 ')' and that's invalid. So algorithm: i0 '(' =>1; i1 '?' -> assign ')', total+=b1, balance=0, push delta1; i2 ')' -> balance=-1; after processing i2, balance<0 -> pop from heap (only delta1) flip i1 to '(': total+=delta1 => a1, balance+=2 =>1; i3 '?' -> assign ')', total+=b3, balance=0, push delta3; final balance=0, total = a1 + b3. This is optimal. So algorithm picks ?1 as '(' forced by deficit.
Thus all good.
Now, let's consider scenario where two flips are needed but the cheaper ones appear after the first deficit but before the second deficit. Example: pattern: "??)??" length 5? even length 6? Let's construct a length 6 pattern: s = "? ? ) ( ? ?" Actually to cause two deficits, we need to have times when balance becomes negative twice. Let's design: s = "?)??(?" maybe. Let's do systematic: We need enough ')' to cause deficits. Suppose fixed characters: start with nothing? Actually we can design with only '?' and maybe a fixed ')' to cause deficit. But deficits can also be caused by '?' initially set as ')'.
Consider pattern: "???". n=3? even? Let's do length 6: all '?': "??????". Then need 3 '(' and 3 ')'. The greedy will produce some sequence. The algorithm will process each '?', initially set as ')', balance decreases each time. After first '?', balance=-1 -> flip that one to '(' (pop its own delta) -> balance=1. After second '?', set ')', balance=0 -> no flip. After third '?', set ')', balance=-1 -> flip the smallest delta among those seen and not yet flipped? At that point, heap contains deltas for second and third? Actually after processing first '?', we popped it, so heap empty. Then second '?': we push its delta, balance becomes 0 (since after second we had balance=1? Let's step:
Start balance=0.
i0 '?': assign ')', balance=-1, push d0; balance<0 pop d0 (flip i0), balance+=2 =>1. Heap empty.
i1 '?': assign ')', total+=b1, balance=0, push d1.
i2 '?': assign ')', total+=b2, balance=-1, push d2; balance<0, pop smallest among d1,d2 (which is min(d1,d2)), flip that index, balance+=2 =>1.
i3 '?': assign ')', total+=b3, balance=0, push d3.
i4 '?': assign ')', total+=b4, balance=-1, push d4; balance<0, pop smallest among d3,d4? But we also have maybe some leftover? Actually after i2 we popped one, heap left with the other (either d1 or d2). Then after i3, heap has that leftover + d3. After i4, heap includes leftover + d3 + d4. When balance<0, we pop smallest among them. This continues. Finally, after i5, we might need another flip if balance negative? Actually total flips should be exactly 3. The algorithm will flip when balance becomes -1, which happens at i0, i2, i4? Actually after each flip, balance becomes 1, then after next two '?' (each decrement) we get -1 again? Let's simulate quickly for 6 '?' with some costs. But it's fine.
Now, note that if we have many '?' and many deficits, the algorithm may flip some '?' that are not the globally smallest deltas because of ordering? But as argued, at each deficit, the set of available candidates is those '?' that have been processed up to that point and not yet flipped. The greedy picks the cheapest among them. This yields a set of flips that are the cheapest possible under the constraint that at each prefix, the number of flips among the first i positions must be at least some required minimum (which is like a lower envelope). This is a classic problem of selecting items with precedence constraints; the greedy algorithm works by exchange argument.
Thus I'm convinced.
Now, implementation details: I need to ensure that the heap's comparison works with long long and int. Using greater<> works.
Now, code.
But wait: There's a subtle bug: When we process a '?' and push its delta, and then immediately if balance < 0, we pop the smallest delta. This could be the same element we just pushed. That's okay. But after popping, we set res[idx] = '(' for that index. However, we also set res[i] = ')' initially for the current index if it is a '?' and we haven't yet popped it? In the case where the current '?' is the one popped (i.e., we immediately flip it), we set res[i] = ')' and then later set it to '(' again. So final result is '(' for that index. That's fine.
But note: After we pop and set res[idx] = '(' for idx possibly less than i, we also need to consider that for the current index i (if it is a '?'), we have already set it to ')' and pushed it; but we may not have popped it. That's fine.
Now, ensure we don't double count cost: We added b_i, then if we flip, we add delta = a_i - b_i, so total becomes a_i.
Now, about the output: If there are multiple optimal sequences, any is fine.
Now, time to write final answer.
But before final, I'll consider one more thing: The pattern may have characters other than '(', ')', '?'? Problem says only these, so okay.
Now, implement.
Now, I realize that the sample input and output show parentheses without spaces. Good.
Now, what about the possibility of newline at the end? No issue.
Now, I'll produce final code.
But wait, there is a known issue: In some problems, the pattern length can be up to 5e4, but m lines are given after the pattern. If the pattern line may contain spaces? Usually no.
Now, double-check reading: after reading pattern with cin >> s, the input pointer is at the end of that line, possibly newline. Then we read m integers. That works because >> skips whitespace.
Now, we also need to ensure that we count m correctly. Use count from s.
Now, confirm that m could be zero. In that case, we won't read any cost lines, which is correct.
Now, edge: The pattern might be something like "(?)" and the costs are given, but what if the pattern has extra spaces? Not.
Now, I think it's fine.
Now, let's also consider that we might have to use 64-bit for total_cost, but we also might need to output as long long.
Now, write final code.
But there's one more nuance: In the algorithm, after we pop and flip a '?', we don't remove its entry from the heap? Actually we pop, so it's removed. Good.
Now, what about the possibility that after flipping, the balance becomes >0, and later we may want to flip another one even if balance not negative because it's cheaper? No, we cannot because that would increase number of '(' beyond needed and break final balance unless we also flip some '(' to ')', which we can't. So it's not allowed.
Now, implement.
Now, let's test with some random small cases using mental or maybe a quick Python script? Not possible now but we can reason.
Case: n=2, s="?(", but that's length 2 with fixed '(' at second? Actually pattern "?(" length 2, fixed '(' count=1, need total '(' =1, so ? must be ')', but then sequence: ')(' is invalid because prefix: after first char balance=-1 invalid. So impossible. Our algorithm: i0 '?' -> assign ')', balance=-1, push delta; balance<0 pop delta? flip? After flipping to '(' (if delta negative maybe), then total cost changes, balance becomes 1; i1 '(' -> balance=2; final balance=2 -> -1. So output -1. Good.
Case: n=4, s="?()?" with costs: first ?: a=5,b=1 (so ')' cheaper), second ?: a=1,b=5 ('(' cheaper). Need total '('=2; fixed '('=1 (at index1), so need 1 more '(' from ?. Which one? Must be first? Because if first is ')', after index1 sequence: ? '(' -> if first is ')', then at index0: balance -1 invalid. So first must be '(' (cost5). Then second must be ')' (cost5). Total=10. Could we do first ')', second '('? Invalid. So optimal cost 10. Our algorithm: i0 '?': total+=b=1, balance=-1, push delta=4 (5-1=4), balance<0 pop delta=4 -> total=5, balance=1, res[0]='('; i1 '(' -> balance=2; i2 ')' -> balance=1; i3 '?': total+=b=5 => total=10, balance=0, push delta=-4 (1-5=-4); end balance=0, total=10. So output 10. If we had cheaper first ')' and second '(' but invalid, algorithm doesn't pick it. So correct.
Now, if costs were first a=1,b=5; second a=5,b=1. Then optimal: first must be '(' (cost1), second ')' (cost1) total=2. Algorithm: i0: total+=5, bal=-1, push delta=-4 (1-5=-4), pop delta=-4 => total=1, bal=1, res[0]='('; i1 '(' => bal=2; i2 ')' => bal=1; i3: total+=1 => total=2, bal=0, push delta=4; total=2. Good.
Now, consider case where both are cheap as ')' but we need '(' due to deficits. Already covered.
Now, consider case where there are many fixed '(' causing surplus, but we might need to convert some '?' to ')' to reduce? Actually we start with all ')', so we are only adding '(' never removing '('; if there are many fixed '(', the initial balance may be positive, and we might need to flip some '?' to ')'? But we cannot because we only have direction ')'=> '(' . However, if fixed '(' are already more than n/2, it's impossible. But if fixed '(' are exactly n/2, then all '?' must be ')'. Our algorithm will assign all '?' as ')'. But will it ever flip? Possibly if balance becomes negative? But with many fixed '(', balance may stay positive, so no flips, and final balance will be (fixed '(' - fixed ')' - m). Let's compute: Suppose fixed '(' = f_o, fixed ')' = f_c, m number of '?'. Need total '(' = n/2. If f_o = n/2, then all '?' must be ')'. Then initial balance B0 = f_o - f_c - m. Since n = f_o + f_c + m, n/2 = f_o, so f_c + m = n/2. So B0 = f_o - f_c - m = (n/2) - (f_c + m) = 0. So initial balance is 0. Actually let's verify: f_o = n/2, then f_c + m = n/2, so B0 = n/2 - f_c - m = 0. So initial balance zero. Then processing: we assign all '?' as ')', which matches the required. The algorithm will never encounter balance negative? It could if at some prefix, fixed ')' outnumber fixed '(' plus flipped '('. But with f_o = n/2 and all '?' as ')', the number of '(' at each prefix might be less than ')'? Since the fixed '(' are exactly half and appear somewhere, the prefix condition might be violated if the fixed '(' are not placed appropriately. For example, pattern: "(? )?" not good. Let's take specific: s = "(?)?" length 4, f_o=1, f_c=1, m=2, but f_o not equal n/2=2. So not this case.
Consider pattern: "(()?)" length 5? Not even.
Better: n=4, pattern: "(()?" Wait f_o: positions: 0:'(',1:'(',2:'?',3:'?') fixed '('=2, n/2=2, so m=2 must be both ')'. The pattern "(()?"? Actually "(()?" has length 4? s = "(()?" -> characters: 0:'(',1:'(',2:'?',3:'?'? Actually "(()?" is 4 chars: 0:'(',1:'(',2:'?',3:'?'? No, "(()?" would be '(' '(' ')' '?'? Actually "(()" includes '(' '(' ')'? Let's not get confused. Let's construct: s = "(())" has f_o=2, f_c=2, m=0. That's valid. With '?' we need to ensure that if f_o = n/2, then all '?' must be ')', but also the fixed '(' must be placed such that prefix condition holds even with all '?' as ')'. For example, s = "(?)" length 3? Even? Not.
Let's choose n=6: s = "((??))" fixed '('=2, fixed ')'=2, m=2, n/2=3, so f_o=2 <3, so not this case.
We need f_o = n/2, so all '?' must be ')', and the fixed '(' count exactly n/2. For the sequence to be regular, the fixed '(' alone must already satisfy prefix condition (since '?' are ')'), which means the fixed '(' positions must be such that at any prefix, number of '(' (from fixed) >= number of ')' (from fixed and '?')? Actually the '?' are ')', so they contribute as ')'. So the condition is that the string consisting of fixed '(' and fixed ')' plus all '?' as ')' must be a regular bracket sequence. But since the fixed '(' are exactly n/2 and fixed ')' + m = n/2, this is possible only if the fixed parentheses themselves already form a correct bracket sequence when supplemented with all '?' as ')'. However, the fixed parentheses may not satisfy prefix condition because the '?' as ')' may cause early deficits if there are too many ')' early. Example: n=4, s = "(?)?"? f_o=1, not n/2. Try n=4: s = "(()?"? f_o=2? s = "(()?" -> characters: 0:'(',1:'(',2:'?',3:'?'? Actually I'll just define: s = "(())" has no '?'. To have '?' and f_o=n/2, we need some '?' but they become ')'. So the string will have more ')' than '(' in prefixes potentially. For example, s = "()??" length 4, f_o=1, f_c=1, m=2, n/2=2, f_o=1 <2, not equal.
To have f_o=n/2, we need fixed '(' count exactly half. So for n=4, f_o=2, so maybe s="(()?)" has f_o=2? s="(()?)": indices:0:'(',1:'(',2:'?',3:'?',4:')'? length 5. Not.
Let's design n=4: s = "(? ?)"? That is '(' '?' '?' ')' => f_o=1, f_c=1, m=2 -> f_o=1, n/2=2. So not.
Maybe n=6: s="((?))?"? Not clear.
Nevertheless, if f_o = n/2, then initial balance B0 = f_o - f_c - m = n/2 - f_c - m = (since n = f_o+f_c+m = n/2+f_c+m) => f_c+m = n/2, so B0 = n/2 - (f_c+m)=0. So after assigning all '?' as ')', the total balance is 0. However, during the scan, prefix balances may dip negative because the fixed '(' might be late. Example: s = "?)("? Not even. Let's try n=4: s = "?(()" ? f_o=2? Actually "?(()": 0:'?',1:'(',2:'(',3:')'? That gives f_o=2? positions1 and2 '('? Wait: characters: 0 '?',1 '(',2 '(',3 ')'? That is three '('? Actually 1 '(' and 2 '(' makes two '('? plus maybe? Let's list: s = "?(()" -> length4: index0='?',1='(',2='(',3=')'? So fixed '(' at indices1 and2 =2, fixed ')' at index3=1, m=1. n/2=2, f_o=2 => all '?' must be ')'. So final string would be: index0=')',1='(',2='(',3=')' -> ")()"? Actually that's ") ( ( )" -> string ")(()" which is not regular because prefix ")(" is invalid. So it's impossible to make a regular bracket sequence despite f_o = n/2? Let's check if there is any alternative: Could we set '?' to '('? That would give f_o=3 >2, too many '('. So indeed impossible. So condition f_o = n/2 does not guarantee existence; we also need prefix condition. Our algorithm would detect this as impossible: Process i0 '?': assign ')', balance=-1, push delta; balance<0 pop delta (if any) but it could flip? If we flip i0 to '(' then f_o would become 3, but later maybe final balance becomes 0? Let's see: If we flip i0 to '(' (cost a0), then string becomes "((()" -> "((()"? Actually indices: '(' '(' '(' ')' => "((()" has three '(' and one ')', total balance 2, not 0. So final balance would be 2, not zero. If we don't flip, we have negative balance at i0 and we can't fix because no previous '?'? Actually after i0, balance=-1, we could pop the heap (which contains delta for i0) and flip it to '('; that gives balance=1. Then i1 '(' ->2; i2 '(' ->3; i3 ')' ->2; final balance=2 !=0, so algorithm would output -1. Good.
Thus algorithm correctly handles impossibility.
Now, let's also test scenario where we might need to flip a '?' that we previously flipped? No.
Now, I think everything is fine.
Now, let's code.
But wait: There is a subtle bug: In the branch for fixed ')', we do balance--, then check if balance<0. However, if we have a heap entry from a previous '?' that has already been flipped? Actually once we flip a '?', we pop it from the heap, so it's not there. So the heap only contains entries for '?' that are currently set as ')'. So it's correct.
Now, confirm that we update total_cost correctly. At the end, total_cost is sum over all ? of either a_i or b_i depending on final assignment.
Now, check if we need to use 64-bit for delta as well; we store as long long.
Now, memory: pq may contain up to m entries, fine.
Now, finalize.
Now, I'll write the solution in the final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
string s;
cin >> s;
int n = (int)s.size();
int m = count(s.begin(), s.end(), '?');
vector<ll> a(m), b(m);
for (int i = 0; i < m; ++i) {
cin >> a[i] >> b[i];
}
vector<char> res(n);
ll total_cost = 0;
int balance = 0;
int q_idx = 0;
// min-heap of (delta = a-b, index)
using P = pair<ll, int>;
priority_queue<P, vector<P>, greater<P>> pq;
for (int i = 0; i < n; ++i) {
if (s[i] == '(') {
res[i] = '(';
++balance;
} else if (s[i] == ')') {
res[i] = ')';
--balance;
} else { // '?'
ll ai = a[q_idx], bi = b[q_idx];
total_cost += bi;
res[i] = ')'; // tentative choice
--balance;
pq.push({ai - bi, i});
++q_idx;
}
// fix negative balance if needed
if (balance < 0) {
if (pq.empty()) {
cout << "-1\n";
return 0;
}
auto top = pq.top();
pq.pop();
ll delta = top.first;
int idx = top.second;
total_cost += delta; // change to '('
balance += 2;
res[idx] = '(';
}
}
if (balance != 0) {
cout << "-1\n";
return 0;
}
cout << total_cost << '\n';
cout << string(res.begin(), res.end()) << '\n';
return 0;
// Initially treat as ')'
total_cost += b_i
result[i] = ')' // tentative
balance -= 1
// push into heap: delta = a_i - b_i, index = i (or j)
heap.push( (a_i - b_i, i) )
// increment j
// after processing the character (all three cases), check if balance < 0
if balance < 0:
if heap is empty: impossible -> print -1 and exit.
// pop the smallest delta (most negative delta is best because we want to minimize added cost? Actually we have total_cost added b_i for that ?, and to flip we add delta (which may be negative or positive). To minimize total cost, we choose the smallest delta (i.e., the most negative) because flipping that gives the lowest increase (or biggest decrease) in total cost. But careful: Our total_cost currently includes b_i for all ?. When we flip a ? from ')' to '(', we need to adjust: total_cost = total_cost + (a_i - b_i). So we add delta. So we want the smallest delta (most negative) to reduce cost the most, or at least to minimize increase. So we pop the minimum delta from heap.
let (delta, idx) = heap.pop()
total_cost += delta
balance += 2 // because we changed that ? to '('
// Mark result[idx] = '('
result[idx] = '('
// Note: We do not push it again. After flipping, it's fixed as '('.