Description
给一个长度为n(n <= 10^5)的“01”串,你可以任意交换一个为0的位和一个为1的位,若这两位相邻,花费为X,否则花费为Y。求通过若干次交换后将串中的“1”全部变换到“0”前面的最小花费。
Input
第一行一个整数T(1 <= T <= 10),表示测试数据的组数。接下来3*T行,每组数据三行,第一行为整数X(1 <= X <= 10^3),第二行为整数Y(X <= Y <= 10^3),第三行是“01”串。
Output
最小花费。
Sample Input
2121100120011
Sample Output
03
思路:最后面的1先和最前面的0交换
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cmath>
#include<queue>
using namespace std;
struct node{
int x;
bool operator < (const node &a) const {
return x>a.x;//最小值优先
}
};
struct node2{
int x;
bool operator < (const node2 &a) const {
return x<a.x;//最大值优先
}
};
priority_queue<node2>que_1; //最大优先级队列
priority_queue<node>que_0; //最小优先级队列
char str[100000+50];
int main(){
int t,x,y;
scanf("%d",&t);
node temp;
node2 temp_1;
while(t--){
scanf("%d %d",&x, &y);
scanf("%s",str);
while(!que_0.empty()) que_0.pop();
while(!que_1.empty()) que_1.pop();
for(int i = 0; str[i] ; i++){
if(str[i] == '0'){
temp.x = i;
que_0.push(temp);
}
else {
temp_1.x = i;
que_1.push(temp_1);
}
}
long long ans = 0;
while(!que_1.empty()){
if(que_1.top().x > que_0.top().x){
ans+=min(x*(que_1.top().x-que_0.top().x),y);
temp.x = que_1.top().x;
que_0.push(temp);
que_0.pop();
}
que_1.pop();
}
printf("%I64d\n",ans);
}
return 0;
}