arundeepak

Bipartite Maximum Matching

Mar 28th, 2016
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. '__author__'=='deepak Singh Mehta(learning Bipartite Maximum Matching... :))'
  2.  
  3. graph,M,N = list(),6,6
  4.  
  5. #recursive dfs returns true if there's a matching for vextex u is possible
  6. def bpm(u,seen,match):
  7.     global graph,N,M
  8.     for v in range(N):
  9.         if graph[u][v] and not seen[v]: #if applicant u is interested in job and is not visited
  10.             seen[v] = True #mark as visited
  11.             #If job 'v' is not assigned to an applicant OR
  12.             #previously assigned applicant for job v (which is match[v])
  13.             #has an alternate job available.
  14.             #Since v is marked as visited in the above line, match[v]
  15.             #in the following recursive call will not get job 'v' again
  16.             if match[v]<0 or bpm(match[v],seen,match):
  17.                 match[v]=u
  18.                 return True
  19.     return False      
  20.        
  21. #Returns maximum number of matching from M to N
  22. def maxBPM():
  23.     global graph,M,N
  24.     # An array to keep track of the applicants assigned to
  25.     # jobs. The value of matchR[i] is the applicant number
  26.     # assigned to job i, the value -1 indicates nobody is
  27.     # assigned.
  28.     match = [-1 for i in range(N)] #Initially all jobs are available
  29.     result = 0 #Count of jobs assigned to applicants
  30.     for u in range(M):
  31.         seen = [False for i in range(N)]#Mark all jobs as not seen for next applicant.
  32.         if bpm(u,seen,match): # Find if the applicant 'u' can get a job
  33.             result += 1
  34.     return result
  35.  
  36. if __name__=='__main__':
  37.     graph = [[0,1,1,0,0,0],
  38.              [1,0,0,1,0,0],
  39.              [0,0,1,0,0,0],
  40.              [0,0,1,1,0,0],
  41.              [0,0,0,0,0,0],
  42.              [0,0,0,0,0,1]
  43.              ]
  44.     print("Maximum number of applicants that can get job is",maxBPM())
Add Comment
Please, Sign In to add comment