POJ 1274 maximum bipartite graph matching

Title

Portal POJ 1274

answer

Naked maximum bipartite graph matching can be solved with maximum flow or Hungarian algorithm. The Hungarian algorithm is used here.

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#define min(a,b)    (((a) < (b)) ? (a) : (b))
#define max(a,b)    (((a) > (b)) ? (a) : (b))
#define abs(x)    ((x) < 0 ? -(x) : (x))
#define INF 0x3f3f3f3f
#define delta 0.85
#define eps 1e-10
#define PI 3.14159265358979323846
using namespace std;

#define MAX_V 405
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 = 0; v < V; v++){
		if(match[v] < 0){
			memset(used, 0, sizeof(used));
			if(dfs(v)){
				++res;
			}
		}
	}
	return res;
}

#define MAX_N 200
#define MAX_M 200
int N, M;
int S[MAX_N];
int like[MAX_N][MAX_M];

void solve(){
	if(N == 0 || M == 0){
		printf("0\n");
		return;
	}
	V = N + M;
	// 初始化图
	for(int v = 0; v < V; v++) G[v].clear();
	// 建图
	for(int i = 0; i < N; i++){
		for(int j = 0; j < S[i]; j++){
			add_edge(i, N + like[i][j]);
		}
	}
	printf("%d\n", bipartite_matching());
}

int main(){
	while(~scanf("%d%d", &N, &M)){
		memset(like, 0, sizeof(like));
		for(int i = 0; i < N; i++){
			scanf("%d", S + i);
			for(int j = 0; j < S[i]; j++){
				scanf("%d", &like[i][j]);
				--like[i][j];
			}
		}
		solve();
	}
	return 0;
}
Published 110 original articles · won praise 1 · views 2043

Guess you like

Origin blog.csdn.net/neweryyy/article/details/105479174