「模板」 二分图匹配(匈牙利算法)
可是,我从来也没有离开过。
#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;
}
}*head[MAXN];
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)
{
std :: fill(head + 1, head + n + 1, nullptr);
memset(vis, 0, sizeof vis);
memset(match, 0, sizeof match);
}
~Graph(void)
{
for(int i = 1; i <= n; ++i)
delete head[i];
}
void AddEdge(int u, int v)
{
head[u] = new Edge(v, head[u]);
}
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
", G -> Hungary());
return 0;
}
谢谢阅读。