题解:at_abc391_e Hierarchical Majority Vote
对于一个长度为
- 对于
,令 为 、 、 中出现次数最多的字符。
现给定一个长度为
请求出最少改变
思维好题,把每次操作后的数提取出来,可以得到一个三叉树(注意是从下往上操作的)

我们层层追溯。例如,在上图中,想要根节点改变,我们就要他子节点中为
想到可以搜索或 dp,但看到
我们在搜索的过程本质上是区间操作,考虑搜索参数为区间 void dfs(int l, int r)
发现三位数只有
if (cnt[1] == 3) {
int ts[] = {x.cost, y.cost, z.cost}
sort(ts, ts + 3);
return make_pair(0, ts[0] + ts[1]); //最小的两个
}
当他们为
if (cnt[1] == 2) {
if (x.val == 1) ans = min(ans, x.cost);
if (y.val == 1) ans = min(ans, y.cost);
if (z.val == 1) ans = min(ans, z.cost);
return make_pair(0, ans);
}
在开始前,需要先求出子节点的最小代价,在
递归即可:
Node x = dfs(l, l + (r - l + 1) / 3 - 1), y = dfs(l + (r - l + 1) / 3, l + (r - l + 1) / 3 * 2 - 1), z = dfs(l + (r - l + 1) / 3 * 2, r);
完整代码:
// [ABC391E] Hierarchical Majority Vote
// by Pdise
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
#define mkpr make_pair
const int N = 1e5 + 10;
const int INF = 0x7fffffff;
string s;
int n;
PII dfs(int l, int r) {
// cerr << l << " " << r << "\n";
if (l == r) return mkpr(s[l - 1] - '0', 1);
PII x = dfs(l, l + (r - l + 1) / 3 - 1), y = dfs(l + (r - l + 1) / 3, l + (r - l + 1) / 3 * 2 - 1), z = dfs(l + (r - l + 1) / 3 * 2, r);
int cnt[2] = {0, 0};
cnt[x.first] ++, cnt[y.first] ++, cnt[z.first] ++;
// 1 0 0, 1 1 0, 1 1 1, 0 0 0
if (cnt[1] == 3) { // 1 1 1 0
int ts[] = {x.second, y.second, z.second};
sort(ts, ts + 3);
return mkpr(1, ts[0] + ts[1]);
}else if (cnt[0] == 3) { // 0 0 0 1
int ts[] = {x.second, y.second, z.second};
sort(ts, ts + 3);
return mkpr(0, ts[0] + ts[1]);
}else if (cnt[1] == 2) { // 1 1 0 0
int ans = INF - 1;
if (x.first == 1) ans = min(ans, x.second);
if (y.first == 1) ans = min(ans, y.second);
if (z.first == 1) ans = min(ans, z.second);
return mkpr(1, ans);
}else { //0 0 1 1
int ans = INF - 1;
if (x.first == 0) ans = min(ans, x.second);
if (y.first == 0) ans = min(ans, y.second);
if (z.first == 0) ans = min(ans, z.second);
return mkpr(0, ans);
}
}
int main() {
ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
cin >> n;
cin >> s;
cout << dfs(1, (int)s.size()).second << "\n";
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】