题目
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≤105) — 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 105.
Output
For each test case, output one integer — the minimum number of coins that the sapper will have to pay.
题意:
有个01字符串,1表示炸点,每次可以花费a点燃一个炸弹,但是炸弹具有连锁反应,与它相邻的炸弹也会爆炸;当然,你也可以花费b来安放一个炸弹,求最终消除所有炸弹所需要的最小花费
题解:
贪心:有两个炸弹区间的时候,我们有两种操作
1、直接引爆两个区间
2、填起来区间,然后引爆一次
AC代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
int t; cin >> t;
while (t--) {
int a, b; cin >> a >> b;
string str; cin >> str;
int len = str.length();
int ans = 0, p = -1;
for (int i = 0; i < len; i++) {
if (str[i] == '1') {
if (p != -1 && (i - p - 1) * b < a)
ans += (i - p - 1) * b;
else
ans += a; // 直接点燃
while (i < len && str[i] != '0')
i++;
p = i - 1;
}
}
cout << ans << endl;
}
return 0;
}