Kattis - codenames

本文针对 Kattis-codenames 编程挑战题进行了解析,该题要求找出一组单词中最大的‘交换自由’子集大小。通过构建图模型并使用匈牙利算法来寻找最大匹配,进而得到最大的独立集。代码实现利用了 C++,包括输入处理、图的构建以及匹配查找等关键步骤。

Kattis - codenames


题目:
You are given W, a set of N words that are anagrams of each other. There are no duplicate letters in any word. A set of words SW is called “swap-free” if there is no way to turn a word xS into another word yS by swapping only a single pair of (not necessarily adjacent) letters in x. Find the size of the largest swap-free set S chosen from the given set W.

Input
The first line of input contains an integer N
(1≤N≤500). Following that are N lines each with a single word. Every word contains only lowercase English letters and no duplicate letters. All N words are unique, have at least one letter, and every word is an anagram of every other word.

Output
Output the size of the largest swap-free set.

Sample Input 1
6
abc
acb
cab
cba
bac
bca
Sample Output 1
3

Sample Input 2
11
alerts
alters
artels
estral
laster
ratels
salter
slater
staler
stelar
talers
Sample Output 2
8

Sample Input 3
6
ates
east
eats
etas
sate
teas
Sample Output 3
4

匈牙利算法求最大匹配从而得出最大独立集

代码

#include <iostream>
#include<bits/stdc++.h>
#define ll long long
const int N = 1111;
using namespace std;

int n;
vector<int>mp[N];
char s[N][N];
int a[N];
int vis[N];

int Find(int x)
{
    for(int i=0; i<(int)mp[x].size(); i++)
    {
        if(!vis[mp[x][i]])
        {
            vis[mp[x][i]]=1;
            if(!a[mp[x][i]]||Find(a[mp[x][i]]))
            {
                a[mp[x][i]]=x;
                return 1;
            }
        }
    }
    return 0;
}

void solve(){
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>s[i];
    }
    int l=strlen(s[1]);
    for(int i=1; i<=n; i++)
    {
        for(int j=i+1; j<=n; j++)
        {
            int num=0;
            for(int k=0; k<l; k++)
            {
                if(s[i][k]!=s[j][k])
                    num++;
                if(num>2)
                    break;
            }
            if(num==2)
            {
                mp[i].push_back(j);
                mp[j].push_back(i);
            }
        }
    }
    int cnt=0;
    for(int i=1; i<=n; i++)
    {
        memset(vis,0,sizeof(vis));
        if(Find(i))
            cnt++;
    }
    cout<<n-cnt/2<<endl;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值