[B. Saving the City
Codeforces Round #681 (Div. 2, based on VK Cup 2019-2020 - Final)](https://codeforces.ml/problemset/problem/1443/B)
题意:给你一栋n层的楼,某些楼层装有炸弹,炸弹爆炸后相邻楼层的炸弹也会爆炸。
有两种操作:
- 引爆某层楼的炸弹(消耗a费)
- 在任意一层添加炸弹(消耗b费)
样例输入:
2
1 1
01000010
5 1
01101110
样例输出:
2
6
解题思路:贪心,连续的1可以引爆并且只消耗a费,两端连续1之间有x个0(添加x个炸弹)可以减少a费,增加xb。我们只需比较a和xb的大小,贪心取最小值。
注意:这道题要特别当心边界情况,刚开始wa了好多发。
下面是简化过的ac代码:
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<set>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<string.h>
#include<string>
#include<math.h>
#define INF 0x7fffffff
#define IOS; {ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);}
#define debug(x) {cout<<"<<<<"<<(x)<<endl;}
const int N = 1e5+5;
typedef long long ll;
using namespace std;
void solve()
{
int a,b;
string s;
int len;
int cnt0=0;
ll ans=0;
cin>>a>>b>>s;
len = s.size();
cnt0 = ans = 0;
bool flag = 1;
int i = 0;
while(i<len && s[i]=='0')++i;
for(;i < len;++i){
if(s[i] == '0'){
++cnt0;
}
else
{
if(flag)ans = a,flag = 0;
else ans += min(a,cnt0*b);
cnt0 = 0;
}
}
cout<<ans<<endl;
}
int main() {
IOS;
int t;cin>>t;
while(t--)
solve();
return 0;
}