一般图最大加权匹配模板

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn=110;
int g[maxn][maxn];
int cnt_node;//点的个数
int dis[maxn];
int match[maxn];
bool vis[maxn];
int st[maxn],top;
bool dfs(int u)
{
    st[top++]=u;
    if(vis[u]) return true;
    vis[u]=true;
    for(int i=0;i<cnt_node;i++)
    {
        if(i!=u&&i!=match[u]&&!vis[i])
        {
            int t=match[i];
            if(dis[t]<dis[u]+g[u][i]-g[i][t])
            {
                dis[t]=dis[u]+g[u][i]-g[i][t];
                if(dfs(t)) return true;
            }
        }
    }
    top--;
    vis[u]=false;
    return false;
} 
int p[maxn];
//返回最大匹配权值 
int get_match(int n)
{
    cnt_node=n;
    for(int i=0;i<cnt_node;i++) p[i]=i;
    for(int i=0;i<cnt_node;i+=2)
    {
        match[i]=i+1;
        match[i+1]=i;
    }
    int cnt=0;
    while(1)
    {
        memset(dis,0,sizeof(dis));
        memset(vis,0,sizeof(vis));
        top=0;
        bool update=false;
        for(int i=0;i<cnt_node;i++)
        {
            if(dfs(p[i]))
            {
                update=true;
                int temp=match[st[top-1]];
                int j=top-2;
                while(st[j]!=st[top-1])
                {
                    match[temp]=st[j];
                    swap(temp,match[st[j]]);
                    j--;
                }
                match[temp]=st[j];
                match[st[j]]=temp;
                break;
            }
        }
        if(!update)
        {
            cnt++;
            if(cnt>=3) break;
            random_shuffle(p,p+cnt_node);
        }
    }
    int ans=0;
    for(int i=0;i<cnt_node;i++)
    {
        int v=match[i];
        if(i<v)    ans+=g[i][v];
    }
    return ans; 
 }
原文地址:https://www.cnblogs.com/xiongtao/p/11196044.html