質問

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] is true iff there is an edge from pigeon i to hole j, 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] and seen[m] are global arrays.
  • main() initializes matchL[] and matchR[] to -1 in all components.
  • main() does a loop over all pigeons i and in each iteration

    • clears seen[] to 0 in all components
    • calls bpm(i) and increments the maxflow counter
    • bpm(i) returns true iff pigeon i can be assigned a hole
  • cnt contains 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:

       if (graph[u][u])

There is no element of graph on the diagonal which is set true, so bpm() always fails completely. It is also not clear why you'd be needing to test the diagonal alone. Maybe it should be if (graph[u][v]), or maybe something else.

(Your indentation leaves somewhat to be desired; it is extremely aconventional to put an if condition such as this on the same line as a for loop control. Incidentally, the initialization of matchL and matchR only works on 2's-complement machines.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top