匈牙利算法模板

const int MAXN = 205;

bool board[MAXN][MAXN];//存边 
int color[MAXN];//用于染色法判断是否是二分图 
int N,M;//N个点M条边 

bool Judge(int x){
	for(int i=1 ; i<=N ; ++i){
		if(board[x][i] == 0)continue;
		if(color[x] == color[i])return false;
		if(color[i] == 0){
			color[i] = 3-color[x];
			if(!Judge(i))return false;
		}
	}
	return true;
}

int pre[MAXN];
bool used[MAXN];

int Find(int x){
	for(int i=1 ; i<=N ; ++i){
		if(board[x][i]){
			if(used[i])continue;
			used[i] = true;
			if(pre[i] == 0 || Find(pre[i])){
				pre[i] = x;
				return 1;
			}
		}
	}
	return 0;
}

inline void init(){
	memset(board,false,sizeof board);
	memset(color,0,sizeof color);
	memset(pre,0,sizeof pre);
}

int main(){
	
	while(scanf("%d %d",&N,&M)!=EOF){
		init();
		while(M--){
			int a,b;
			scanf("%d %d",&a,&b);
			board[a][b] = board[b][a] = true;
		}
		color[1] = 1;
		if(!Judge(1)){
			printf("No\n");
			continue;
		}
		int sum = 0;
		for(int i=1 ; i<=N ; ++i){
			memset(used,false,sizeof used);
			sum += Find(i);
		} 
	}
	
	return 0;
}

 

posted @ 2018-07-17 17:27  Assassin_poi君  阅读(161)  评论(0编辑  收藏  举报