0%

匈牙利算法

求二分图的最大匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 1000001;
const int M = 2000001;

int n1, n2, m, ans;
bool state[N];
int result[N];

int fir[N], edge_num, nxt[M], to[M];
void addEdge(int x, int y){
to[++edge_num] = y;
nxt[edge_num] = fir[x];
fir[x] = edge_num;
}

void init(){
int t1, t2;
memset(result, 0, sizeof(result));
ans = 0;
scanf("%d%d%d", &n1, &n2, &m);
for(int i=1;i<=m;i++){
scanf("%d%d", &t1, &t2);
if(t1>n1 || t2>n2) continue;
addEdge(t1, t2);
}
}

bool find(int x){
for(int i=fir[x]; i; i=nxt[i]){
int v = to[i];
if(!state[v]){
state[v] = 1;
if(result[v]==0 || find(result[v])){
result[v] = x;
return true;
}
}
}
return false;
}

int main(){
init();
for(int i=1;i<=n1;i++){
memset(state, 0, sizeof(state));
if(find(i)) ans++;
}
printf("%d\n", ans);


return 0;
}

求大佬赏个饭