Detailed Explanation of Hungarian Algorithm of Matching Algorithm

reference:

  1. Algorithm Study Notes (5): Hungarian Algorithm
  2. Talking about the Hungarian Algorithm
  3. Hungarian algorithm, KM algorithm
  4. Hungarian Algorithm (Bipartite Graph)
  5. Easy to understand Xiaobai introduction) bipartite graph maximum matching - Hungarian algorithm
  6. Data association for multi-target tracking (Hungarian matching algorithm and KM algorithm)
  7. [Xiaobai study notes] (1) Target tracking - Hungarian matching

1. Basic concept of Hungarian algorithm

  • The Hungarian algorithm (Hungarian algorithm), that is, the algorithm for finding the maximum matching in graph theory , does not consider the weighted maximum matching (implemented by the KM algorithm).
  • The Hungarian algorithm is mainly used to solve some problems related to bipartite graph matching.

1. Bipartite graph

  • A bipartite graph is a special model in graph theory. If the vertex V of the undirected graph G=(V,E) can be divided into two vertex sets whose intersection is empty, and the two endpoints of any edge belong to two sets, then the graph G is called a bipartite graph .
  • A bipartite graph is a special type of graph that can be divided into two parts, and the points in each part are not connected to each other . The figure below is a typical bipartite graph.
    insert image description here
    It can be seen that in the above bipartite graph, the endpoints of each edge are in the point sets X and Y respectively.

2. match

  • A matching of a graph G is a set of edges that are not cycles and have no common endpoint .
    Here, we use a graph to represent the concept of matching:
    insert image description here
    as shown in the figure, the three edges are a match of the graph. Therefore, there are two key points of matching: 1. Matching is a set of edges; 2. In this set, any two edges cannot have a common vertex .
    Then, we naturally have an idea, how many matches will a graph have? Is there a maximum matching (that is, the matching with the most edges)?

3. Maximum match

  • Selecting such a subset with the largest number of edges is called the maximum matching problem of the graph. The maximum number of matching edges is called the maximum matching .

4. Perfect match

  • If in a match, every vertex in the graph is associated with an edge in the graph, the match is called a perfect match (exact match), also known as a complete match .
  • Considering a bipartite graph with subsets X={x1 ,x2, …} and Y={y1, y2, …}, a perfect matching is defined as a bijection from XY, followed by x1, x2, … xn to find the paired Vertex, finally able to get n! a perfect match .

5. Best match

  • Optimal matching, also known as weighted maximum matching, refers to finding a match in a bipartite graph with weighted edges so that the sum of weights on the matching edges is the largest .
  • Generally, the number of vertices in the X and Y sets is the same, and the optimal matching is also a complete matching, that is, each vertex is matched. If the numbers are not equal, the conversion can be realized by adding points and adding 0 sides. Generally, the KM algorithm is used to solve this problem.

6. Minimum Coverage

  • The minimum cover of a bipartite graph is divided into minimum vertex cover and minimum path cover :

    ①The minimum vertex cover refers to the minimum number of vertices so that each edge in the bipartite graph G is associated with at least one of the points , the minimum vertex cover number of the bipartite graph = the maximum number of matches of the bipartite graph ;

    ②The minimum path cover is also called the minimum edge cover, which refers to covering all the vertices in the bipartite graph with as few disjoint simple paths as possible . The minimum path coverage of the bipartite graph = |V| - the maximum matching number of the bipartite graph ;

7. Maximum independent set

  • The maximum independent set is to find a set of points such that any two points have no corresponding edges in the graph. For general graphs, the maximum independent set is an NP-complete problem, and for bipartite graphs: maximum independent set = |V| - the maximum number of matches in the bipartite graph .

8. Alternate Road

  • Starting from the unmatched point, passing through the unmatched side and the matched side in turn, it is an alternate road , such as Fig.3: 3 -> 5 -> 1 -> 7 -> 4 -> 8
    insert image description here

9. Zengguang Road (also known as Zengguang track or staggered track)

  • If the alternate road passes through another unmatched point other than the starting point, this alternate road is called an augmented road . For example, in the example of the concept of an alternate road, its passing point 8 is an augmented road.

  • The following three conclusions can be deduced from the definition of augmented road (set P as an augmented road) :
    1). The path length of P must be an odd number, and the first and last edges are unmatched edges (according to the The matched edge sum needs to pass through another unmatched point. This conclusion can be understood as the first point and the last point are both unmatched points , which can be observed in the augmented path in Fig.3)

    2). Numbering the augmented path, all odd-numbered edges are not in M, and even-numbered edges are in M.

    3). P can get a larger matching graph through the inversion operation, one more than the original match (the inversion operation means that the unmatched side becomes the matched side, and the matched side becomes the unmatched side. This conclusion According to conclusion 1). and the concept of alternate roads, this conclusion can be obtained)

    4). If and only if there is no augmenting path on the graph M, then the graph M is a maximum matching . So the idea of ​​the Hungarian algorithm is: keep looking for augmenting paths and increase the number of matches .

