官方题解。
根据题意, 同构,当且仅当 中相同的字符对应 中相同的字符, 中不同的字符对应 中不同的字符。
故可以直接枚举 中字符的对应关系,即枚举 个数字字符的全排列,这样便可以确定 ,然后暴力统计 中相同字符的对数。复杂度 ,其中 为字符种数。可以获得 分。
容易发现统计时有大量重复。考虑将所有 扔进一个桶 ,则 中的每种字符 产生的贡献即为 ,其中 为 对应的字符。这样便可以 地统计了。复杂度 ,可以通过。
Bonus
若允许使用提高级算法,则本题可使用状压 dp 做到 。若允许使用 NOI 级算法,则本题就是【模板】二分图最大权完美匹配,可使用 KM 算法做到 。
实现
#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;
}