题意:给你一个二进制的01字符串,让我们定义这个二进制字符串的结果为的所有十进制数之和。
例如:S=1011;
他的所有结果为"10"+"01"+"11"=22.
现在给你m个操作数,每次操作可以交换任意两个相邻的字符串,问你经过小于等于的m任意次交换,S的最小的结果会是多少?
思路:通过样例2和样例3我们可以发现,如果交换不换到最后一位或者第一位的话,其结果是不会改变的,因为对于每一个'1',只要他不在第一位和最后一位,那么他一定会前面加1后面加10.
把1换到最后一位会少10,把一换到第一位会少1,那么我们就先尽可能的把1换到最后一位,如果可以就再考虑换到第一个,换完后直接暴力搜一遍结果就好了。
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#define sc_int(x) scanf("%d", &x)
#define sc_ll(x) scanf("%lld", &x)
#define pr_ll(x) printf("%lld", x)
#define pr_ll_n(x) printf("%lld\n", x)
#define pr_int_n(x) printf("%d\n", x)
#define ll long long
using namespace std;
const int N = 1000000 + 100;
int n, m, h;
char s[N];
int cal(int i, int j)
{
int res = 0;
if (s[i] == '1')
res += 10;
if (s[j] == '1')
res++;
return res;
}
int main()
{
int t;
sc_int(t);
while (t--)
{
cin >> n >> m >> s + 1;
int l = 0, r = 0;
for (int i = 1; i <= n; i++)
{
if (s[i] == '1')
{
if (!l)
l = i;
else
r = i; //找最小的和最长的1
}
}
if (!r) //如果只有一个1
{
if (n - l <= m)
swap(s[l], s[n]);
else if (l - 1 <= m)
swap(s[1], s[l]);
}
else
{ //有两个及以上
if (n - r <= m)
{
swap(s[r], s[n]);
m -= (n - r);
}
if (l - 1 <= m)
swap(s[1], s[l]);
}
int res = 0;
for (int i = 1; i < n; i++)
res += cal(i, i + 1);
cout << res << endl;
}
return 0;
}
本文探讨了一道关于二进制字符串的操作题,目标是最小化由字符串转换得到的十进制数之和。通过分析发现,将1尽可能移至字符串末尾能够有效减少结果值。文章提供了一个C++实现方案。
529

被折叠的 条评论
为什么被折叠?



