KM匹配模板

 1 int G[N][N];
 2 int lx[N], ly[N];
 3 int slack[N];
 4 int match[N];
 5 bool visitx[N], visity[N];
 6 int n;
 7 
 8 bool Hungary(int u)
 9 {
10     visitx[u] = true;
11     for(int i = 0; i < n; ++i)
12     {
13         if(visity[i])
14             continue;
15         else
16         {
17             if(lx[u] + ly[i] == G[u][i])
18             {
19                 visity[i] = true;
20                 if(match[i] == -1 || Hungary(match[i]))
21                 {
22                     match[i] = u;
23                     return true;
24                 }
25             }
26             else
27                 slack[i] = min(slack[i], lx[u] + ly[i] - G[u][i]);
28         }
29     }
30     return false;
31 }
32 
33 void KM_perfect_match()
34 {
35     int temp;
36     memset(match, -1, sizeof(match));
37     memset(lx, 0, sizeof(lx));
38     memset(ly, 0, sizeof(ly));
39     for(int i = 0; i < n; ++i)
40         for(int j = 0; j < n; ++j)
41             lx[i] = max(lx[i], G[i][j]);
42     for(int i = 0; i < n; ++i)
43     {
44         for(int j = 0; j < n; ++j)
45                 slack[j] = INT_MAX;
46         while(1)
47         {            
48             memset(visitx, false, sizeof(visitx));
49             memset(visity, false, sizeof(visity));
50             if(Hungary(i))
51                 break;
52             else
53             {
54                 temp = INT_MAX;
55                 for(int j = 0; j < n; ++j)
56                     if(!visity[j])
57                         temp = min(temp, slack[j]);
58                 for(int j = 0; j < n; ++j)
59                 {
60                     if(visitx[j])
61                         lx[j] -= temp;
62                     if(visity[j])
63                         ly[j] += temp;
64                     else
65                         slack[j] -= temp;
66                 }
67             }
68         }
69     }
70 }
View Code

 

posted @ 2015-07-26 21:48  UsedRose  阅读(152)  评论(0编辑  收藏  举报