I have the following code which is an implementation of BPM (bipartite matching, from graph theory)
#include <iostream>
#include <cstring>
using namespace std;
#define M 128
#define N 128
bool graph[M][N];
bool seen[N];
int matchL[M],matchR[N];
int n=4;
int m=4;
bool bpm(int u){
for(int v=0;v<n;v++) if(graph[u][u])
{
if (seen[v]) continue;
seen[v]=true;
if(matchR[v] <0 || bpm(matchR[v])){
matchL[u]=v;
matchR[v]=u;
return true;
}
}
return false;
}
int main(){
graph[0][1]=1;
graph[0][3]=1;
graph[1][3]=1;
graph[0][2]=1;
memset(matchL,-1,sizeof(matchL));
memset(matchR,-1,sizeof(matchR));
int cnt=0;
// memset(seen,0,sizeof(seen));
for(int i=0;i<m;i++){
memset(seen,0,sizeof(seen));
if(bpm(i)) cnt++;
}
cout<<cnt<<endl;
return 0;
}
The definition of cnt and the purpose of this code are given below.
Given a bipartite graph represented as an m-by-n matrix, where
graph[i][j]istrueiff there is an edge from pigeonito holej, computes the maximum number of pigeons that can find a hole (one per pigeon) and an optimal assignment.
graph[m][n],matchL[n],matchR[m]andseen[m]are global arrays.main()initializesmatchL[]andmatchR[]to-1in all components.-
main()does a loop over all pigeonsiand in each iteration- clears
seen[]to0in all components - calls
bpm(i)and increments themaxflowcounter bpm(i)returnstrueiff pigeonican be assigned a hole
- clears
-
cntcontains the number of happy pigeons.
In my case, cnt‘s value is output as 0. Does this graph algorithm work correctly or have I made some error?
Either your initialization is faulty or this condition in
bpm()is faulty:There is no element of
graphon the diagonal which is settrue, sobpm()always fails completely. It is also not clear why you’d be needing to test the diagonal alone. Maybe it should beif (graph[u][v]), or maybe something else.(Your indentation leaves somewhat to be desired; it is extremely aconventional to put an
ifcondition such as this on the same line as aforloop control. Incidentally, the initialization ofmatchLandmatchRonly works on 2’s-complement machines.)