给我们一些01串,有两种操作,把一段字串反转,代价为x,或者把一段字串每个取反,代价为y
我们发现,要把所有字符都变成 1,我们至少用一次取反操作,最多用n-1次取反操作(n代表全为0的块的个数)。
我的思路取反不会去把1变成0,没啥意义,那么我们每用一次反转操作,就可以将两个全为0的块合并为1个。
那么可以发现,假设操作1的次数为a,操作2的次数为b,那么答案就为 a * y + b * (x - y),可以发现,我们求的最小的代价只会有两种情况,要么 x 比 y 大,要么 x 比 y 小。所以答案为,当 x >= y 的时候 为n * y 如果 x < y 的时候,(n -1 ) * x + y
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e6 + 10;
char s[maxn],str[maxn];
int main(){
LL n,x,y,p = 0;
scanf("%lld%lld%lld",&n,&x,&y);
scanf("%s",s);
str[p++] = s[0];
for (int i=1; i<n; i++) {
if (s[i] != str[p-1]) {
str[p++] = s[i];
}
}
LL cnt1 = 0,cnt2 = 0;
for (int i=0; i<p; i++) {
if (str[i] == '1') {
cnt1++;
}else{
cnt2++;
}
}
if (x >= y || cnt2 == 0) {
// cout << cnt2 * y << endl;
printf("%lld",cnt2 * y );
}else{
printf("%lld",(cnt2-1)*x + y);
}
return 0;
}