CF18E Flag 2
小清新 dp 题。
有点像这道题。
Solution :
发现
定义
转移方程是
输出方案的话,直接按一般的套路递归找就可以了。
code
int n, m;
string s[N];
int f[N][26][26], cost[N][26][26];
void output(int x, int fst, int scd) {
if(!x) return;
int lst = f[x][fst][scd] - cost[x][fst][scd];
rep(i, 0, 25) rep(j, 0, 25) {
if(i == fst || j == scd || i == j) continue;
if(f[x - 1][i][j] == lst) {
output(x - 1, i, j);
goto ed;
}
}
ed:;
rep(i, 1, m)
if(i & 1) cout << (char)('a' + fst);
else cout << (char)('a' + scd);
cout << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> m;
rep(i, 1, n) cin >> s[i], s[i] = " " + s[i];
rep(i, 1, n) rep(j, 0, 25) rep(k, 0, 25) {
auto &v = cost[i][j][k];
rep(l, 1, m) {
if(l & 1) v += s[i][l] != 'a' + j;
else v += s[i][l] != 'a' + k;
}
}
memset(f, 0x3f, sizeof f);
rep(i, 0, 25) rep(j, 0, 25) f[0][i][j] = 0;
rep(i, 1, n) rep(j, 0, 25) rep(k, 0, 25) {
if(k == j) continue;
rep(fst, 0, 25) {
if(fst == j) continue;
rep(scd, 0, 25)
if(scd != k && scd != fst) {
f[i][j][k] = min(f[i][j][k], f[i - 1][fst][scd] + cost[i][j][k]);
}
}
}
int ans = INF, fst, scd;
rep(i, 0, 25) rep(j, 0, 25)
if(f[n][i][j] < ans) {
ans = f[n][i][j];
fst = i, scd = j;
}
cout << ans << '\n';
output(n, fst, scd);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现