CodeForces 1860D Balanced String

发布时间 2023-08-19 07:29:49作者: zltzlt

洛谷传送门

CF 传送门

首先考虑一个子问题,给两个只含有 \(0\)\(1\) 的字符串 \(s, t\),求至少要使用多少次交换 \(t\) 的任意两个字符的操作,使得 \(s\)\(t\) 相等,或报告无解。

显然无解情况就是两个串 \(0\)\(1\) 的出现次数不同。接下来我们排除相等的位置,设还剩 \(k\)\(s_i = \texttt{0}, t_i = \texttt{1}\) 的位置和 \(k\)\(s_i = \texttt{1}, t_i = \texttt{0}\) 的位置,每次选择一对 \((0, 1)\) 交换,答案就是 \(k\)

回到原题,发现 \(n \le 100\),那不就直接把题面中乱七八糟的条件塞进 dp 状态吗。设 \(f_{i, j, k}\)\(t\) 中填完 \([1, i]\),填了 \(j\)\(0\),当前 \(\texttt{01}\) 子序列个数减去 \(\texttt{10}\) 子序列个数 \(= k\)\(t\)\(s\) 不相等的位置个数的最小值。转移就枚举第 \(i\) 个位置填 \(0\) 还是 \(1\),如果填 \(0\),那么 \(k\) 加上 \([1, i - 1]\)\(0\) 的个数,否则 \(k\) 减去 \([1, i - 1]\)\(1\) 的个数。

时间复杂度 \(O(n^4)\)

code
// Problem: D. Balanced String
// Contest: Codeforces - Educational Codeforces Round 153 (Rated for Div. 2)
// URL: https://codeforces.com/contest/1860/problem/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define mems(a, x) memset((a), (x), sizeof(a))

using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;

const int maxn = 110;
const int K = 12000;

int n, f[2][maxn][maxn * maxn * 2];
char s[maxn];

inline void upd(int &x, int y) {
	(x > y) && (x = y);
}

void solve() {
	scanf("%s", s + 1);
	n = strlen(s + 1);
	int c0 = 0, c1 = 0;
	for (int i = 1; i <= n; ++i) {
		c0 += (s[i] == '0');
		c1 += (s[i] == '1');
	}
	mems(f, 0x3f);
	f[0][0][K] = 0;
	for (int i = 1, o = 1; i <= n; ++i, o ^= 1) {
		mems(f[o], 0x3f);
		for (int j = 0; j <= i; ++j) {
			int k = i - j - 1;
			for (int p = -(n * n); p <= n * n; ++p) {
				if (f[o ^ 1][j][p + K] > 1e9) {
					continue;
				}
				upd(f[o][j + 1][p - k + K], f[o ^ 1][j][p + K] + (s[i] != '0'));
				upd(f[o][j][p + j + K], f[o ^ 1][j][p + K] + (s[i] != '1'));
			}
		}
	}
	printf("%d\n", f[n & 1][c0][K] / 2);
}

int main() {
	int T = 1;
	// scanf("%d", &T);
	while (T--) {
		solve();
	}
	return 0;
}