Present

· · 题解

官方题解。

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

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

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

:::info[Bonus]{open}

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

:::

:::success[实现]{open}

#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;
}

:::