跳到正文

题解

Present

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

文章信息

发布
2026年3月21日
收录
2026年4月12日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
5
题目
P16278

版本

  1. v2当前
  2. v1

官方题解。

根据题意,s,s′s,s' 同构,当且仅当 ss 中相同的字符对应 s′s' 中相同的字符,ss 中不同的字符对应 s′s' 中不同的字符。

故可以直接枚举 s,s′s,s' 中字符的对应关系,即枚举 1010 个数字字符的全排列,这样便可以确定 s′s',然后暴力统计 s′,ts',t 中相同字符的对数。复杂度 O(w!⋅n)O(w! \cdot n),其中 ww 为字符种数。可以获得 6060 分。

容易发现统计时有大量重复。考虑将所有 (si,ti)(s_i,t_i) 扔进一个桶 cc,则 ss 中的每种字符 xx 产生的贡献即为 cx,pxc_{x,p_x},其中 pxp_x 为 xx 对应的字符。这样便可以 O(w)O(w) 地统计了。复杂度 O(w!⋅w+n)O(w! \cdot w+n),可以通过。

Bonus

若允许使用提高级算法,则本题可使用状压 dp 做到 O(2w⋅w+n)O(2^w \cdot w+n)。若允许使用 NOI 级算法,则本题就是【模板】二分图最大权完美匹配,可使用 KM 算法做到 O(w3)O(w^3)。

实现
C++
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10;
int cnt[MAXN][MAXN], p[MAXN], n, ans;
bool vis[MAXN];
string s, t;
void dfs(int step){
	if (step > 9){
        int tot = 0;
		for (int i = 0; i <= 9; i++){
            tot += cnt[i][p[i]];
        }
        ans = max(ans, tot);
		return;
	}
	for (int i = 0; i <= 9; i++){
		if (vis[i]){
			continue;
		}
		vis[i] = true;
		p[step] = i;
		dfs(step + 1);
		vis[i] = false;
	}
	return;
}
void solve(){
	memset(cnt, 0, sizeof(cnt));
	cin >> n >> s >> t;
	for (int i = 0; i < n; i++){
		cnt[s[i] - '0'][t[i] - '0']++;
	}
	ans = 0;
	dfs(0);
	cout << ans << endl;
	return;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int T;
	cin >> T;
	while (T--){
		solve();
	}
	return 0;
}
原文