# 「模板」 二分图匹配（匈牙利算法）

<题目链接>

#include <algorithm>
#include <cstdio>
#include <cstring>

const int MAXN = 2010;

int n, m, e;

class Graph
{
private:
bool vis[MAXN];
int match[MAXN];
struct Edge
{
int to;
Edge *next;
Edge(int to, Edge* next): to(to), next(next) {}
~Edge(void)
{
if(next != nullptr)
delete next;
}
int DFS(int u)
{
int v;
for(Edge *i = head[u]; i != nullptr; i = i -> next)
if(!vis[v = i -> to])
{
vis[v] = true;
if(!match[v] || DFS(match[v]))
{
match[u] = v;
match[v] = u;
return 1;
}
}
return 0;
}
public:
Graph(int n)
{
memset(vis, 0, sizeof vis);
memset(match, 0, sizeof match);
}
~Graph(void)
{
for(int i = 1; i <= n; ++i)
}
{
}
int Hungary(void)
{
int ans = 0;
for(int i = 1; i <= n; ++i)
if(!match[i])
{
memset(vis, 0, sizeof vis);
ans += DFS(i);
}
return ans;
}
}*G;

int main(void)
{
scanf("%d %d %d", &n, &m, &e);
G = new Graph(n + m);
for(int i = 1, u, v; i <= e; ++i)
{
scanf("%d %d", &u, &v);
if(u <= n && v <= m)
G -> AddEdge(u, v + n);
}
printf("%d\n", G -> Hungary());
return 0;
}


posted @ 2019-04-15 16:33  Capella  阅读(310)  评论(1编辑  收藏  举报