AtCoder Beginner Contest 393-D Swap to Gather题解
更好的阅读体验(大概吧
思路
考虑贪心,经过手玩样例发现,在
那么新的问题就来了,设目标位置为 abs(v[i] - (v[k] - (k - i))); (
代码
#include <bits/stdc++.h>
#define ll long long
#define N 500001
#define mod 998244353
#define all(a) a.begin(),a.end()
#define uniqueu(a) a.erase(unique(all(a)), a.end())
using namespace std;
mt19937_64 mrand(random_device{}());
int n;
string s;
int v[N], l;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> s;
bool ok = true;
for (int i = 0; i < n; i++) {
if (s[i] == '1' && (i == 0 || s[i - 1] == '0') && ok)
ok = false;
if (s[i] == '1' && s[i - 1] == '0' && !ok)
ok = true;
}
if (!ok) {
cout << "0\n";
return 0;
}
for (int i = 0; i < n; i++)
if (s[i] == '1')
v[++l] = i + 1;
int k = l / 2;
if (l % 2)
k++;
ll ans = 0;
for (int i = 1; i <= l; i++)
ans += abs(v[i] - (v[k] - (k - i)));
cout << ans << "\n";
}