2. Overview of the Hungarian Algorithm

  • The Hungarian algorithm is mainly used to solve two problems: finding the maximum number of matches and the minimum number of points covered in a bipartite graph .

1. Maximum matching problem

  • After reading the above, I believe readers will feel confused: What is this? What's the use? So we manipulated this bipartite graph a bit, and changed it into the following:
    insert image description here
    Now Boys and Girls are two point sets respectively, and the points inside are boys and girls respectively, and the side indicates that there is an "ambiguous relationship" between them.
  • The maximum matching problem is equivalent to , if you are a matchmaker and can match any pair of men and women who have an affair, how many couples can you match at most? ( Mathematical expression: how many edges without common endpoints can be found in the bipartite graph )
  • Now let's see how the Hungarian algorithm works:
    • Let's start from B1 (men and women are equal, it is also possible to look from the girl's side), he has an affair with G2, then we will temporarily connect him to G2 (note that this is just your idea on paper as a matchmaker, You have not really acted, and the arrangements at this time are temporary).
      insert image description here
    • Let's look at B2, B2 also likes G2, and at this time G2 has already "become famous" (although it is only our imagination), so what should we do? Let's go back and look at G2's currently assigned boyfriend, which is B1. Does B1 have any other options? Yes, G4, G4 has not been arranged yet, then we will arrange G4 for B1.
      insert image description here
    • Then B3, B3 can be directly matched with G1, there is no problem. As for B4, he only loves G4, and G4 is currently paired with B1. In addition to G4, B1 can also choose G2, but if B1 chooses G2, G2's original configuration, B2, has no choice. We went around in a big circle and found that B4 can only be destined to be single, poor. (In fact, G3, which has never been considered, is even more pitiful)
      insert image description here
  • This is the process of the Hungarian algorithm. As for the specific implementation, let's take a look at the code:
int M, N;            //M, N分别表示左、右侧集合的元素数量
int Map[MAXM][MAXN]; //邻接矩阵存图
int p[MAXN];         //记录当前右侧元素所对应的左侧元素
bool vis[MAXN];      //记录右侧元素是否已被访问过
bool match(int i)
{
    
    
    for (int j = 1; j <= N; ++j)
        if (Map[i][j] && !vis[j]) //有边且未访问
        {
    
    
            vis[j] = true;                 //记录状态为访问过
            if (p[j] == 0 || match(p[j])) //如果暂无匹配,或者原来匹配的左侧元素可以找到新的匹配
            {
    
    
                p[j] = i;    //当前左侧元素成为当前右侧元素的新匹配
                return true; //返回匹配成功
            }
        }
    return false; //循环结束,仍未找到匹配,返回匹配失败
}
int Hungarian()
{
    
    
    int cnt = 0;
    for (int i = 1; i <= M; ++i)
    {
    
    
        memset(vis, 0, sizeof(vis)); //重置vis数组
        if (match(i))
            cnt++;
    }
    return cnt;
}

In fact, the process is consistent with what we described above. Note that a recursive trick is used here, we keep recursing down, trying to find a suitable match .

  • Note: A perfect match must be a maximum match, but a maximum match is not necessarily a perfect match .

2. Minimum point coverage problem

  • Another problem about bipartite graphs is finding the minimum point cover: we want to find the fewest points such that all edges of the bipartite graph have at least one endpoint among these points. In other words, if you delete the edges containing these points, you can delete all the edges .
    insert image description here
    Why can this be solved with the Hungarian algorithm? If you think I'm going to talk about it for a long time, you're wrong. We only need a theorem: the
    maximum number of matches in a bipartite graph is equal to the minimum number of point covers in this graph.

