二分图匹配

Hungary 算法

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
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int N=1050;
int n,m,T,cnt=0,used[N],c[N];
vector<int> e[N];
inline int read()
{
register int x=0,t=1;
register char ch=getchar();
while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if (ch=='-') {t=-1;ch=getchar();}
while (ch>='0'&&ch<='9') {x=x*10+ch-48;ch=getchar();}
return x*t;
}
int find(int o)
{
for(int i=0;i<e[o].size();i++)
{
int to=e[o][i];
if (used[to]) continue;
used[to]=1;
if (!c[to]||find(c[to]))
{
c[to]=o;
return 1;
}
}
return 0;
}
int main()
{
n=read(),m=read(),T=read();
while (T--)
{
int u=read(),v=read();
if (u>n||v>m) continue;
e[u].push_back(v);
}
for(int i=1;i<=n;i++)
{
memset(used,0,sizeof(used));
cnt+=find(i);
}
printf("%d",cnt);
return 0;
}