题意:现有一种操作,能使字母c1变成c2,还有两个字符串,问你最少要多少个(c1,c2)组合能把两个字符串变成一样。
思路:样例给我们的启示就是把所有的字母都变成一样的,这样两个字符串就一样了,我们需要的操作数是字母数量减一,但是如果只想到这一点并不全对,因为还有这样的样例:
3
ab
cd
按照上面的方法我们得到的结果是3,但是最优解一眼就可以看出来是2。
所以正确的思路是把对应位置不相同的字母看成之间有一条边(如果对应位置相同的字母不用管),这样两个字符串中所有的字母就构成了一个图,其中有很多联通块,把每个联通块按照上面说的方法,求出不同字母数量减一,总共的和就是答案。
我用的是并查集保存联通关系,用dfs也是可以的。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
char a[100010];
char b[100010];
int f[30];
int find(int x)
{
if(f[x] == x)
return f[x];
else
return f[x] = find(f[x]);
}
int main(void)
{
int n,i,j;
while(scanf("%d",&n)==1)
{
for(i=0;i<26;i++)
f[i] = i;
scanf("%s%s",a,b);
for(i=0;i<n;i++)
{
if(a[i] == b[i])
continue;
int x = find(a[i]-'a');
int y = find(b[i]-'a');
if(x != y)
f[x] = y;
}
int ans = 0;
for(i=0;i<26;i++)
{
int cnt = 0;
for(j=0;j<26;j++)
{
if(find(j) == i)
cnt++;
}
if(cnt != 0)
ans += cnt-1;
}
printf("%d\n",ans);
for(i=0;i<26;i++)
{
if(i == find(i))
continue;
printf("%c %c\n",'a'+i,'a'+find(i));
}
}
return 0;
}