【图论】匈牙利算法模板

来源:互联网 发布:阿里面试题 java p7 编辑:程序博客网 时间:2024/05/22 03:02

匈牙利算法:

由增广路得性质可以知道,二分图最大匹配可以通过网络流来求解,所谓匈牙利算法就是针对网络流的特性来写的网络流。

匈牙利算法模板:

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<algorithm>#include<map>#include<string>#include<queue>#include<vector>#include<list>//#pragma comment(linker,"/STACK:1024000000,1024000000")using namespace std;#define INF 0x3f3f3f3f/* * 匈牙利算法,vector邻接表实现,算法复杂度O(V*E); */const int MAX_V=100005;int V;//二分图一边的节点数vector<int> G[MAX_V];int match[MAX_V];bool used[MAX_V];//建立无向边void add_edge(int u,int v){    G[u].push_back(v);    G[v].push_back(u);}bool dfs(int v){    used[v]=true;    for(int i=0;i<G[v].size();i++)    {        int u=G[v][i],w=match[u];        if(w<0||!used[w]&&dfs(w))        {            match[v]=u;            match[u]=v;            return true;        }    }    return false;}//贪心寻找增广路int bipartite_matching(){    int res=0;    memset(match,-1,sizeof match);    for(int v=1;v<=V;v++)//注意下标    {        if(match[v]<0)        {            memset(used,0,sizeof used);            if(dfs(v))            {                res++;            }        }    }    return res;}



0 0