跳到正文

题解

AtCoder Beginner Contest 393-D Swap to Gather题解

JettK约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年2月16日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟

版本

  1. v1当前

更好的阅读体验(大概吧

思路

考虑贪心,经过手玩样例发现,在 11 不是连续的情况下,11 的个数是奇数时,每个 11 都向中间的 11 的位置交换时最优。11 的个数是偶数时,每个 11 都向 11 的个数除 22 的那个 11 的所在位置交换更优。

那么新的问题就来了,设目标位置为 kk ,那么 ii 这个位置的 11 要换到那个位置呢?答案是:abs(v[i] - (v[k] - (k - i))); (vkv_k viv_i 表示 kk 和 ii 的位置)为什么呢?因为这个 ii 前面换了 k−ik - i 个 11,所以这次要换到 vkv_k 前第 k−ik - i 个位置。然后这题就做完了,记得要特判 11 最开始是不是连续的。

代码

C++
#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";
}
原文