七月冒泡第二题。
#include <iostream> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <cmath> #include <vector> #include <queue> #include <algorithm> #include <map> using namespace std; const int maxn = 310; const int INF = 0x3f3f3f3f; int n; int W[maxn][maxn]; int Lx[maxn], Ly[maxn]; int Left[maxn]; bool S[maxn], T[maxn]; bool match(int i) { S[i] = 1; for(int j = 1; j <= n; j++) if(Lx[i]+Ly[j] == W[i][j] && !T[j]) { T[j] = 1; if(!Left[j] || match(Left[j])) { Left[j] = i; return 1; } } return 0; } void update() { int a = INF; for(int i = 1; i <= n; i++) if(S[i]) for(int j = 1; j <= n; j++) if(!T[j]) a = min(a, Lx[i]+Ly[j]-W[i][j]); for(int i = 1; i <= n; i++) { if(S[i]) Lx[i] -= a; if(T[i]) Ly[i] += a; } } void KM() { for(int i = 1; i <= n; i++) { Left[i] = Lx[i] = Ly[i] = 0; for(int j = 1; j <= n; j++) Lx[i] = max(Lx[i], W[i][j]); } for(int i = 1; i <= n; i++) { for(;;) { for(int j = 1; j <= n; j++) S[j] = T[j] = 0; if(match(i)) break; else update(); } } } inline void readint(int &x) { char c; c = getchar(); while(!isdigit(c)) c = getchar(); x = 0; while(isdigit(c)) x = x*10+c-'0', c = getchar(); } void read_case() { for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) { readint(W[i][j]); } } void solve() { read_case(); KM(); int ans = 0; for(int i = 1; i <= n; i++) ans += W[Left[i]][i]; printf("%d\n", ans); } int main() { while(~scanf("%d", &n)) { solve(); } return 0; }