二分图最大匹配问题,这一类的问题难点往往不是算法上,难点在于从一个问题中抽象数学模型,然后去求解。
WIKI百科传送门:二分图最大匹配
二分图匹配的衍生问题:二分图最大匹配应用
附上HDU 2063 例题代码。
CODE:
/*ED模板*/
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAXN 10010
#define MAXM 100010
struct Edge
{
int v, next;
}edge[MAXM];
int n, m;
int cnt;
int girl, boy;
int first[MAXN], link[MAXN];
bool vis[MAXN];
inline void init()
{
cnt = 0;
memset(link, -1, sizeof(link));
memset(first, -1, sizeof(first));
}
inline void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u];
first[u] = cnt++;
}
int ED(int u)
{
for(int e = first[u]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
if(!vis[v])
{
vis[v] = true;
if(link[v] == -1 || ED(link[v]))
{
link[v] = u; //取反
return true;
}
}
}
return false;
}
void solve()
{
int ans = 0;
for(int i = 1; i <= girl; i++) //for(int i = 1; i <= n; i++) n为匹配点的个数
{
memset(vis, 0, sizeof(vis));
if(ED(i)) ans++;
}
printf("%d\n", ans);
}
int main()
{
while(scanf("%d", &m) && m)
{
init();
scanf("%d%d", &girl, &boy);
while(m--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
}
solve();
}
return 0;
}
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAXN 10010
#define MAXM 100010
struct Edge
{
int v, next;
}edge[MAXM];
int n, m;
int cnt;
int girl, boy;
int first[MAXN], link[MAXN];
bool vis[MAXN];
inline void init()
{
cnt = 0;
memset(link, -1, sizeof(link));
memset(first, -1, sizeof(first));
}
inline void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u];
first[u] = cnt++;
}
int ED(int u)
{
for(int e = first[u]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
if(!vis[v])
{
vis[v] = true;
if(link[v] == -1 || ED(link[v]))
{
link[v] = u; //取反
return true;
}
}
}
return false;
}
void solve()
{
int ans = 0;
for(int i = 1; i <= girl; i++) //for(int i = 1; i <= n; i++) n为匹配点的个数
{
memset(vis, 0, sizeof(vis));
if(ED(i)) ans++;
}
printf("%d\n", ans);
}
int main()
{
while(scanf("%d", &m) && m)
{
init();
scanf("%d%d", &girl, &boy);
while(m--)
{
int u, v;
scanf("%d%d", &u, &v);
read_graph(u, v);
}
solve();
}
return 0;
}