HK algorithm bipartite graph maximum matching algorithm is the classical algorithm in Hungary, but this article is not about the Hungarian algorithm, but that a more optimal time complexity.
Points define the x, y point side bipartite graph both different points.
Implementation process:
1. All points in the x point not cover all queued.
2. wide search to find short augmenting path.
Specific process is as follows:
1>每次进行访问时,找到y方点中没有标号的点,将它的标号设为x方点的标号+1。
2>如果所选的y方点是未盖点,则找到了“可增广路”,不继续搜索这条线。
3>如果所选的y方点时匹配点,则沿着那条路继续搜。同时将其匹配的x方点的标号设为y方点标号+1.
3, to find not cover point, Hungary search algorithm to find an augmenting path, but the access point before a label +1 point when necessary.
Code:
wherein dx is the reference point of the x, dy is a y-reference point, linkx point matching the x points, linky y-point matching point.
/*
written by tyx_yali
2017.02.09
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define For(aa,bb,cc) for(int aa=bb;aa<=cc;++aa)
#define Set(aa,bb) memset(aa,bb,sizeof(aa))
using namespace std;
const int maxn=250010;
int n,m,s,ans;
int be[maxn],ne[maxn],to[maxn],e;
int linkx[maxn],linky[maxn];
int dx[maxn],dy[maxn];
void add(int x,int y){
to[++e]=y,ne[e]=be[x],be[x]=e;
if(!linkx[x] && !linky[y]) linkx[linky[y]=x]=y,++ans;
}
bool bfs(){
bool flag=0;
int q[maxn],f=0,l=0;
Set(dx,0),Set(dy,0);
For(i,1,n){
if(!linkx[i]) q[++l]=i;
}
while(f<l){
int k=q[++f];
for(int i=be[k];i;i=ne[i]){
int u=to[i];
if(!dy[u]){
dy[u]=dx[k]+1;
if(!linky[u]) flag=1;
else dx[linky[u]]=dy[u]+1,q[++l]=linky[u];
}
}
}
return flag;
}
bool dfs(int node){
for(int i=be[node];i;i=ne[i]){
int u=to[i];
if(dy[u]==dx[node]+1){
dy[u]=0;
if(!linky[u] || dfs(linky[u])){
linkx[linky[u]=node]=u;
return 1;
}
}
}
return 0;
}
void work(){
scanf("%d%d%d",&n,&m,&s);
For(i,1,s){
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
}
while(bfs()){
For(i,1,n){
if(!linkx[i] && dfs(i)) ++ans;
}
}
printf("%d\n",ans);
For(i,1,n){
printf("%d ",linkx[i]);
}
puts("");
}
int main(){
work();
return 0;
}