Title

【图论】匈牙利算法——社会人数规模专家

图解

AcWing 861. 二分图的最大匹配

#include<bits/stdc++.h>
using namespace std;
const int N = 5E2+10,M = 1E5+10;
int n1,n2,m;

int h[N],ne[M],e[M],idx=0;
void add(int a,int b)
{
	e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}


int match[N];
bool st[N];

bool find(int u)
{
	for(int i = h[u];~i;i=ne[i])
	{
		int j= e[i];
		if(!st[j])//如果i的潜在对象j仍未被打扰的话,可以尝试一下,
		{      //可能被间接打扰,在一层层询问之中。相当于你拜托一个你拜托的人已经拜托的人。 
	        st[j]=true;//已被访问,谢绝再访 
			if(!match[j]||find(match[j]))//让match[j]挪下位置 
		    {
		    	match[j] = u;//j的新欢变成了u
                return true;
			}
		}
	}
	return false; //找了一圈都没有找到,返回false 
}

void init()
{
   cin>>n1>>n2>>m;
   memset(h,-1,sizeof(h));	
   memset(match,false,sizeof(match));

   for(int i=0;i<m;i++)
   {
   	    int u,v;
   	    cin>>u>>v;
   	    add(u,v);
   }
}

int Hungarian()
{
	int res=0;
	for(int i=1;i<=n1;i++)
	{
		memset(st,false,sizeof(st));
		if(find(i))
		   res++;
	}
	return res;
}

int main()
{
	init();
        cout<<Hungarian();	
	return 0;
}

资料

CSDN

posted @ 2021-07-21 22:00  BeautifulWater  阅读(33)  评论(0编辑  收藏  举报