标签:
最大二分图匹配,O(n^3).
1 /* 2255 */ 2 #include <iostream> 3 #include <algorithm> 4 #include <cstdio> 5 #include <cstring> 6 #include <cstdlib> 7 using namespace std; 8 9 #define MAXN 305 10 #define INF 0xfffffff 11 12 int w[MAXN][MAXN]; 13 int link[MAXN]; 14 int Lx[MAXN], Ly[MAXN]; 15 int slack; 16 bool S[MAXN], T[MAXN]; 17 int n; 18 19 bool dfs(int i) { 20 S[i] = true; 21 for (int j=1; j<=n; ++j) { 22 if (T[j]) 23 continue; 24 int tmp = Lx[i]+Ly[j]-w[i][j]; 25 if (tmp == 0) { 26 T[j] = true; 27 if (!link[j] || dfs(link[j])) { 28 link[j] = i; 29 return true; 30 } 31 } else if (slack > tmp) { 32 slack = tmp; 33 } 34 } 35 return false; 36 } 37 38 void update() { 39 for (int i=1; i<=n; ++i) { 40 if (S[i]) Lx[i] -= slack; 41 if (T[i]) Ly[i] += slack; 42 } 43 } 44 45 void KM() { 46 int i, j, k; 47 48 memset(link, 0, sizeof(link)); 49 memset(Lx, 0, sizeof(Lx)); 50 memset(Ly, 0, sizeof(Ly)); 51 for (i=1; i<=n; ++i) 52 for (j=1; j<=n; ++j) 53 Lx[i] = max(Lx[i], w[i][j]); 54 for (i=1; i<=n; ++i) { 55 for (;;) { 56 memset(S, false, sizeof(S)); 57 memset(T, false, sizeof(T)); 58 slack = INF; 59 if (dfs(i)) 60 break; 61 else 62 update(); 63 } 64 } 65 } 66 67 int main() { 68 int i, j, k; 69 int ans; 70 71 #ifndef ONLINE_JUDGE 72 freopen("data.in", "r", stdin); 73 #endif 74 75 while (scanf("%d",&n)!=EOF) { 76 for (i=1; i<=n; ++i) 77 for (j=1; j<=n; ++j) 78 scanf("%d", &w[i][j]); 79 KM(); 80 for (ans=0,i=1; i<=n; ++i) 81 if (link[i]) 82 ans += w[link[i]][i]; 83 printf("%d\n", ans); 84 } 85 86 return 0; 87 }
标签:
原文地址:http://www.cnblogs.com/bombe1013/p/4338905.html