题目链接:http://acm.fzu.edu.cn/problem.php?pid=2197
思路:如果用相邻法移动把所有的1移到前面,实则总步数是固定的,所以如果能换,就把最后的1和最前的0做交换,花费为min(y, 间距 * x),累加即可
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <climits>
#include <functional>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int maxn = 101000;
char s[maxn];
vector <int> pos;
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
pos.clear();
int x, y;
scanf("%d%d", &x, &y);
scanf("%s", s);
int len = strlen(s);
for (int i = len - 1; i >= 0; i--)
{
if (s[i] == '1')
pos.push_back(i);
}
long long ans = 0;
int cc = 0;
for (int i = 0; i < pos.size(); i++)
{
if (s[i] == '0')
{
ans += min((pos[cc++] - i) * x, y);
}
}
cout << ans << endl;
}
return 0;
}