#include #define relaxMin(a, b) (a) = min((a), (b)) using namespace std; const int MAXN = 510; const int oo = 1E9; int n; int cost[MAXN][MAXN]; int u[MAXN], v[MAXN]; int match[2 * MAXN]; char type[2 * MAXN]; bool Dfs(int vr){ if(type[vr] == '+') return false; type[vr] = '+'; for(int i = 0;i < n;++i) if(cost[vr][i] == u[vr] + v[i]){ if(match[n + i] == -1 || Dfs(match[n + i])){ match[n + i] = vr, match[vr] = i; return true; } else type[n + i] = '+'; } return false; } void HungarianAlg(){ memset(u, 0, sizeof u); memset(v, 0, sizeof v); memset(match, -1, sizeof match); for(int i = 0;i < n;++i){ for(int vr = 0;vr < n;++vr){ if(vr == 0) memset(type, '-', sizeof type); if(match[vr] == -1 && Dfs(vr)) break; if(vr == n - 1){ int delta = oo; for(int i = 0;i < n;++i) for(int j = 0;j < n;++j) if(type[i] == '+' && type[n + j] == '-') relaxMin(delta, cost[i][j] - u[i] - v[j]); for(int i = 0;i < n;++i){ if(type[i] == '+') u[i] += delta; if(type[n + i] == '+') v[i] -= delta; } vr = -1; } } } } int main(){ n = 4; cost[0][0] = 82; cost[0][1] = 83; cost[0][2] = 69; cost[0][3] = 92; cost[1][0] = 77; cost[1][1] = 37; cost[1][2] = 49; cost[1][3] = 92; cost[2][0] = 11; cost[2][1] = 69; cost[2][2] = 5; cost[2][3] = 86; cost[3][0] = 8; cost[3][1] = 9; cost[3][2] = 98; cost[3][3] = 23; HungarianAlg(); for(int i = 0;i < n;++i) cout << i << " -> " << match[i] << '\n'; return 0; }