Bertown is a city with n buildings in a straight line.
The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise.
Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes a coins. He can repeat this operation as many times as you want.
Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes b coins. He can also repeat this operation as many times as you want.
The sapper can carry out operations in any order.
You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city.
Input
The first line contains one positive integer t (1 ≤ t ≤ 10^5) — the number of test cases. Then t test cases follow.
Each test case begins with a line containing two integers a and b (1 ≤ a, b ≤ 1000) — the cost of activating and placing one mine, respectively.
The next line contains a map of mines in the city — a string consisting of zeros and ones.
The sum of the string lengths for all test cases does not exceed 10^5.
Output
For each test case, output one integer — the minimum number of coins that the sapper will have to pay.
Example
Input
2
1 1
01000010
5 1
01101110
Output
2
6
Note
In the second test case, if we place a mine under the fourth building and then activate it, then all mines on the field are activated. The cost of such operations is six, b=1 coin for placing a mine and a=5 coins for activating.
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 understand problem: Bertown with buildings in line, some have mines (string of 0/1). Sapper can perform two operations:
Activate a mine manually: cost a coins. When a mine at x is activated, it causes explosion that activates mines at x-1 and x+1 (if they exist). Those then activate neighbors, etc? The description: "When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment." This suggests that the activation propagates through adjacent mines: one activation triggers neighbors, which trigger theirs, etc. So a connected segment of mines can all be activated by manually activating any single mine in that segment (cost a). But careful: The process: manually activate one mine (cost a). It triggers adjacent mines if they exist. Those triggers further. So yes, one manual activation per connected component (contiguous group of 1s) is enough to set off all mines in that component. But is there any nuance? Could it be beneficial to manually activate more than once within a segment? Probably not, because once a mine is activated, it's gone, and it triggers neighbors. So one manual activation per contiguous segment of 1s should be enough to clear all mines in that segment. However, the sapper can also place mines (cost b) under buildings that originally have no mines. By placing additional mines, he can potentially connect separate segments, so that one activation can set off multiple segments, saving on manual activation costs. But placing mines costs b per mine placed. Also he can manually activate multiple times if needed. Goal: clear all mines (both original and any placed?) Actually "You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city." So after all actions, there should be no mines. So any placed mines must also be eventually activated (since they are mines and we want no mines). But careful: If we place a mine, it's there. Then we must activate it (or it gets activated through propagation). So placing a mine incurs cost b, and then likely it will be activated, maybe via propagation from another activation, so no extra manual activation cost if it's connected to a manually activated mine. However, we might also manually activate a placed mine, but that would cost extra a. So typically we would only manually activate one mine per connected component (after placement) to blow up the whole component. So the cost will be: for each connected component of mines after we place some extra mines, we need to pay a for one manual activation within that component, plus b times the number of mines we placed.
We need to minimize total cost.
Given a binary string s of length n. We can add 1's (by placing mines) at positions originally 0. After adding, we get a new set of positions with mines. Then we need to manually activate each connected component of that set (i.e., contiguous blocks of 1's). The total cost = a * (#components) + b * (#added mines). Goal: minimize.
We need to decide where to add mines to connect existing segments, trading off between the cost of adding mines (b each) and reduction in number of components (each component costs a). Typically, if we have two separate segments of 1's, they are separated by some zeros. If we place mines in the gap to connect them, we turn two components into one (saving a), but we pay b * gap_length (the number of zeros we fill). So connecting is beneficial if b * gap_length < a (since we save a cost of one activation, but we add cost of filling gap). But careful: If we have multiple gaps, we may have a sequence of segments separated by gaps. It's like we have an initial string. Let segments = contiguous blocks of 1's. Let gaps = runs of zeros between them. Suppose there are k segments initially. The cost if we do nothing: a*k (since we manually activate each segment). If we fill some gaps (i.e., convert some zeros into ones) to merge segments, we reduce the number of components. However, each gap we fill completely connects the adjacent segments, merging them into one component. If we fill multiple gaps, the total number of components becomes k - (#gaps filled). However, if we fill non-consecutive gaps, the merging might combine more than two if gaps are adjacent? Actually if we fill a gap, it merges the two neighboring segments into one. After merging, the resulting larger segment may be adjacent to another gap that we also fill, further merging. So effectively, if we fill a set of gaps, the resulting number of components = k - (#gaps filled). Provided we fill gaps that are between segments (non-overlapping). So we can decide which gaps to fill.
But note: Could we partially fill a gap? For example, if we fill some but not all zeros in a gap, does that connect the segments? To connect two segments, we need a continuous path of mines. So we need to fill all zeros between them. If there is at least one zero left, the segments remain separate. So either we fill the entire gap or not. However, there might be cases where we fill a gap partially and then also add mines to the sides? Actually if we fill a gap partially, we might create three segments: left original, new middle block, right original, still separated. So that's not connecting. Unless we also fill additional gaps. But filling part of a gap might be beneficial if we can connect with other segments via that partial? That seems unlikely. Typically we either fill a gap completely to connect adjacent segments, or we don't. But could we benefit from filling a gap partially and then manually activating the new small segment? That would add cost of placing mines (b per placed) and also require manual activation of that new segment (cost a). But we could just manually activate the original segments separately; adding a small isolated segment would increase components, so that's not helpful. So we shouldn't partially fill gaps.
But there is another nuance: The sapper can also place mines at positions not necessarily between segments, maybe at the ends? Placing mines at the ends doesn't connect anything because there are no mines beyond; it just creates new isolated segments (or extend existing segment if adjacent). Could that reduce cost? Possibly if we place a mine adjacent to an existing segment, we extend it, but that doesn't reduce the number of components; it just adds a mine to be cleared that will be activated as part of the segment. That adds cost b but doesn't save a. Unless by extending we can connect to another segment later via additional placements? But that is equivalent to filling the gap. So adding mines at ends is never beneficial because it increases total mines to place (cost) without reducing manual activation count (unless it somehow merges with something else). So we only consider filling gaps between segments.
But also consider that we might not want to activate all segments manually; maybe we could place mines and then manually activate a single mine and let the chain reaction propagate through placed mines and original mines, clearing everything. That would correspond to filling all gaps, i.e., making the entire set of mines (original + placed) into one connected component. That costs a + b*(total zeros we fill). But if there are many zeros, it might be cheaper to just manually activate each segment separately.
Thus the problem reduces to: given initial segments (blocks of 1's) separated by gaps (runs of zeros). Let gaps lengths be g1, g2, ..., g_{k-1} where k is number of segments. Initially, total cost = a * k. If we decide to fill a subset of gaps, total cost = a * (k - m) + b * sum of lengths of selected gaps, where m = number of selected gaps. We want to minimize this.
We can choose any subset. This is like: we have an option for each gap i: we can pay b * gi to reduce the component count by 1 (save a). So it's beneficial to fill a gap if b * gi < a. If b * gi == a, it's indifferent. If b * gi > a, it's not beneficial. However, is there any interdependence? Since each gap reduces component count by exactly 1 regardless of other gaps, decisions are independent. But careful: If we fill a gap, it merges two segments into one. But then what about the next gap? After merging, the gaps are still between the now larger segment and the next segment, so filling it still reduces component count by 1. So the effect of each gap is independent; filling a gap always reduces component count by 1. There is no overlap or conflict. So the optimal is to fill every gap where b * gi < a, and possibly also fill gaps where b * gi == a (either fill or not doesn't change cost). So total cost = a * k - a * (#gaps where b*gi < a) + b * sum_{selected gaps} gi. But wait, we also need to consider that we could fill all gaps or none, but independent selection is optimal.
But let's test with provided examples.
Example 1:
a=1, b=1
s = "01000010"
Indices: 1-based maybe? But string: 0 1 0 0 0 0 1 0. Segments: one '1' at position 2, another '1' at position 7. So k=2. Gaps between them: zeros from index3 to 6 inclusive? Actually between segment1 (pos2) and segment2 (pos7) there are positions 3,4,5,6 = 4 zeros. So g=4. b=1, a=1, bg = 4, which is > a=1. So not beneficial. So we don't fill. Cost = ak = 1*2 = 2. Output is 2. matches.
Example2:
a=5, b=1
s = "01101110"
Let's parse: length 8? Actually string: 0 1 1 0 1 1 1 0? Wait "01101110": positions: 1:0, 2:1, 3:1, 4:0, 5:1, 6:1, 7:1, 8:0. So segments: [2-3] (length2), [5-7] (length3). k=2. Gap: position4 = 1 zero between them? Actually between segment1 ends at 3, segment2 starts at 5, so only index4 is zero -> g=1. b=1 => bg=1 < a=5, so it's beneficial to fill. Then we fill gap (place mine at pos4). Cost = a(k - 1) + b * g = a1 + 11 = 5+1=6. Output is 6. matches.
So the simple greedy works for these.
But wait, is there any situation where we might want to fill a gap even if b*g > a? Perhaps if filling a gap also allows merging multiple components at once? But each gap reduces component count by exactly one. There's no synergy: filling two gaps reduces count by 2. But could we fill a gap that is not between two segments? Possibly at the ends? Filling at ends wouldn't reduce component count, but might allow merging with something else? No.
Consider scenario: three segments with gaps g1 and g2. Suppose g1 is huge, g2 is small. If we fill only g2, we merge segments 2 and 3 into one, leaving segments1 and merged component => 2 components. If we fill both, we get 1 component. The decision to fill g1 is independent: if bg1 < a, it's beneficial; else not. But is there any scenario where it's better to fill g1 even if bg1 > a, because filling both might allow something like only needing to manually activate one and we save 2a, and maybe we could fill only one gap but not the other, but total cost = a2 + bg_selected? If both gaps are selected: cost = a1 + b*(g1+g2). If only g2 selected: cost = a2 + bg2. The difference between filling both vs only g2 is: extra cost = (a1 + b(g1+g2)) - (a2 + bg2) = -a + bg1. So if bg1 < a, it's cheaper to also fill g1; if b*g1 > a, it's cheaper not to fill g1. So independent.
Thus the greedy rule holds.
But wait: there is another operation: manual activation of a mine costs a, and we can do it multiple times. Could it be beneficial to not manually activate any mine in a component? That's impossible; we need to clear mines. Unless we place mines and then manually activate a placed mine and let it propagate, but that's the same.
Could there be a scenario where we partially fill a gap and then manually activate the newly created small segment, but also somehow merge with others later? For example, we have two segments far apart; we could fill a partial gap to create a bridge? Actually to connect, we need contiguous 1's. If we fill only some zeros, there will be a break. The only way to connect is to fill all zeros in between. So partial won't connect.
But what about the possibility of not using manual activation at all? Could we clear mines by placing mines and then perhaps the chain reaction can be started without any manual activation? No, we need at least one manual activation to start the chain; otherwise no mines explode.
Thus solution appears straightforward: Count number of segments of '1's, and for each gap (run of zeros between segments), if length * b < a, then fill that gap, reduce component count, and add length * b to cost. At the end, cost = a * (final_component_count) + b * (sum of filled gaps lengths). But careful: Initially components = number of segments. For each gap we fill, components reduces by 1. So final_components = segments - filled_gaps. So total cost = a * (segments - filled_gaps) + b * sum_filled_gaps_lengths.
Equivalently, total cost = a * segments + sum_{gap} min(0, b * length - a)? Actually we can think: for each gap, we can either not fill: cost contribution 0; or fill: we pay blength but save a (since components reduce by 1). So net effect: if we fill, additional cost = blength - a compared to not filling? Actually initial baseline cost = asegments. For each gap, if we fill, we reduce component count by 1 (saving a) but add blength. So new total = asegments - a + blength. So change = -a + blength. So we fill if blength < a (change negative). So total optimal cost = asegments + sum_{gap} min(0, blength - a). That's a neat expression.
But wait: what about zeros at the beginning or end? They are not between segments, so they don't affect component count. Could we ever benefit from placing mines at the ends? Suppose there is a segment at the very beginning; if we place mines to the left, it doesn't connect to anything, so it increases component count? Actually if we place mines adjacent to the segment (at beginning), we extend the segment, but there is no other segment to merge, so component count remains same. However, we add extra mines that must be cleared; they will be cleared as part of the same component (since they are contiguous). So cost increases by b per placed mine, no saving. So never beneficial. Could there be a scenario where we place mines in multiple separate zeros and then manually activate only one of them, and the chain reaction propagates through both original segments because we created a bridge? That's exactly filling gaps. So only gaps between segments matter.
Thus solution: For each test case, read a, b, string s. Compute number of segments of '1's. Also compute lengths of zero runs that are between segments, i.e., zeros that are between the first 1 and the last 1, and that lie between two 1's. Basically we need to consider gaps strictly inside the outermost 1's? Zeros at extremes (prefix and suffix) do not separate segments, so they are not considered gaps. So we need to iterate through the string, find segments and between them zero runs.
Implementation: Iterate i from 0 to n-1. When we encounter a '1', start a segment. When we transition from 1 to 0 after a segment, start counting zeros. If we later encounter a '1' again, then the zeros counted become a gap. So we need to collect lengths of zero runs that are bounded by 1's on both sides.
Alternatively, we can compute segments and gaps as:
Initialize segments = 0, gaps = [].
i = 0
while i < n:
if s[i] == '1':
segments += 1
# skip consecutive ones
while i < n and s[i] == '1': i+=1
# now at zero or end
# start counting zeros until next 1
zero_count = 0
while i < n and s[i] == '0': i+=1
# after zeros, if we encounter a 1 (i < n and s[i]=='1'), then the zeros we counted are between segments
# but careful: if after zeros we are at end, it's not a gap.
if i < n and s[i] == '1':
gaps.append(zero_count)
# loop continues; note that we are now at start of next segment (since i points to a '1')
else:
i+=1
But there is a nuance: if there are multiple segments, there is exactly one gap between each adjacent pair. However, if there are leading zeros, they are skipped by the initial while; if there are trailing zeros, they are counted but we only add gap if next 1 is found. So it's correct.
Then total cost = a * segments + sum_{g in gaps} min(0, bg - a) i.e., sum of negative values of (bg - a) if negative. Actually to compute total directly: cost = a * segments; for each gap length g, if bg < a then cost += bg - a (since we fill, cost becomes baseline - a + bg). So we can do: cost = a * segments; for each g: if bg < a: cost += b*g - a.
Alternatively, compute filled_gaps = [g for g in gaps if bg < a]; then cost = a(segments - len(filled_gaps)) + b*sum(filled_gaps).
Edge Cases: What if segments == 0? Then no mines initially. We need to blow up all mines, but there are none. So cost = 0. However, could we ever place mines and then activate them? That would be unnecessary; we can just do nothing. So cost = 0. Our algorithm: segments = 0, gaps empty => cost = a*0 = 0. Good.
What if segments == 1? No gaps, cost = a*1 = a? But is it always optimal to pay a? Let's think: there is a single segment of mines. We can manually activate one mine in that segment, cost a, and all mines in segment explode. That's minimal? Could we maybe place extra mines to reduce cost? If we add mines anywhere, it adds cost b and does not reduce manual activation count (still one component). So cost would be a + b * (placed). So worse. So a is optimal. So cost = a.
But wait: is there any alternative to manually activating? Could we place a mine and then manually activate that placed mine, but still need to activate the original segment? Actually if we place a mine adjacent to the segment, it becomes part of the same component, still one manual activation needed. So cost = a + b*(placed). So no benefit. So correct.
Thus the solution seems trivial. But let's check constraints: t up to 1e5, sum of n up to 1e5, a,b up to 1000. So O(n) per test case is fine.
But wait: The problem statement says: "He can repeat this operation as many times as you want." So he can manually activate mines and place mines in any order. The description of activation: "When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment." This indeed indicates propagation along adjacent mines.
But there's nuance: Could there be a scenario where we manually activate a mine, and the explosion triggers adjacent mines, but those might also cause further explosions, etc. So chain reaction covers the whole connected component. So indeed.
Now, is there any subtlety about cost when we place a mine and then manually activate it? Could we avoid paying a for the original segment by placing a mine that triggers it? That's what we already considered: by filling gaps we connect segments, then one manual activation triggers all. So fine.
But is there any possibility to not manually activate any mine at all, but instead use placed mines to cause chain reaction from nothing? No.
Thus solution appears solved.
But let's double-check with more examples. For instance: a=10, b=2, s = "10001". That is segments: two '1's at ends, gap length = 3 zeros. bg = 6 < a=10 => beneficial to fill gap. Then cost = a(2-1)+b3 =10+6=16. Without filling: cost = a2=20. So filling saves 4.
Now consider a=5, b=3, s="101". gap length=1 => b*g=3 <5 => fill, cost=5+3=8 vs 10. Good.
Consider a=4, b=5, s="10001": b*g=15 >4 => not fill, cost=8 vs filling would cost 4+15=19.
Now consider multiple gaps: a=5, b=2, s="101001". Let's compute: string: 1,0,1,0,0,1? Actually "101001": indices: 1:1,2:0,3:1,4:0,5:0,6:1. Segments: positions1, position3, position6? Actually contiguous: there are three segments: [1], [3], [6] (isolated ones). Gaps: between segment1 and segment2: zeros at index2 -> length1. Between segment2 and segment3: zeros at indices4-5 -> length2. So gaps = [1,2]. For each: bg: 21=2 <5 => fill; 22=4 <5 => fill. So both beneficial. Then final components = 3-2=1, sum filled lengths = 1+2=3, cost = a1 + b3 =5+6=11. Without any filling: cost =53=15. So saved 4.
Now test a scenario where some gaps are beneficial and some not: a=5, b=3, s="10010001". Segments: positions1,4? Actually let's write: 1 0 0 1 0 0 0 1 -> segments at indices1,4,8 => three segments. Gaps: between 1 and 4: zeros indices2-3 -> length2. bg=6 >5 => not beneficial. Between 4 and 8: zeros indices5-7 -> length3. bg=9 >5 => not beneficial. So no fill, cost=15. What if we fill both? cost=5+3*(5)=5+15=20. So worse. So indeed choose none.
Now what if one gap is beneficial, other not: a=5, b=2, s="1010001". Segments: [1], [3], [7]? Actually s=1 0 1 0 0 0 1: segments at1,3,7. Gaps: between1&3: length1 -> b1=2<5 beneficial; between3&7: length3 -> b3=6>5 not beneficial. So fill first gap only: components = 3-1=2; sum filled lengths=1; cost = a2 + b1 =10+2=12. Without fill: cost=15; fill both: cost=5+2*(1+3)=5+8=13; fill only first is best (12). Check independent: first gap beneficial, second not. So cost = asegments + (bg1 - a) + 0? Actually baseline 15, for gap1: bg1-a =2-5=-3, so cost=12; for gap2: bg2-a=6-5=+1 (if we fill it we add +1 relative to baseline after maybe? Actually careful: if we fill gap1 and gap2, we get baseline + (bg1 - a)+(bg2 - a) =15-3+1=13; fill gap1 only:15-3=12; fill gap2 only:15+1=16. So independent selection works: we only fill gap if b*g - a < 0. So algorithm holds.
Thus answer is straightforward.
But wait, could there be a scenario where it's beneficial to fill a gap partially? For instance, if a is very high, and b is low, maybe it's cheaper to place a mine somewhere in the middle and then manually activate that placed mine and also manually activate original segments separately? That would be worse. However, consider: Suppose we have a large gap length L. Filling the whole gap costs bL. If L is huge, bL might exceed a. So we wouldn't fill it. But what if we place just one mine in the gap, and then manually activate that mine, and let it trigger the two adjacent mines? But those adjacent mines are zeros originally; if we place a mine at some position, it's isolated unless it's adjacent to other mines. If we place a single mine in the middle of zeros, it will be isolated and its activation will only affect its neighbors if they have mines; but they don't (unless we place more). So it won't trigger the original segments. So to connect, we need continuity. Could we do a different approach: Instead of manually activating each segment, we could manually activate a placed mine that is adjacent to one segment, causing that segment to blow up, but not the other. That doesn't help merging. So partial filling does not connect.
But what about placing mines not as a bridge but to create a new component that when activated, triggers both sides via chain reaction that jumps gaps? The chain reaction only goes to adjacent positions. So to propagate from one side to the other, we need a contiguous path of mines. So we must fill the entire gap.
Thus partial is not beneficial.
Hence solution stands.
But is there any nuance with multiple gaps and the possibility of merging more than two segments by filling some gaps but not others, maybe the order of activation matters? No.
Thus we can implement as described.
But wait, problem statements sometimes have twist: The sapper can place a mine under a building if it wasn't there. He can also manually activate a mine. He can carry out operations in any order. Could there be a scenario where we place a mine, manually activate a different mine, and the explosion triggers the placed mine before we finish placing others? But order doesn't matter because we can place all mines first, then activate. So final state is the same.
Thus answer computed.
Now we need to write code: For each test case:
Read a, b.
Read string s.
n = len(s)
Initialize segments = 0, gaps = [] (list of zero lengths between segments)
i = 0
while i < n:
if s[i] == '1':
segments += 1
# skip contiguous 1s
while i < n and s[i] == '1':
i += 1
# now at zero or end; start counting zeros
start_zero = i
while i < n and s[i] == '0':
i += 1
zero_len = i - start_zero
# if after zeros we are not at end and the next char is '1' (i < n and s[i]=='1'), then this zero run is a gap.
# But careful: i is now at first non-zero after zeros (either '1' or end). So condition:
if i < n and s[i] == '1':
gaps.append(zero_len)
# then continue loop; note we are at a '1' now, so the loop will see it.
else:
i += 1
But careful: The while loop after skipping ones goes to zeros. Then after counting zeros, we check if next char is '1'. If so, we add zero_len. But then we are at i pointing to that '1', so next iteration of outer while will see s[i]=='1' and start new segment. This correctly handles consecutive segments.
But there is a subtle case: What if there are multiple zero runs between segments? Actually after a segment we count zeros until next '1' or end. That yields exactly the run of zeros directly following the segment. Then if the next character is '1', there is a segment after it. So gap length is correct.
Now compute cost:
if segments == 0: print(0) and continue.
else:
total = a * segments
for g in gaps:
if b * g < a:
total += b * g - a
Alternatively, compute:
filled_gaps = [g for g in gaps if b*g < a]
cost = a * (segments - len(filled_gaps)) + b * sum(filled_gaps)
We need to be careful about integer overflow? a, b up to 1000, n up to 1e5, sum of gaps up to n, so cost up to about 1e8, fits in int.
Test with examples: works.
But consider string "1" only: segments=1, gaps empty => cost = a*1 = a. That seems right.
Consider "0"? segments=0 => cost=0.
Consider "01": segments=1, gaps empty => cost=a.
Consider "10": same.
Consider "010": segments=1? Actually string: 0,1,0 => one segment (the '1'), cost=a.
Now consider scenario where there are zeros between segments but they are length zero? Not possible, because segments are contiguous blocks separated by at least one zero.
Now is there any scenario where we might want to fill some gaps but not all even if b*g < a for all? Actually if all gaps are beneficial, we fill all, then final components = 1, cost = a + b * sum(gaps). But wait: Could it be that filling all gaps might cause us to have to place mines on zeros that are at the very ends? No, gaps are only between segments. After merging all segments into one, the component might be surrounded by zeros at ends, but they don't need to be filled. So fine.
But what if we have no segments? Already handled.
Thus solution is simple.
However, is there any catch regarding the order of operations and the cost of activation? For instance, if we place mines, we might need to manually activate the component. That's accounted.
Another nuance: When we manually activate a mine, it activates adjacent mines. That includes both original and placed mines. But after activation, those mines are removed. So chain reaction works.
Thus problem solved.
But before finalizing, let's test with some random strings using brute force small n to confirm. Since constraints small for brute force, we could attempt to check all possibilities of placing mines (2^n possibilities) for small n, but that's exponential. However, we can test the greedy approach on many random small strings by a DP to verify. I'll do mental reasoning: The problem seems similar to "minimum cost to connect segments" where each connection costs b*length and saves a. So it's exactly as we modeled.
But wait, there is a nuance: If we fill a gap, we are placing mines on every zero in that gap. But what if after filling a gap, the resulting component now includes the zeros at the edges? Actually, the gap is between two segments; after filling, the entire region from left segment to right segment becomes one big segment. That's fine.
Could there be a scenario where we fill a gap but then also fill some zeros at the ends to reduce manual activation count? Not needed.
But maybe there is a more subtle strategy: Instead of filling an entire gap, we could place a mine at one of the zero positions and then manually activate it, which might set off one side but not the other? That doesn't help.
Or maybe we could manually activate a mine in a segment, and then before it explodes, place a mine adjacent to it so that the explosion triggers the new mine, which then triggers the other side? However, the explosion happens instantly? The problem statement: "When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens)." It doesn't specify timing. But if we can interleave operations, maybe we can place a mine in a gap just as the explosion is propagating? Could we exploit a kind of "wave" to connect segments without filling the entire gap? For example, suppose we have two segments separated by a gap of length L. Could we manually activate the left segment, and as the explosion propagates to the rightmost mine of that segment, we quickly place a mine at the adjacent building (which is the first gap building) before the explosion reaches it, so that the explosion triggers that newly placed mine, and then we could similarly place a mine ahead of the explosion to continue the chain? But the problem likely assumes operations are sequential and the state is static when an activation occurs. Usually in such problems, you can perform operations in any order, but you cannot interleave within the same activation event. The activation of a mine causes immediate chain reaction to adjacent mines, and those cause further, etc., all instantly. So you cannot insert new mines during the explosion. The order of operations is: you can place mines (any number), then you can activate mines (any number). Or you can intermix, but once you activate a mine, the chain reaction goes through all currently present mines. So you cannot place a mine after activation and have it be triggered by that same activation wave. So to have a chain reaction go through a gap, the mines must be present in the gap at the moment of activation. So you need to place them beforehand. So full gap filling is necessary.
Thus the model holds.
Therefore the solution is as above.
Now let's consider possible pitfalls: When counting gaps, we must ensure we only consider zeros that are between two segments. In the iteration method described, after a segment we count zeros until next character. If the next character is '1', the zeros counted are a gap; if it's the end, they are trailing zeros and not a gap. That's correct.
But what about cases where there are multiple segments but with zeros between them that are counted correctly? Yes.
Now let's double-check with a more complex string: "10101". This has segments: [1], [3], [5]? Actually positions: 1:1,2:0,3:1,4:0,5:1 => three segments. Gaps: between 1 and 3: zero length at pos2 -> 1; between 3 and 5: zero length at pos4 -> 1. So two gaps of length1. Our algorithm: after first segment at positions1, we skip ones: only one '1', then i goes to index1? Let's simulate: i=0, s[0]=='1' -> segments=1; skip ones: while i<n and s[i]=='1': i++ -> i=1 (since s[1]=='0'). Then count zeros: start_zero=1; while i<n and s[i]=='0': i++ -> at i=1, s[1]=='0' -> i=2; s[2]=='1'? Actually s[2] is '1', so loop stops; zero_len = i - start_zero = 2-1=1; now i=2, s[2]=='1'; i<n and s[i]=='1' true, so we add gap 1. Continue outer while: now i=2, s[2]=='1' => segments++ becomes 2; skip ones: while i<n and s[i]=='1' -> i=3 (s[3]=='0'); count zeros: start_zero=3; while i<n and s[i]=='0' -> i=4 (s[4]=='1'? Actually s[4] is '1')? Wait index4: s[4] is '1'? string length 5 indices 0-4: s[0]=1, s[1]=0, s[2]=1, s[3]=0, s[4]=1. So after i=3, s[3]=='0', i increments to 4; s[4]=='1', stops; zero_len=4-3=1; i=4, s[4]=='1' and i<n, so add gap length 1. Continue: i=4, s[4]=='1' -> segments++ becomes 3; skip ones: while i<n and s[i]=='1': i=5 (end); count zeros: start_zero=5; while i<n and s[i]=='0': i stays 5? i=5 out of bounds, zero_len=0; i=5, i<n false, so do not add gap. End. So segments=3, gaps=[1,1]. Good.
Now compute cost as per rule.
Now what about string "110011"? indices: 1,1,0,0,1,1? Actually "110011": s[0]=1,s[1]=1,s[2]=0,s[3]=0,s[4]=1,s[5]=1 => segments: [0-1] and [4-5]? Actually block1: indices0-1 (two 1s), block2: indices4-5 (two 1s). Gaps: zeros at indices2-3 length2. So one gap length2. Good.
Now, is there any scenario where there are overlapping segments? No.
Thus solution is straightforward.
Now, we must implement for up to 1e5 test cases with total length 1e5. So O(total length) is fine.
But we need to be mindful of reading input fast (use sys.stdin.read). We'll implement in Python.
Now let's double-check with potential edge case: a is very small, b is very large. For example a=1, b=1000, s has many gaps. It's never beneficial to fill gaps because bg > a (since g>=1). So we never fill, cost = asegments. Good.
Now, if a is large, b is small, we fill all gaps, cost = a + b * sum_gaps. That could be less than a*segments if sum_gaps is not too huge.
Now, there's one more nuance: If we have a single segment, but there are zeros inside that segment? Not possible; segment is contiguous ones.
Thus answer.
But wait, I recall a Codeforces problem "Bertown Subway" or something? Actually it's Codeforces Round #... It might be problem "1475B" no. There is a problem "Bertown subway" but not this. Actually I've seen a problem "Bertown Underground" but not. This problem likely is from CF Round #... It's similar to problem "1462C" no. It resembles problem "Sapper" from some contest. The solution I described is exactly as many editorial solutions: iterate and for each zero segment between ones, if its length * b < a then fill. So I'm confident.
But let's check the note for the second example: They placed a mine under the fourth building and then activated it. That connects segments? Actually initial map: 01101110. After placing at building 4, map becomes 01111110? Actually original: building1:0,2:1,3:1,4:0,5:1,6:1,7:1,8:0. After placing mine at 4: positions 2,3,4,5,6,7 become all 1? Wait: original 2,3 are 1; 4 becomes 1; 5,6,7 are 1. So indeed all from 2 to 7 become 1, a continuous segment. Then activate any mine: cost a=5. Total 6. That matches our reasoning: fill gap of length1 (b=1), then one activation a=5 => total 6.
Now, what if there are more than two segments? The sapper could place mines in multiple gaps. The note does not discuss that but it's fine.
Now, one more nuance: In the process, after manually activating a mine, all mines in that component explode, so they are removed. If we placed mines, they are removed too. So the goal is achieved.
Thus answer.
But let's read the problem statement carefully again: "When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment." So activation triggers only immediate neighbors, not all at once. But it cascades, so eventually the whole segment gets activated.
Now, what about "He can repeat this operation as many times as you want." So he can manually activate multiple mines, even after some explosions? But if a mine already exploded, it's gone; can't activate again.
Thus we've covered.
Now, think about possibility: Instead of filling gaps, could we remove mines by some other method? No.
Now, consider: Could we place mines and then manually activate a mine in a component, but maybe we could also manually activate another mine in the same component before it explodes? That would be redundant; it doesn't help.
Thus solution stands.
Implementation details:
We'll read t, loop.
Pseudo-code:
import sys
def solve():
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
a = int(next(it)); b = int(next(it))
s = next(it).strip()
n = len(s)
segments = 0
gaps = []
i = 0
while i < n:
if s[i] == '1':
segments += 1
# skip ones
while i < n and s[i] == '1':
i += 1
# now count zeros
start = i
while i < n and s[i] == '0':
i += 1
zero_len = i - start
# if next is 1, then it's a gap
if i < n and s[i] == '1':
gaps.append(zero_len)
# continue; i now points to next 1 or end
else:
i += 1
if segments == 0:
out.append('0')
continue
total = a * segments
for g in gaps:
if b * g < a:
total += b * g - a
out.append(str(total))
sys.stdout.write('\n'.join(out))
But we need to ensure the counting works for case where segment ends at the end: after skipping ones, we count zeros, but if i becomes n, zero_len might be some value (trailing zeros) but we don't add because i==n, so no gap. That's fine.
But careful: In the case where there is a segment, then zeros, then end, we don't add gap. That's correct.
Now test with sample.
We'll run mentally:
Sample input:
2
1 1
01000010
5 1
01101110
First test: a=1,b=1,s='01000010', n=8.
i=0 s[0]='0' -> i=1
i=1 s[1]='1' -> segments=1; skip ones: i goes to 2 (s[2]='0'); count zeros: start=2; while s[i]=='0': i increments until not zero; at i=2 zero, i=3; s[3]=0, i=4; s[4]=0,i=5; s[5]=0,i=6; s[6]='1'? Actually s[6]='1'? Wait string: indices:0:'0',1:'1',2:'0',3:'0',4:'0',5:'0',6:'1',7:'0'. So i from 2: s[2]=0 => i=3; s[3]=0 => i=4; s[4]=0 => i=5; s[5]=0 => i=6; s[6]='1' => stop. zero_len=6-2=4. i=6, s[6]='1', i<n, so add gap length 4.
Continue: i=6, s[6]='1' -> segments=2; skip ones: while i<n and s[i]=='1': i goes to 7 (s[7]='0'); count zeros: start=7; while i<n and s[i]=='0': i=8 (end); zero_len=8-7=1; i=8, i==n, so not add gap.
Loop ends. segments=2, gaps=[4].
Total = asegments = 2.
For g=4: bg=4, a=1 => 4<1? false, so no adjustment. total=2. Output 2.
Second test: a=5,b=1,s='01101110'.
Indices:0:'0',1:'1',2:'1',3:'0',4:'1',5:'1',6:'1',7:'0'.
i=0: s[0]='0' i=1.
i=1: s[1]='1' -> segments=1; skip ones: while s[i]=='1': i=2 (s[2]='1') i=3 (s[3]='0')? Actually start: i=1; while i<n and s[i]=='1': i++; i becomes 2 (s[2]=1) then 3 (s[3]=0) stop. So i=3. count zeros: start=3; while s[i]=='0': i=4 (s[4]=1) stop; zero_len=4-3=1; i=4, s[4]='1', so add gap length1.
Continue: i=4: s[4]='1' -> segments=2; skip ones: while s[i]=='1': i=5 (1) i=6 (1) i=7 (0) stop; i=7. count zeros: start=7; while s[i]=='0': i=8 (end) stop; zero_len=8-7=1; i=8, end, so not add gap.
Segments=2, gaps=[1].
Total = a2 =10.
For g=1: bg=1 <5 => total += 1-5 = -4 => total=6.
Output 6. matches.
So algorithm correct.
But wait, what about the case where there are zeros at the beginning and then a segment, and then zeros, and then segment? Already handled.
Now consider if there are multiple segments but some gaps are of length zero? Not possible because between segments there is at least one zero. So no.
Now, one more nuance: In our counting, after we process a segment and count zeros, we check if next char is '1' to add gap. But what if there are multiple segments separated by zeros, but the zeros we counted include all zeros up to the next '1'. That's correct.
Now, we should also consider the possibility of empty string? Not per constraints (n length at least 1? It says map is a string of zeros and ones, length not specified but at least 1? Possibly empty? But sum of lengths up to 1e5, and test cases have strings, I assume non-empty). But if empty, segments=0 cost=0 fine.
Now, we must confirm with some corner cases:
Case: "1 0 1"? Actually b can be 0? According to constraints 1 ≤ a, b ≤ 1000, so b is at least 1. So no zero cost to place mines.
Case: a=1000, b=1, s with many large gaps but many segments. For each gap if length1 < 1000? If length <= 999, it's beneficial. So we fill all gaps except those of length >=1000? But gap length is at most n which could be up to 1e5, so some gaps may be longer than 1000. So we only fill gaps where length < a/b? Actually condition bg < a. Since b=1, condition g < a. So if a=1000, we fill gaps of length 999 or less, but not gaps of length 1000 or more. So cost = a*(segments - filled_gaps) + sum_filled_gaps.
Now, what about a scenario where a=1, b=1000, we never fill.
Now, is there any scenario where we would not fill a gap even if b*g < a? Possibly if filling that gap also forces us to fill other gaps? No.
But maybe consider if we have three segments, and we fill the middle gap but not the outer gap. That's allowed.
Thus the solution is indeed greedy per gap.
Hence implement.
But wait, let's read the problem statement again: "Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment." This suggests that if we have a continuous segment, we need to manually activate one mine. But what if we have a continuous segment that includes both original and placed mines, we need to activate one mine. That's fine.
Now, can we place mines and then manually activate a placed mine that is not part of any original segment? That would blow up only the placed mines if they are isolated; not helpful.
Thus correct.
But there is another nuance: The cost a is for manually activating one mine. If we have a segment, we must pay a to activate it. However, if we have a segment that is connected to another segment via a bridge of placed mines, then after merging, it's one segment. So we pay a once. So we saved a.
Thus the model stands.
Now, let's consider scenario where we have two segments separated by a gap of length L. If we fill the gap, we pay b*L. But could we get away with only placing mines on some of the positions in the gap and then manually activating multiple mines to cause chain reaction across the gap? For chain reaction to cross, each adjacent pair must have a mine. So we need to fill every position between the two segments. Because if there is a missing position, the chain stops. So must fill all.
Thus no.
Now, check if there is any other operation: "He can place a mine under a building if it wasn't there." That includes originally there is no mine, he can place. Also, he can also possibly remove mines? No.
Thus everything covered.
Now, confirm with some more tests via brute reasoning:
Consider a=3, b=2, s="10001". segments=2, gap length=3, b*g=6 >3 => not fill. cost=6. Alternative: fill gap cost=3+6=9, worse.
Now consider a=3, b=1, s="10001". gap length=3, bg=3, not less than a=3 (equal). So can fill or not. If we fill: cost = a1 + b3 = 3+3=6; if not fill: cost = a2 = 6; same. So either.
Now, consider a=3, b=1, s="100001". gap length=4, b*g=4 >3 => not fill. cost=6; fill: 3+4=7, worse.
Now, what if there are multiple gaps and we fill some but not others, independent.
Thus solution done.
Now, given constraints, we can implement.
But I recall that in some Codeforces solutions, they used a simpler method: iterate over the string, find the positions of first and last '1', then for zeros between them, if a segment of zeros of length L, then if Lb < a, then add Lb to total and subtract a? Or they compute cost = a * (number of segments) and then subtract a for each zero segment where Lb < a and add Lb. That's exactly.
Alternatively, we can treat zeros at the extremes as not considered.
So code is ready.
Now, let's think about potential pitfalls: when the string is long, the loop is fine.
Now, double-check the computation of gaps: In our loop, after a segment we count zeros until next non-zero. If we are at the end after counting zeros, we do not add gap. But what about the case where there are multiple segments and we have zeros after the last segment; those are trailing zeros, not a gap. Also zeros before first segment: we skip them in the outer loop (i increments until we find a '1'). So those are not counted as gaps.
Now, what about the scenario where there are only zeros? segments=0 => cost=0.
Now, what about the scenario where there is a single '1' and zeros around: segments=1, no gaps => cost=a.
Now, what about scenario where the string is all ones: segments=1, no gaps => cost=a.
Now, what about scenario where the string is "101": segments=2, gap length=1. cost as per rule.
Thus answer.
Now, let's consider the possibility of placing mines not only in gaps but also at positions that are not between segments but might allow a different connection pattern, like connecting three segments with a "hub" placed somewhere. For example, segments at positions 1, 5, 9. Gaps: between 1&5: length 3; between 5&9: length 3. If we fill both gaps, cost = a1 + b6. But what if we place mines at position 3 and 7 (not filling all), and then manually activate the middle segment? That wouldn't connect all. To connect all three, we need a path. Could we place mines at 3 and 7 and then also at something to connect them? That would end up filling all positions between anyway. Or we could place a mine at position 5 (already there), and then maybe place mines at 3 and 7 and then manually activate at 3, which would trigger 1? 3 adjacent to 4? Wait, let's map: positions: 1 (original), 5 (original), 9 (original). If we place mines at 3 and 7, we have mines at 1,3,5,7,9. Are they contiguous? 1 and 3 are not adjacent (position2 is empty). So they are not contiguous; chain from 1 to 3 would require 2. So not connected. To connect, we need to fill all positions between 1 and 5: i.e., positions2,3,4. So partial doesn't work.
Thus indeed.
Now, could we benefit from not activating all mines at once? Suppose we have two segments. Instead of manually activating each segment separately (cost 2a) or connecting them (cost a + bL), maybe we could manually activate one segment, let it explode, then place mines in the gap and manually activate them to blow up the other segment? But after first explosion, the first segment mines are gone. We can then place mines in the gap (cost bL) and then manually activate one of them (cost a) to blow up the second segment? But we still need to blow up the second segment. However, we could also after placing mines in the gap, we could manually activate the second segment directly (cost a). So total cost = a (first) + bL + a (second) = 2a + bL. That's worse than just manual activation both (2a) if bL >0, and worse than connecting (a + bL) if a >0. So no benefit.
Could we place mines after first explosion to connect to second segment and then the second segment is triggered automatically? After first explosion, there are no mines left from first segment, but we could place mines in the gap and then manually activate a placed mine that is adjacent to the second segment. That would blow up the second segment. But that's still a manual activation for the second segment (since the placed mine is adjacent to second segment, activating it will trigger the second segment's mines? Actually if we place a mine at a position adjacent to the second segment (say at the boundary of the gap next to the second segment), and then manually activate that placed mine, it will trigger the adjacent mine in the second segment (since it's adjacent), causing the whole second segment to explode. So that's effectively manually activating the second segment via a placed mine, but it's still a manual activation (cost a). So total cost = a (first) + bL (place mines) + a (activate placed mine) = 2a + bL. Worse.
But what if we place a mine in the gap, and then manually activate the first segment; the explosion of the first segment might propagate through the gap if the mines are present at the time of activation. So to have propagation, we need mines in the gap before activation. So if we place mines after the first explosion, it's too late. So the only way to have one manual activation is to place mines first, then activate one mine. So that's the merging strategy.
Thus, the model holds.
Now, the solution is basically greedy: fill gaps where length * b < a.
But wait: Could there be an even more clever approach: Instead of filling an entire gap, we could fill a subset and then manually activate multiple times in a specific order to cause propagation across the gap without full filling? For instance, consider two segments separated by a gap of length 2: positions: 1 (mine), 2 (empty), 3 (empty), 4 (mine). Could we do: manually activate mine at 1, which explodes and does nothing to 2 because no mine there. Then after explosion, we quickly place a mine at 2? But explosion already happened; can't. If we place mine at 2 before activation, but not at 3: then activation at 1 will trigger mine at 2 (since adjacent). Mine at 2 explodes and triggers neighbors: 1 (already gone) and 3 (no mine). So chain stops. So not reaching 4. To reach 4, we need a mine at 3 as well at the time 2 explodes. So both 2 and 3 needed simultaneously before any activation. So full filling required.
Thus done.
Thus final answer.
Now, we should think about potential integer overflow: Not an issue in Python.
Now, to be thorough, let's think about another scenario: Suppose we have a segment, then a gap of zeros, then another segment. If we fill the gap, we pay b*L. But maybe we could instead place mines only on one side of the gap and then manually activate the other segment? That doesn't connect.
Now, think about case where a is extremely high, b is low, and there are many segments separated by small gaps. It's beneficial to fill all small gaps. That's captured.
Now, note: The cost of manually activating a mine is a per activation, not per mine activated. So we just pay a each time we manually trigger a mine. So each component we manually trigger costs a.
Now, is there any scenario where we could trigger a mine without paying a? No.
Thus answer.
Now, let's write final code.
But wait, I recall a known Codeforces problem: "1462C" is something else. Actually this problem might be from Codeforces Round #1462? Not sure. The problem is called "Mines" or "Sapper"? I think it's Codeforces 1612A? Not sure. However, I've seen an editorial that says: Count the number of segments of ones. For each segment of zeros between ones, if its length * b < a, then add length*b to answer and reduce the number of segments by 1. Finally answer = a * segments + sum of chosen lengths * b.
Yes.
Now, one more nuance: In the cost expression, if we fill some gaps, we reduce number of components. But do we need to pay the activation cost for the component after filling? Yes, we pay a for each resulting component. So if we fill all gaps, we pay a once.
Now, what about the possibility of not activating any component? That would leave mines. So not allowed.
Thus final.
But before finalizing, check for some tricky input: "0". That yields 0.
Now, consider "1". Output a.
Now, consider "00". Output 0.
Now, consider "010". Output a.
Now, consider "01010". Let's compute: segments=3 (positions2,4? Actually indices1,3? 0-index: s[1]=1, s[3]=1? Actually "01010": indices0:0,1:1,2:0,3:1,4:0 => segments=2? Wait there are two 1's at indices1 and 3, but they are not adjacent? They are separated by index2 zero, so two segments? Actually "01010": positions: 0,1,0,1,0. So there are two 1's at positions 2 and 4? Actually if we index from 1:1:0,2:1,3:0,4:1,5:0. So segments: one at building2, one at building4, separated by one zero (building3). So segments=2, gap length=1. So cost according to rule.
Now, what about "001100"? segments=1? Actually "001100": indices:0:0,1:0,2:1,3:1,4:0,5:0 => one segment of two 1's, so segments=1. trailing zeros not considered. So cost=a.
Now, "1011001": let's compute: indices:1,0,1,1,0,0,1 => segments: at 1 (pos1), at 3-4 (pos3,4), at 7 (pos7). Actually careful: positions1:1,2:0,3:1,4:1,5:0,6:0,7:1. So segments: [1], [3,4], [7]. So 3 segments. Gaps: between seg1 and seg2: zeros at pos2 length1; between seg2 and seg3: zeros at pos5-6 length2. So two gaps.
Now, if a=4, b=2: gap1: 2<4 fill; gap2: 4 ==4? Actually bg=4 => not less (equal). So fill only gap1 or not? Since equal, both choices give same total? Let's compute: baseline cost=43=12. Fill gap1 only: cost = 42 + 21 =8+2=10. Fill gap2 only: 42 + 22 =8+4=12. Fill both: 41 + 23 =4+6=10. So fill gap1 only and both give 10; gap2 only gives 12. So optimal is to fill gap1, and optionally gap2 (if equal, doesn't matter). Since we use condition b*g < a to decide to fill, gap1 (2<4) will be filled, gap2 (4<4 false) not filled. That yields cost 10, which is optimal. So our condition (<) yields one of the optimal solutions. That's fine.
Now, if bg == a, filling gives no net change, so we can choose either. We'll choose not to fill to keep it simple, but it doesn't affect cost. So condition bg < a is okay.
Now, confirm that we don't need to consider the possibility of filling a gap partially to connect multiple segments with less cost? Suppose three segments with gaps g1 and g2. Could we fill only some mines such that the three segments become connected via a path that does not require filling all zeros? For three segments, to connect all three, we need to fill the two gaps fully, or maybe we could fill a "bridge" that connects all three at a common point? For example, segments at positions 1, 5, 9. Could we place mines at positions 3 and 7, and also place mines at positions 4 and 6? That's essentially filling all positions 2-8? Not exactly. Actually to have a continuous path from 1 to 9, we need all positions from 1 to 9 to be filled. If we fill only some positions, there will be gaps. Unless we can have the path not be straight line? But buildings are in a straight line; there's only one dimension. So to connect, the entire interval between the leftmost and rightmost must be filled. So indeed, to merge k segments into one, we need to fill all zeros between the leftmost and rightmost segments. That is equivalent to filling all gaps between them. So the cost to merge a set of consecutive segments is the sum of the lengths of the gaps between them. So merging two adjacent segments costs the gap length. Merging three segments (1,2,3) costs gap12 + gap23. So if we merge multiple segments, the total cost is sum of the gaps we fill. And the saving in activation cost is (number of segments - 1)a. So the decision to merge a set of consecutive segments is equivalent to individually deciding to fill each gap between them; each gap decision is independent and yields saving a but cost blength. So if for each gap blength < a, it's beneficial to fill it; otherwise not. However, what if for a gap, blength > a, but if we fill it together with other gaps, could the combined saving be more than sum of individual net costs? For instance, we have three segments with gaps g1 and g2. Suppose bg1 > a (so individually not beneficial), bg2 > a (individually not beneficial), but b*(g1+g2) < 2a? Actually if we fill both gaps, we pay b*(g1+g2) and save 2a. Net change = b*(g1+g2) - 2a. If both individually are not beneficial, that means bg1 - a > 0 and bg2 - a > 0, so sum > 0, so net change > 0. So still not beneficial. But what if one gap is large and the other is small, and individually the small is beneficial, the large not. If we fill both, net = (bg1 - a) + (bg2 - a) = (bg1 - a) + (bg2 - a). Since bg2 - a is negative (beneficial), bg1 - a positive, the sum could be negative if the negative outweighs the positive. That is, if the beneficial gap saves more than the loss from the other gap. Example: a=10, b=1, g1=15 (cost 15, saving 10 => net +5), g2=5 (cost 5, saving 10 => net -5). Individually, we would fill g2 but not g1. If we fill both, net = (15-10)+(5-10)=5-5=0, same as filling just g2? Actually if we fill just g2: cost = a*? Let's compute baseline: 3 segments => cost=30. Fill g2 only: final components = 2, cost = 20 + 5 = 25. Fill both: components =1, cost = 10 + 20 = 30. So filling both is worse than filling only g2 (25 vs 30). But wait, if we fill both, cost=10+20=30; baseline=30; so equal? Actually baseline 3 segments cost 30. Fill both: 10+20=30, same. So net zero. Fill only g2: 20+5=25, better. So indeed, we should not fill the large gap if it's not beneficial individually, even if combined with a beneficial gap. However, what if we have three segments, and we consider merging all three into one by filling both gaps, but we might also consider merging only segments 2 and 3, or 1 and 2. The independent decision per gap yields: fill gap2 if bg1 < a. In the example, bg1=15>10 => not fill gap1. That yields components=2, cost=20+5=25. That's optimal. So independent decision works.
But consider scenario where bg1 is just a bit above a, and bg2 is just a bit below a, and maybe the combined net is negative? Let's compute: a=10, b=1, g1=11 (bg1=11 >10), g2=9 (bg2=9<10). Individually: g2 beneficial, g1 not. Fill only g2: cost = 2 components? Actually three segments, fill g2: merge seg2&3 => components=2, cost = 20 + 9 = 29. Baseline=30. Fill both: components=1, cost =10 + 20 =30. So fill only g2 gives 29, better than both (30). So independent still works.
What if g1=12, g2=8? Fill g2 only: cost =20+8=28. Fill both: 10+20=30. So still better to only fill g2.
What if g1=10 (equal), g2=9? bg1=10 not <10, so not fill; g2=9 fill. Cost: baseline=30, fill g2: 20+9=29; fill both: 10+19=29? Actually fill both: a1 + b*(10+9)=10+19=29; same. So independent gives 29 either way (since we can fill g2 and not g1 yields 29; if we fill both also 29). So no issue.
Thus independent decision is optimal.
But is there any scenario where merging non-adjacent segments by filling a gap that is not directly between them might be cheaper? For example, segments at positions 1, 10, 20. To merge all three, we need to fill gaps 1-10 and 10-20. That's sum of both gaps. Could there be a cheaper way: place mines to create a new segment that connects them indirectly? That still requires filling the intervals.
Thus independent per gap works.
Now, the solution is essentially O(n) per test case.
Now, can we simplify code by using splitting on '1'? For example, we can get segments by splitting the string on '1'? Actually if we split on '1' we get zero runs. For string s, after stripping leading and trailing zeros, the internal zero runs correspond to gaps. For example, s.strip('0') removes leading/trailing zeros. Then split on '1' gives list of zero runs between ones. But careful: If there are consecutive ones, splitting on '1' yields empty strings? Actually better: Use s.strip('0') to remove leading/trailing zeros, then split('1') yields segments of zeros. However, splitting on '1' where there are multiple consecutive ones will produce empty strings for each pair of consecutive ones, but we only care about runs of zeros between ones, not empty strings. So we can filter out empty strings and those are the gaps. For instance, s = "01101110". strip('0') -> "110111"? Actually strip('0') removes leading and trailing zeros: leading '0' at index0 removed, trailing '0' at index7 removed, so becomes "110111". Then split('1') on this string yields: ["","","0","","",""]? Actually splitting "110111" on '1': after first char '1' -> empty; after second char '1' -> empty; after third char '0' -> "0"; after fourth char '1' -> empty; after fifth char '1' -> empty; after sixth char '1' -> empty. So we get ["", "", "0", "", "", ""]. Filtering out empties gives ["0"]. So gap length 1. Works. But careful: If there are multiple gaps, e.g., "10101". strip('0')? Actually "10101" has no leading/trailing zeros? It starts and ends with 1, so strip('0') does nothing. Then split('1') yields ["", "0", "0", ""]? Actually "10101": split on '1' yields: after first 1 -> ""; between 1 and 0? Actually split divides by delimiter. The string "1 0 1 0 1". Splitting on '1' gives: before first 1: '' (if starts with delimiter), then between first and second 1: "0", between second and third 1: "0", after last 1: "". So we get ["", "0", "0", ""] -> gaps ["0","0"] lengths 1 each. So that works. This method may be simpler: compute gaps = [len(block) for block in s.strip('0').split('1') if block != '']? Actually we need blocks of zeros that are between ones, which are exactly the non-empty strings after splitting on '1' of the stripped string. However, careful: If there are consecutive ones, split yields empty strings, but those correspond to no zeros. So we can just filter blocks with length>0. So we can compute:
stripped = s.strip('0')
if not stripped:
print(0)
continue
segments = stripped.count('1')? Actually number of segments equals number of groups of consecutive ones. That's not simply count('1') because there could be multiple ones in a segment. But we can count segments by counting occurrences of "01" or something. But easier: we already have number of segments = len(stripped.split('0')) after removing empty? Actually stripped consists of ones and zeros. Splitting on '0' yields blocks of ones. So segments = len([block for block in stripped.split('0') if block != '']) . But we can also compute segments by counting transitions or by the number of blocks of ones in original string. Simpler to compute during iteration.
But to simplify: we can get gaps from stripped.split('1') filtered, and number of segments can be computed as stripped.count('1')? Not exactly, because consecutive ones would count multiple ones but still one segment. But we can compute segments = len(stripped.replace('0', ' ').split()) something like that. However, it's easier to just use the iterative method, which is straightforward and O(n). So I'll stick with iterative.
Now, consider performance: t up to 1e5, total length 1e5, so many test cases may have very short strings. Iterative is fine.
Now, final code.
But there is one more nuance: In the problem statement, it says "the sum of the string lengths for all test cases does not exceed 10^5". So overall O(total length) is fine.
Thus we will implement.
Now, before finalizing, consider another viewpoint: Could there be an alternative strategy of not activating any mine, but using placement to cover? No.
Now, we will produce final answer.
But wait, I've seen a Codeforces problem "Minesweeper" where the answer is something like: answer = a * number_of_components + min(a, b) * (something). But not.
Now, let's double-check with some random tests using brute force for small n to confirm our greedy is optimal. But I'm confident.
However, there might be a catch: The sapper can also place mines after some activations, but we argued it's not beneficial. But could there be a scenario where we place a mine, manually activate it, and that explosion triggers only one side because the other side is not yet present? That doesn't help.
Now, let's think about an unusual scenario: a is very high, b is low, but the string has many gaps. Suppose we have segments spaced out: 1, 100, 200. Gaps: 98? Actually between 1 and 100, zeros count = 98? If positions: 1 is mine, then positions 2-99 zeros, 100 mine. So gap length = 98. If a=1000, b=1, then bgap=98 <1000, so fill. But after filling, we have a huge continuous segment from 1 to 100. Then next gap between 100 and 200 is 99 zeros, bgap=99 <1000, so fill. Then we pay a + b*(98+99)=1000+197=1197. Without filling, cost = 3*1000 = 3000. So huge saving. So greedy works.
Now, what about scenario where there are many small segments separated by length-1 gaps? If a=3, b=2, and each gap length=1, then bgap=2 <3, so fill each gap, merging all into one. So cost = a + bsum(gaps). If there are many segments, sum(gaps) might be large but each gap is small. If sum(gaps) is huge, maybe a + bsum(gaps) could exceed asegments? Let's test: 100 segments, 99 gaps each length 1. a=3, b=2. asegments=300. a + bsum(gaps)=3+2*99=3+198=201, which is less. So merging beneficial. If b=2, a=3, always beneficial for gap length 1. So good.
Now, if b=3, a=4, gap length=1: 3<4 beneficial.
Now, if b=4, a=3, gap length=1: 4<3 false, not beneficial.
So the greedy rule is consistent.
Thus final answer.
Now, I'm going to produce the final solution in code.
But I also want to think about potential overflow of intermediate values: Not an issue.
Now, implement.
One more nuance: The problem statement might have the possibility of not having to manually activate a segment if it gets activated by a neighboring explosion from a placed mine that is not manually activated? But any explosion must start from a manually activated mine. So we always need at least one manual activation per connected component.
Thus everything fine.
Now, let's produce final answer.
But wait: The sample input includes a newline after the number of test cases? Not an issue.
Now, code:
import sys
def min_coins(a, b, s):
n = len(s)
i = 0
segments = 0
total = 0
# Actually we can compute baseline and adjust.
# We'll collect gaps.
gaps = []
while i < n:
if s[i] == '1':
segments += 1
# skip consecutive ones
while i < n and s[i] == '1':
i += 1
# count zeros
start = i
while i < n and s[i] == '0':
i += 1
zero_len = i - start
# if there is a '1' after these zeros, it's a gap
if i < n and s[i] == '1':
gaps.append(zero_len)
# continue; i now points to a '1' or end
else:
i += 1
if segments == 0:
return 0
total = a * segments
for g in gaps:
if b * g < a:
total += b * g - a
return total
def main():
import sys
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
a = int(next(it)); b = int(next(it))
s = next(it)
out.append(str(min_coins(a, b, s)))
sys.stdout.write("\n".join(out))
if name == "main":
main()
That should work.
But we should test with some cases.
Test 1: t=1, a=5 b=1 s=0 -> output 0.
Test 2: a=5 b=1 s=1 -> output 5.
Test 3: a=5 b=1 s=101 -> gaps length=1 => bg=1<5, so total = 52 + (1-5)=10-4=6? Actually baseline 10, adjustment -4 => 6. So cost 6. But is that correct? Two segments (at positions1 and3). Fill gap of length1 (place mine at pos2) cost1, then one activation cost5 => total6. Yes.
Now, test 4: a=5 b=10 s=101 -> gap length=1, bg=10 >5, not fill, cost = 52 =10. So output 10.
Now, test 5: a=5 b=5 s=101 -> gap length=1, b*g=5, not less, not fill, cost=10. (But could fill, cost=5+5=10, same). So output 10, fine.
Now, test 6: a=5 b=5 s=10001 -> gaps length=3, b*g=15 >5, not fill, cost=10. Fill would be 5+15=20, worse.
Now, test 7: a=5 b=1 s=10001 -> gap length=3, b*g=3<5, fill, cost=5+3=8. Output 8.
Now, test 8: a=5 b=1 s=10010001 -> gaps:2 and 3; both >? 2*1=2<5 fill? Actually 2<5 yes fill; 3<5 fill; cost =5+5=10? Wait segments=3 baseline=15; fill both: components=1, cost=5 + (2+3)*1=5+5=10. So output 10. Without fill:15.
But earlier we computed that for a=5,b=1, gaps 2 and 3, fill both cost=10. That seems correct. Check manually: place mines in gaps (positions2-3 and 5-7?), actually original: 1 at pos1, pos4, pos8. To connect all, fill positions2,3,5,6,7? Wait gap1 between pos1 and pos4: zeros at pos2,3 => fill both. Gap2 between pos4 and pos8: zeros at pos5,6,7 => fill three. So total placed 5 mines, cost5. Then activate any mine cost5 => total10.
Thus fine.
Now, test 9: a=5 b=2 s=10010001 -> gaps:2-> bg=4<5 fill? Actually 4<5 => fill; gap2:32=6>5 not fill. So fill only first gap. Cost = a*(3-1)+b2 = 52+4=10+4=14? Wait components: originally3, fill one gap => components=2, activation cost =52=10, plus placement cost=22=4 => total14. Baseline=15, so 14. Output should be 14. Compute with formula: baseline 15, gap1 4-5=-1 => total14; gap2 not fill. So 14.
Now, manual: place mines at positions2,3 (cost 4), now we have mines at pos1,2,3,4? Actually original mines at pos1 and pos4, placed at pos2,3 => now segment from pos1 to pos4 continuous, plus separate mine at pos8. So two components. Activate each component: cost5 each =>10, plus placement4 => total14. Yes.
Now, verify with code.
Thus solution passes.
Now, I will finalize.
But before final answer, let's consider if there is any possibility to not activate any mine if we place a mine and then manually activate it, causing chain reaction that clears everything? That still requires activation.
Thus final.
Now, I'll write the final answer. ```python
import sys
def solve():
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
a = int(next(it))
b = int(next(it))
s = next(it)
n = len(s)
i = 0
segments = 0 # number of contiguous groups of '1'
gaps = [] # lengths of zero runs between groups
while i < n:
if s[i] == '1':
segments += 1
# skip the whole block of '1'
while i < n and s[i] == '1':
i += 1
# count zeros after the block
start = i
while i < n and s[i] == '0':
i += 1
zero_len = i - start
# if these zeros are followed by a '1', it's a gap between segments
if i < n and s[i] == '1':
gaps.append(zero_len)
# i now points to the next '1' or is past the end
else:
i += 1
code
if segments == 0:
out.append('0')
continue
total = a * segments
for g in gaps:
if b * g < a: # filling this gap reduces total cost
total += b * g - a # save a, pay b*g
out.append(str(total))
sys.stdout.write('\n'.join(out))