Binary Graph matching (DFS implementation of Hungarian algorithm)
Initialization: g[][] Division of vertices on both sides
Build G[i][j] means that the i->j has a forward edge, which is the right side to the left.
G is initialized to 0 without a side connection
UN is the number of vertices to match to the left, and VN is the number of vertices matching the right
Call: Res=hungary (); Output maximum number of matches
Advantages: Suitable for dense map, DFS find augmented road, simple and easy to understand
Complexity of Time: O (VE)
***************************************************************************/
Vertex numbering starts with 0
/*hdu 1151*/#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> Using namespace std;/* **************************************************************************// Binary Graph matching (DFS implementation of the Hungarian algorithm)//initialization: g[][] The division of vertices between the two sides//build g[i][j] means that the i->j has a forward edge on it, is left to the right side of the match//g no edge is connected to the 0//un is the number of vertices to match the left, VN is the number of vertices matching the right//call: Res=hungary (); Output maximum number of matches//advantages: Suitable for dense graphs, DFS find augmented road, simple and easy to understand/time complexity: O (VE)//****************************** const int maxn=150;int un,vn;//u,v number int g[maxn][maxn];int with vertex numbering starting from 0 Linker[maxn];bool used[maxn];bool dfs (int u)//from the left to find the augmented path {int V; for (v=0;v<vn;v++)//This vertex number starting from 0, to start with 1 need to modify if (G[u][v]&&!used[v]) {used[v]=true; if (linker[v]==-1| | DFS (Linker[v]) {//Find augmented road, reverse linker[v]=u; return true; }} return false;//this do not forget, often forget this sentence}int Hungary () {int res=0; int u; memset (LINKER,-1,SIZEOF (linker)); for (u=0;u<un;u++) {memset (Used,0,sizeof (used)); if (DFS (U)) res++; } return res; /int Main () {int k; int n; int u,v; int T; scanf ("%d", &t); while (t--) {scanf ("%d%d", &n,&k); memset (G,0,sizeof (g)); while (k--) {scanf ("%d%d", &u,&v); u--; v--; G[u][v]=1; } un=vn=n; printf ("%d\n", N-hungary ()); } return 0;}
HDU 1151 Air Raid (minimum path overlay)