Hungarian algorithm template with two-point maximum matching
/**************************************************** binary Map matching (DFS implementation of the Hungarian algorithm) init:g[][] Call:res=hungary () on both sides of the fixed-point division Output maximum Match number advantages: suitable for dense map, DFS find the augmented road fast, simple and easy to understand time complexity: O (VE); ****************************************************/Const intMAXN =510;intUN,VN;//Number of U,vintG[MAXN][MAXN];//the number is 1~n.intLINKER[MAXN];BOOLUSED[MAXN];BOOLDfsintu) { intv; for(v=1; v<=vn;v++){ if(g[u][v]&&!Used[v]) {Used[v]=true; if(linker[v]==-1||DFS (Linker[v])) {Linker[v]=T; return true; } } } return false;}intHungary () {intres=0; intu; MEMSET (linker,-1,sizeof(linker)); for(u=1; u<=un;u++) {memset (used,false,sizeof(used)); if(Dfs (U)) res++; } returnRes;}
Example: HDU 2063 roller Coaster (template problem)
#include <stdio.h>#include<string.h>#include<iostream>using namespacestd;/**************************************************** binary Map matching (DFS implementation of the Hungarian algorithm) init:g[][] Call:res=hungary () on both sides of the fixed-point division Output maximum Match number advantages: suitable for dense map, DFS find the augmented road fast, simple and easy to understand time complexity: O (VE); ****************************************************/Const intMAXN =510;intUN,VN;//Number of U,vintG[MAXN][MAXN];//the number is 1~n.intLINKER[MAXN];BOOLUSED[MAXN];BOOLDfsintu) { intv; for(v=1; v<=vn;v++){ if(g[u][v]&&!Used[v]) {Used[v]=true; if(linker[v]==-1||DFS (Linker[v])) {Linker[v]=u; return true; } } } return false;}intHungary () {intres=0; intu; MEMSET (linker,-1,sizeof(linker)); for(u=1; u<=un;u++) {memset (used,false,sizeof(used)); if(Dfs (U)) res++; } returnRes;}intMain () {intK; while(SCANF ("%d", &k) = =1&&k) {scanf ("%d%d",&un,&VN); memset (G,0,sizeof(G)); for(intI=1; i<=k;i++){ intu,v; scanf ("%d%d",&u,&v); G[U][V]=1; } printf ("%d\n", Hungary ()); } return 0;}
Binary graph matching (Hungarian algorithm template)