问题 D: Swap Free
时间限制: 1 Sec 内存限制: 128 MB
题目描述
A set of words is called swap free if there is no way to turn any word in the set into any other word in the set by swapping only a single pair of (not necessarily adjacent) letters.
You are given a set of n words that are all anagrams of each other. There are no duplicate letters in any word. Find the size of the largest swap free subset of the given set. Note that it is possible for the largest swap free subset of the given set to be the set itself.
输入
The first line of input contains a single integer n ( 1 ≤ n ≤ 500 ).
Each of the next n lines contains a single word w ( 1 ≤ |w| ≤ 26 ).
Every word contains only lower-case letters and no duplicate letters. All n words are unique, and every word is an anagram of every other word.
输出
Output a single integer, which is the size of the largest swap free subset.
样例输入 Copy
【样例1】 6 abc acb cab cba bac bca 【样例2】 11 alerts alters artels estral laster ratels salter slater staler stelar talers 【样例3】 6 ates east eats etas sate teas
样例输出 Copy
【样例1】 3 【样例2】 8 【样例3】 4
二分图、最大匹配等相关定义的讲解
该题的参考链接
我们对于两个一次操作(交换两个不同位置)不能互相变换的串建边,那么答案就是这个图的最大团。
一个图的最大团等于这个图补图的最大独立集,那么我们要建这个图的补图。
这个图的补图就是对能够一次操作互相变换的两个串建边。
那么现在答案就是这个补图的最大独立集。
这个补图一定是一个二分图。
二分图的最大独立集等于图中点的个数 - 最大匹配数。
所以我们现在可以对这个二分图求一个最大匹配。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int n;
char s[505][50];
vector<int>ma[505];
int use[505];
int from[505];
int ans;
bool match(int x)///找最大匹配
{
int len=ma[x].size();
for(int i=0;i<len;i++)
{
if(!use[ma[x][i]])
{
use[ma[x][i]] = true;
if(from[ma[x][i]]==0||match(from[ma[x][i]]))
{
from[ma[x][i]] = x;
return true;
}
}
}
return false;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%s",s[i]);
}
int len=strlen(s[1]);// anagrams
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
int num=0;
for(int k=0;k<=len;k++)
{
if(s[i][k]!=s[j][k])
num++;
if(num>2)
break;
}
if(num==2)///只有两个交换
{
ma[i].push_back(j);
ma[j].push_back(i);
}
}
}
///二分图的最大独立集等于图中点的个数 - 最大匹配数。
ans=0;
for(int i=1;i<=n;i++)
{
memset(use,0,sizeof(use));
if(match(i)) ans++;
}
cout<<n-ans/2<<endl;
return 0;
}