NYOJ 239 月老的難題(二分圖匹配)

題目連接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=239

簡單的二分圖入門題。。。

 
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

#define CLR(arr,v) memset(arr,v,sizeof(arr))

template<int MaxV,int MaxE>
class Graph{
public:
	void Clear(){
		pos = 0; CLR(H,-1);
	}
	void add(int u,int v,int c){
		Num[pos] = v;
		Len[pos] = c;
		Next[pos] = H[u];
		H[u] = pos++;
	}
	int H[MaxV],Num[MaxE],Len[MaxE],Next[MaxE],pos;
};

const int MaxV = 505;
Graph<MaxV,MaxV*MaxV> g;
class MaxNumMatch{
public:
	void Clear(){
		CLR(Match,-1); g.Clear();
	}
	int GetMaxNumMatch(int s,int t){
		int MatchNum = 0;
		for(int i = s;i <= t;++i){
			CLR(Vist,false);
			if(Dfs(i)) MatchNum++;
		}
		return MatchNum;
	}
	bool Dfs(int cur){
		for(int i = g.H[cur];i != -1;i = g.Next[i])
		{
			if(!Vist[ g.Num[i] ]){
				Vist[ g.Num[i] ] = true;
				if(Match[ g.Num[i] ] == -1 || Dfs(Match[ g.Num[i] ]))
				{
					Match[ g.Num[i] ] = cur;
					return true;
				}
			}
		}
		return false;
	}
private:
	int Match[MaxV];
	bool Vist[MaxV];
};

MaxNumMatch g1;

int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		g1.Clear();
		int n,m,b,e;
		scanf("%d%d",&n,&m);
		for(int i = 1;i <= m;++i)
		{
			scanf("%d%d",&b,&e);
			g.add(b,e,0);
		}
		cout<<g1.GetMaxNumMatch(1,n)<<endl;
	}
	return 0;
}        


發佈了74 篇原創文章 · 獲贊 33 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章