1. 程式人生 > >二分圖最大匹配(匈牙利算法)

二分圖最大匹配(匈牙利算法)

bsp stdin ret back net target tails cto 如果

參考:

https://blog.csdn.net/cillyb/article/details/55511666

https://blog.csdn.net/c20180630/article/details/70175814

模板:

#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5 + 7;
vector<int> G[maxN];
int match[maxN];
int vis[maxN];
int n, m, sum;
int dfs(int u) {

    for(int i = 0; i < G[u].size(); i++) {
        
int v = G[u][i]; //有路而且沒被訪問 if(!vis[v]) { vis[v] = 1;//標記點i已經訪問過 //如果點i未被配對或者找到了新的配對 if(match[v] == 0 || dfs(match[v])) { //更新配對關系 match[v] = u; match[u] = v; return 1; } } }
return 0; } int main() { // freopen("1.txt","r", stdin); scanf("%d %d", &n, &m); for(int i = 1; i <= n; i++) { int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); G[v].push_back(u); } memset(match, 0 , sizeof(match)); for(int i = 1
; i <= n; i++){ memset(vis, 0, sizeof(vis)); if(dfs(i)) { sum++; } } printf("%d\n", sum); }

二分圖最大匹配(匈牙利算法)