Codeforces Round #821 (Div. 2) - D2. Zero-One (Hard Version)
区间DP
题意
给一个长度为 的 01串,每次操作可选择一个 , 把 反转。如果 , 花费为 x,否则为 y
求把所有的 1 变成 0 的最小代价
思路
-
根据 D1 的提示,要分类讨论,当 x >= y 时很容易贪心求解
-
当 x < y 时,结合数据范围,可以尝试区间dp
-
可以先把每个 1 的位置记下来,存到 数组中,设共有 m 个 1 (m为偶数,奇数直接返回-1)
-
记 为将第 个 1 到第 个 1 全部清零,有三种策略
这里 必定至少结合一组,因为如果都与不相邻的结合,不管用哪种操作都没有与更近的结合更优(因为x<y)
-
记忆化搜索即可
代码
#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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!