题解:P16278 「MierOI R1」Present

· · 题解

题目传送门

题面分析

注意到对于任意 1 \le i,j \le m,若 s_i=s_j,则 s'_i=s'_j,否则 s'_i \ne s'_j。所以 s' 可以看作将 s 中不同的数字对应替换成另一个数字或不变得到的,我们需要求 s' 和 t 最多有多少对相同的数字。

思路

我们可以先枚举将 s 中的每一个数字替换为另一个数字后会与 t 产生多少对相同数字,然后再 DFS 一下每一个数字替换为哪个数字,在所有方案中取最大值,输出即可。

复杂度 O(10! \times T+100 \times Tn)。

代码

#include <bits/stdc++.h>
using namespace std;
int a[10][10],b[10];
string s,t;
int T,n,sum;
void dfs(int x,int v)//DFS 替换方案,当前枚举到 x 替换为哪个数字,对数和为 v
{
    if(x>9)
    {
        sum=max(sum,v);//取对数的最大值
        return;
    }
    for(int i=0;i<=9;i++)
    {
        if(b[i]==1)
        {
            continue;
        }
        b[i]=1;//打标记
        dfs(x+1,v+a[x][i]);
        b[i]=0;//注意要还原
    }
    return;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>T;
    for(int i=1;i<=T;i++)
    {
        cin>>n;
        cin>>s>>t;
        for(int j=0;j<=9;j++)
        {
            for(int k=0;k<=9;k++)//枚举将 s 中的数字 j 替换为数字 k 后会与 t 产生多少对相同数字
            {
                a[j][k]=0;
                for(int o=0;o<n;o++)
                {
                    if((s[o]==char(j+'0'))&&(t[o]==char(k+'0')))
                    {
                        a[j][k]++;
                    }
                }
            }
        }
        sum=0;
        dfs(0,0);
        cout<<sum<<'\n';
    }
    return 0;
}