3. The core of the Hungarian algorithm

  • The core of the Hungarian algorithm is to constantly find augmenting paths to expand the matching set M.
    We give examples to understand.
    insert image description here
    We look for the maximum matching as shown above.

    (1) First, the M set is empty (that is, there is no edge in it), and then start to look for the augmented path from X1. Following the above principles, we can only look for it in Yi, find the path Y1, (X1, Y1), and meet the conditions , negate, and add the path (X1, Y1) to M.
    insert image description here
    (2) Next, we find the X2 point. Follow the principle, find Y1, Y1 is not an uncovered point, at this time we have two options, one is depth search, the other is breadth search, we use depth first, although Y1 is not an uncovered point, (X2, Y1) is not augmented Road, but Y1 is connected to X1, and X1 is connected to Y3, we consider ( X2,Y1,X1,Y3 ) this path, odd number? Alternate left and right? The start and end points are not covered? Odd paths do not belong to M Even paths belong to? Satisfy all augmenting path conditions, so this is an augmenting path, and then negate it to get the following figure.
    insert image description here
    (3) Now there are two paths in the M set, and since we have found an augmented path, the number of edges in M ​​increases. Therefore, the augmenting path is the core of the Hungarian algorithm. Every time an augmenting path is found, it means that the number of edges in the M set will increase by 1. When the augmenting path cannot be found, the number of edges in M ​​at this time is our two The maximum number of matches for a partial graph.

    How do we find this path? Starting from X2, we first find Y1. Y1 is not an uncovered point. We consider the original matching point X1 of Y1, start looking for the augmenting path from X1, and find Y3. When X1 When there is a Zengguang road, add the two paths of (X1,Y1)(X2,Y1) to still satisfy the Zengguang road condition.

    So based on our above understanding, we can give the pseudo code for finding the augmented path :

  while(找到Xi的关联顶点Yj){
    
    
          if(顶点Yj不在增广路径上){
    
    
                将Yj加入增广路
               if(Yj是未覆盖点或者Yj的原匹配点Xk能找到增广路径){
    
     //扩充集合M
                      将Yj的匹配点改为Xi;
                      返回true
           }
      }
               返回false
}

Searching from X2 is based on depth-first, what if it is based on breadth-first? Then X2 will find Y2.

4. Hungarian Algorithm Implementation

  • Depth-first Hungarian algorithm C language code:
typedef struct tagMaxMatch{
    
    
    int edge[COUNT][COUNT];
    bool on_path[COUNT];
    int path[COUNT];
    int max_match;
}GRAPH_MATCH;

void outputRes(int *path){
    
    
    for (int i = 0 ; i<COUNT; i++) {
    
    
        printf("%d****%d\n",i,*(path+i));   //Yj在前 Xi在后
    }
}

void clearOnPathSign(GRAPH_MATCH *match){
    
    
    for (int j = 0 ; j < COUNT ; j++) {
    
    
        match->on_path[j] = false;
    }
   
}
//dfs算法
bool FindAugPath(GRAPH_MATCH *match , int xi){
    
    
    
    for (int yj = 0 ; yj < COUNT; yj++) {
    
    
        if ( match->edge[xi][yj] == 1 && !match->on_path[yj]) {
    
     //如果yi和xi相连且yi没有在已经存在的增广路经上
             match->on_path[yj] = true;
            if (match->path[yj] == -1 || FindAugPath(match,match->path[yj])) {
    
     // 如果是yi是一个未覆盖点或者和yi相连的xk点能找到增广路经,
                  match->path[yj] = xi; //yj点加入路径;
                  return true;
            }
        }
    }
    return false;
}

void Hungary_match(GRAPH_MATCH *match){
    
    
    for (int xi = 0; xi<COUNT ; xi++) {
    
    
          FindAugPath(match, xi);
          clearOnPathSign(match);
    }
    outputRes(match->path);
}

int main() {
    
    
    GRAPH_MATCH *graph = (GRAPH_MATCH *)malloc(sizeof(GRAPH_MATCH));
    for (int i = 0 ; i < COUNT ; i++) {
    
    
        for (int j = 0 ; j < COUNT ; j++) {
    
    
            graph->edge[i][j] = 0;
        }
    }
    graph->edge[0][1] = 1;
    graph->edge[0][0] = 1;
    graph->edge[1][1] = 1;
    graph->edge[1][2] = 1;
    graph->edge[2][1] = 1;
    graph->edge[2][0] = 1;
    graph->edge[3][2] = 1;
    
    for (int j = 0 ; j < COUNT ; j++) {
    
    
        graph->path[j] = -1;
        graph->on_path[j] = false;
    }
    
    Hungary_match(graph);   
}

Guess you like

Origin blog.csdn.net/yohnyang/article/details/130589984
Recommended