#include#include #define M 310 #define inf 0x3f3f3f3f int n,nx,ny; int link[M],lx[M],ly[M],slack[M]; //lx,ly為頂標,nx,ny分別為x點集y點集的個數 int visx[M],visy[M],w[M][M]; int DFS(int x) { visx[x] = 1; for (int y = 1;y <= ny;y ++) { if (visy[y]) continue; int t = lx[x] + ly[y] - w[x][y]; if (t == 0) // { visy[y] = 1; if (link[y] == -1||DFS(link[y])) { link[y] = x; return 1; } } else if (slack[y] > t) //不在相等子圖中slack 取最小的 slack[y] = t; } return 0; } int KM() { int i,j; memset (link,-1,sizeof(link)); memset (ly,0,sizeof(ly)); for (i = 1;i <= nx;i ++) //lx初始化為與它關聯邊中最大的 for (j = 1,lx[i] = -inf;j <= ny;j ++) if (w[i][j] > lx[i]) lx[i] = w[i][j]; for (int x = 1;x <= nx;x ++) { for (i = 1;i <= ny;i ++) slack[i] = inf; while (1) { memset (visx,0,sizeof(visx)); memset (visy,0,sizeof(visy)); if (DFS(x)) //若成功(找到了增廣軌),則該點增廣完成,進入下一個點的增廣 break; //若失敗(沒有找到增廣軌),則需要改變一些點的標號,使得圖中可行邊的數量增加。 //方法為:將所有在增廣軌中(就是在增廣過程中遍歷到)的X方點的標號全部減去一個常數d, //所有在增廣軌中的Y方點的標號全部加上一個常數d int d = inf; for (i = 1;i <= ny;i ++) if (!visy[i]&&d > slack[i]) d = slack[i]; for (i = 1;i <= nx;i ++) if (visx[i]) lx[i] -= d; for (i = 1;i <= ny;i ++) //修改頂標後,要把所有不在交錯樹中的Y頂點的slack值都減去d if (visy[i]) ly[i] += d; else slack[i] -= d; } } int res = 0; for (i = 1;i <= ny;i ++) if (link[i] > -1) res += w[link[i]][i]; return res; } int main () { int i,j; while (scanf ("%d",&n)!=EOF) { nx = ny = n; // memset (w,0,sizeof(w)); for (i = 1;i <= n;i ++) for (j = 1;j <= n;j ++) scanf ("%d",&w[i][j]); int ans = KM(); printf ("%d\n",ans); } return 0; }