DFS(邻接矩阵)
const int MAXN=1000;
int p,n; //u,v数目
int g[MAXN][MAXN];//左右集合连接情况
int linker[MAXN];
bool used[MAXN];
bool dfs(int u)
{
int v;
for(v=1; v<=n; v++)
if(g[u][v]&&!used[v])
{
used[v]=true;
if(linker[v]==-1||dfs(linker[v]))
{
linker[v]=u;
return true;
}
}
return false;
}
int hungary()
{
int res=0;
int u;
memset(linker,-1,sizeof(linker));
for(u=1; u<=p; u++)
{
memset(used,0,sizeof(used));
if(dfs(u))
res++;
}
return res;
}
DFS(邻接表)
const int MAXN=10050;
int linker[MAXN];
bool used[MAXN];
vector<int>g[MAXN];
int n;
bool dfs(int u)
{
for(int i=0; i<g[u].size(); i++)
{
if(!used[g[u][i]])
{
used[g[u][i]]=true;
if(linker[g[u][i]]==-1||dfs(linker[g[u][i]]))
{
linker[g[u][i]]=u;
return true;
}
}
}
return false;
}
int hungary()
{
int u;
int res=0;
memset(linker,-1,sizeof(linker));
for(u=1; u<=n; u++)
{
memset(used,false,sizeof(used));
if(dfs(u))
res++;
}
return res;
}
BFS
const int MAXN = 1000;
int g[MAXN][MAXN];
int Mx[MAXN], My[MAXN], p, n;
int chk[MAXN];
int Q[MAXN];
int pre[MAXN];
int hungary()
{
int res = 0;
int qs, qe;
memset(Mx, -1, sizeof(Mx));
memset(My, -1, sizeof(My));
memset(chk, -1, sizeof(chk));
for (int i = 1; i <= p; i++)
{
if (Mx[i] == -1) //对于x集合中的每个没有匹配的点i进行一次bfs找交错轨
{
qs = qe = 0;
Q[qe++] = i;
pre[i] = -1;
bool flag = 0;//判断是否找到
while (qs < qe && !flag)
{
int u = Q[qs];
for (int v = 1; v <= n && !flag; v++)
if (g[u][v]//如果u和v相连
&& chk[v] != i)//并且v没有被u check过
{
chk[v] = i;
Q[qe++] = My[v];//放进
if (My[v] >= 0)//如果v和其他的相连,则修改之
pre[My[v]] = u;
else //直到找到一个u和v都没有用过的
{
flag = 1;
int d = u, e = v;
while (d != -1) //确保回到最初
{
int t = Mx[d];
Mx[d] = e;
My[e] = d;
d = pre[d];
e = t;
}
}
}
qs++;
}
if (Mx[i] != -1)
res++;
}
}
return res;
}
Hopcroft-Carp 算法
#define MAXN 128
const int INF = 1 << 28;
int g[MAXN][MAXN], Mx[MAXN], My[MAXN], Nx, Ny;
int dx[MAXN], dy[MAXN], dis;
bool vst[MAXN];
bool searchP(void)
{
queue<int> Q;
dis = INF;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
for (int i = 0; i < Nx; i++)
{
if (Mx[i] == -1)
{
Q.push(i);
dx[i] = 0;
}
}
while (!Q.empty())
{
int u = Q.front(); Q.pop();
if (dx[u] > dis)
break;
for (int v = 0; v < Ny; v++)
{
if (g[u][v] && dy[v] == -1)
{
dy[v] = dx[u]+1;
if (My[v] == -1)
dis = dy[v];
else
{
dx[My[v]] = dy[v]+1;
Q.push(My[v]);
}
}
}
}
return dis != INF;
}
bool DFS(int u)
{
for (int v = 0; v < Ny; v++)
{
if (!vst[v] && g[u][v] && dy[v] == dx[u]+1)
{
vst[v] = 1;
if (My[v] != -1 && dy[v] == dis)
continue;
if (My[v] == -1 || DFS(My[v]))
{
My[v] = u;
Mx[u] = v;
return 1;
}
}
}
return 0;
}
int MaxMatch(void)
{
int res = 0;
memset(Mx, -1, sizeof(Mx));
memset(My, -1, sizeof(My));
while (searchP())
{
memset(vst, 0, sizeof(vst));
for (int i = 0; i < Nx; i++)
{
if (Mx[i] == -1 && DFS(i))//if (dx[i] == 0 && DFS(i))
res++;
}
}
return res;
}