跳到正文

题解

题解:AT_abc197_f [ABC197F] Construct a Palindrome

lw393约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年2月8日
更新
2026年2月8日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

我错了,不是现在 ABC 水,是 ABC 都水。

发现 N,MN,M 都很小。考虑不那么直接的暴力。

我们想要它是回文,就转换成从 11 出发到一个点 XX,和从 nn 出发到一个点 XX 的路径上字符拼接而成的字符串相同或者是是 11 到 XX 与 nn 到 YY 的字符串相同,且 (X,Y)(X,Y) 存在边。

那我们就可以设 d(S,T)d(S,T) 表示 11 到 SS,nn 到 TT 的路径上字符串相同的最小代价。这个直接做 BFS 可以得到。

剩下就是时间复杂度分析了。

我们对于一个状态 (x,y)(x,y),其后继状态应当为 deg(x)×deg(y)deg(x)\times deg(y),我们对每个状态都应当枚举其所有后继状态,所以枚举后继状态是 ∑x∑ydeg(x)×deg(y)=4m2\sum_{x}\sum_{y}deg(x)\times deg(y)=4m^2。状态数是 n2n^2 个。

所以总复杂度做到 O(m2+n2)O(m^2 + n^2)。

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long

void solve() {
	int n, m; cin >> n >> m;
	vector<vector<vector<int> > > G(n + 1, vector<vector<int> >(26));
	for(int i = 1; i <= m; i++) {
		int u, v; char c;
		cin >> u >> v >> c;
		G[u][c - 'a'].push_back(v), G[v][c - 'a'].push_back(u);
	}
	queue<pair<int, int> > q; map<pair<int, int>, int> dis;
	q.push({1, n}); dis[{1, n}] = 0;
	while(!q.empty()) {
		auto [s, t] = q.front(); q.pop();
		for(int i = 0; i < 26; i++)
			for(auto sv : G[s][i])
				for(auto tv : G[t][i])
					if(!dis.count({sv, tv}))
						dis[{sv, tv}] = dis[{s, t}] + 2, q.push({sv, tv});
	}
	int ans = 0x3f3f3f3f;
	for(int i = 1; i <= n; i++)
		if(dis.count({i, i})) ans = min(ans, dis[{i, i}]);
	for(int u = 1; u <= n; u++)
		for(int i = 0; i < 26; i++)
			for(auto v : G[u][i])
				if(dis.count({u, v})) ans = min(ans, dis[{u, v}] + 1);
	if(ans != 0x3f3f3f3f) cout << ans << '\n';
	else cout << -1 << '\n';
}

signed main() {
	ios::sync_with_stdio(false);
	ios_base::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	// For Problem with file IO
	// #ifndef CPH
	//   freopen(".in", "r", stdin);
	//   freopen(".out", "w", stdout);
	// #endif
	int t = 1;
	// cin >> t;
	while(t--) {
		solve();
	}
	return 0;
}
原文