二分图最大匹配模板(匈牙利算法)

二分图最大匹配模板(匈牙利算法)

P3386 【模板】二分图最大匹配 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

struct augment_path {
	vector<vector<int> > g;
	vector<int> pa;  // 匹配
	vector<int> pb;
	vector<int> vis;  // 访问
	int n, m;         // 两个点集中的顶点数量
	int dfn;          // 时间戳记
	int res;          // 匹配数

	augment_path(int _n, int _m) : n(_n), m(_m) {
		assert(0 <= n && 0 <= m);
		pa = vector<int>(n, -1);
		pb = vector<int>(m, -1);
		vis = vector<int>(n);
		g.resize(n);
		res = 0;
		dfn = 0;
	}

	void add(int from, int to) {
		assert(0 <= from && from < n && 0 <= to && to < m);
		g[from].push_back(to);
	}

	bool dfs(int v) {
		vis[v] = dfn;
		for (int u : g[v]) {
			if (pb[u] == -1) {
				pb[u] = v;
				pa[v] = u;
				return true;
			}
		}
		for (int u : g[v]) {
			if (vis[pb[u]] != dfn && dfs(pb[u])) {
				pa[v] = u;
				pb[u] = v;
				return true;
			}
		}
		return false;
	}

	int solve() {
		while (true) {
			dfn++;
			int cnt = 0;
			for (int i = 0; i < n; i++) {
				if (pa[i] == -1 && dfs(i)) {
					cnt++;
				}
			}
			if (cnt == 0) {
				break;
			}
			res += cnt;
		}
		return res;
	}
};
posted @ 2023-12-02 12:32  Ke_scholar  阅读(24)  评论(0编辑  收藏  举报