匈牙利算法:二分圖的最大匹配

傳送門
題意:給定一個二分圖,其中左半部包含n1個點(編號1 ~ n1),右半部包含n2個點(編號1~n2),二分圖共包含m條邊。
數據保證任意一條邊的兩個端點都不可能在同一部分中。
請你求出二分圖的最大匹配數。

  • 二分圖的匹配:給定一個二分圖G,在G的一個子圖M中,M的邊集{E}中的任意兩條邊都不依附於同一個頂點,則稱M是一個匹配。
  • 二分圖的最大匹配:所有匹配中包含邊數最多的一組匹配被稱爲二分圖的最大匹配,其邊數即爲最大匹配數。

輸入格式
第一行包含三個整數 n1、 n2 和 m。
接下來m行,每行包含兩個整數u和v,表示左半部點集中的點u和右半部點集中的點v之間存在一條邊。

輸出格式
輸出一個整數,表示二分圖的最大匹配數。

數據範圍
1≤n1,n2≤500,
1≤u≤n1,
1≤v≤n2,
1≤m≤10^5
輸入樣例:
2 2 4
1 1
1 2
2 1
2 2
輸出樣例:
2

思路:
啊啊啊!y總簡直不要這麼可愛好嘛!講解的也太有趣了!

  • 目的:把兩個集合比喻成男生集合以及女生集合,兩集合存在一條邊表示這個邊上的兩人互相中意。找到最大的匹配方法,讓每個人都鍾情專一。
  • 先遍歷男生集合,再遍歷某個男生中意的妹子的名單;如果某個妹子還是單身,便互相匹配。
  • 如果某個妹子已經名花有主,他也不會放棄,他會展開猛烈的攻勢,簡直不撞南牆不甘心。 找到她的男朋友,再遍歷一遍她男朋友的備胎名單,勸說他換一個新女友。
    如果換女友成功,則兩個男生都可以匹配成功;如果他換不了,才放棄。

代碼實現:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define int long long
#define lowbit(x) (x &(-x))
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;
const int  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double EXP = 1e-8;
const ll   MOD = 1e9 + 7;
const int  N = 510, M = 1e5 + 5;

int n1, n2, m;
int h[N], e[M], ne[M], idx;
int match[N];
bool st[N];

void add(int a, int b)
{
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}

bool find(int x)
{
    //遍歷備胎列表
    for(int i = h[x]; ~i; i = ne[i]){
        int j = e[i];
        if(!st[j]){  //如果還沒有考慮過這個妹子
            st[j] = 1;
            //如果這個妹子還是單身或她的男朋友能換新女友
            if(!match[j] || find(match[j])){
                match[j] = x;  //匹配成功
                return 1;
            }
        }
    }
    return 0;
}

signed main()
{
    IOS;
    cin >> n1 >> n2 >> m;
    mem(h, -1);

    while(m --){
        int a, b;
        cin >> a >> b;
        add(a, b);
    }

    int ans = 0;
    for(int i = 1; i <= n1; i ++){
        mem(st, 0);  //保證每個妹子都只考慮一遍
        if(find(i)) ans ++; //匹配成功,當然匹配數++
    }

    cout << ans << endl;

    return 0;
}

哈哈哈,還有很多神級評論:
“匈牙利算法告訴我們要廣撒網!”,“讓他換一個人勾搭”,“這簡直就是渣男算法”
%%%,y總簡直太強了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章