Codeforces Round #821 (Div. 2) - D2. Zero-One (Hard Version)

区间DP

Problem - D2 - Codeforces

题意

给一个长度为 \(n(5<=n<=5000)\) 的 01串,每次操作可选择一个 \(l,r(l<r)\), 把 \(s[l],s[r]\) 反转。如果 \(l+1==r\), 花费为 x,否则为 y

求把所有的 1 变成 0 的最小代价

思路

  1. 根据 D1 的提示,要分类讨论,当 x >= y 时很容易贪心求解

  2. 当 x < y 时,结合数据范围,可以尝试区间dp

  3. 可以先把每个 1 的位置记下来,存到 \(pos\) 数组中,设共有 m 个 1 (m为偶数,奇数直接返回-1)

  4. \(f[l][r]\) 为将第 \(l\) 个 1 到第 \(r\) 个 1 全部清零,有三种策略

    1. \(cost(l,l+1)+f[l+2][r]\)
    2. \(cost(r-1,r)+f[l][r-2]\)
    3. \(cost(l,r)+f[l+1][r-1]\)

    这里 \((l,l+1)与(r-1,r)\) 必定至少结合一组,因为如果都与不相邻的结合,不管用哪种操作都没有与更近的结合更优(因为x<y)

  5. 记忆化搜索即可

代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>

using namespace std;
#define endl "\n"

typedef long long ll;
typedef pair<int, int> PII;

const int N = 5e3 + 10;
int n;
ll x, y;
string s;
int a[N], b[N], c[N];
int d[3];
ll f[N][N];
vector<int> pos;
ll dfs(int l, int r)
{
	if (l > r)
		return 0;
	if (f[l][r] != -1)
		return f[l][r];
	ll ans1 = dfs(l + 2, r) + min(y, (pos[l+1] - pos[l]) * x);
	ll ans2 = dfs(l, r - 2) + min(y, (pos[r] - pos[r-1]) * x);
	ll ans3 = dfs(l + 1, r - 1) + min(y, (pos[r] - pos[l]) * x);
	return f[l][r] = min({ans1, ans2, ans3});
}
ll solve()
{
	int cnt = 0;
	for (int i = 1; i <= n; i++)
		cnt += c[i];
	if (cnt & 1)
		return -1;
	if (x >= y)
	{
		if (cnt != 2)
			return cnt / 2 * y;
		int t = 0;
		for (int i = 1; i <= n; i++)
			if (c[i] == 1)
				d[++t] = i;
		if (d[1] + 1 == d[2])
			return min(x, 2 * y);
		return y;
	}
	pos.clear();
	pos.push_back(-1);
	for (int i = 1; i <= n; i++)
		if (c[i] == 1)
			pos.push_back(i);
	int m = pos.size() - 1;
	for (int i = 0; i <= m; i++)
		for (int j = 0; j <= m; j++)
			f[i][j] = -1;
	return dfs(1, m);
}
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int T;
	cin >> T;
	while(T--)
	{
		cin >> n >> x >> y;
		cin >> s;
		s = " " + s;
		for (int i = 1; i <= n; i++)
			a[i] = s[i] - '0';
		cin >> s;
		s = " " + s;
		for (int i = 1; i <= n; i++)
			b[i] = s[i] - '0';
		for (int i = 1; i <= n; i++)
			c[i] = a[i] ^ b[i];
		cout << solve() << endl;
	}
    return 0;
}
posted @ 2022-09-20 23:59  hzy0227  阅读(164)  评论(0编辑  收藏  举报