最大团问题

问题 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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值