Code Names(二分图的匹配)

Code Names

解题思路:该题求的是二分图最大独立集。

#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<ll,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 5e2+10;
const ull base = 131;
const ll mod =  1e9+7;
const double PI = acos(-1.0);
const double eps = 1e-4;

inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){str+=s;s=getchar();}return str;}
int random(int n){return (int)(rand()*rand())%n;}
void writestring(string s){int n = s.size();for(int i = 0;i < n;i++){printf("%c",s[i]);}}
ll fast_power(ll a,ll p){
    ll ans = 1;
    while(p){
        if(p&1) ans = (ans*a)%mod;
        p >>= 1;
        a = (a*a)%mod;
    }
    return ans;
}

string s[N];
vector<int>G[N];
int vis[N];
int match[N];

bool dfs(int u){
    for(int i = 0;i < G[u].size();i++){
        int v = G[u][i];
        if(vis[v]) continue;
        vis[v] = 1;
        if(!match[v]||dfs(match[v])){
            match[v] = u;
            return true;
        }
    }
    return false;
}
bool fun(string s,string t){
    int cnt = 0;
    for(int i = 0;i < s.size();i++){
        if(s[i] != t[i]) cnt++;
    }
    return cnt == 2;
}
int main(){
    srand((unsigned)time(NULL));
    //freopen(  "out.txt","w",stdout);
    int n = read();
    for(int i = 1;i <= n;i++){
        s[i] = readstring();
    }
    for(int i = 1;i <= n;i++){
        for(int j = i+1;j <= n;j++){
            if(fun(s[i],s[j])){
                //cout<<i<<" "<<j<<endl;
                G[i].push_back(j);
                G[j].push_back(i);
            }
        }
    }
    int cnt = 0;
    for(int i = 1;i <= n;i++){
        memset(vis,0,sizeof vis);
        if(dfs(i)) cnt++;
    }
    cout<<n-cnt/2<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42868863/article/details/114496857