标签:for tle mic class 范围 dfs pid 老百姓 完美
http://acm.hdu.edu.cn/showproblem.php?pid=2255
代码:
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int maxn = 550; int N; int mp[maxn][maxn]; int exg[maxn], exb[maxn]; int visg[maxn], visb[maxn]; int match[maxn], slack[maxn]; bool dfs(int u) { visg[u] = 1; for(int v = 0; v < N; v ++) { if(visb[v]) continue; int gap = exg[u] + exb[v] - mp[u][v]; if(!gap) { visb[v] = 1; if(match[v] == -1 || dfs(match[v])) { match[v] = u; return true; } } else slack[v] = min(slack[v], gap); } return false; } int KM() { memset(match, -1, sizeof(match)); memset(exb, 0, sizeof(exb)); for(int i = 0; i < N; i ++) { exg[i] = mp[i][0]; for(int j = 1; j < N; j ++) exg[i] = max(exg[i], mp[i][j]); } for(int i = 0; i < N; i ++) { memset(slack, inf, sizeof(slack)); while(1) { memset(visg, 0, sizeof(visg)); memset(visb, 0, sizeof(visb)); if(dfs(i)) break; int d = inf; for(int j = 0; j < N; j ++) if(!visb[j]) d = min(d, slack[j]); for(int j = 0; j < N; j ++) { if(visg[j]) exg[j] -= d; if(visb[j]) exb[j] += d; else slack[j] -= d; } } } int res = 0; for(int i = 0; i < N; i ++) res += mp[match[i]][i]; return res; } int main() { while(~scanf("%d", &N)) { for(int i = 0; i < N; i ++) { for(int j = 0; j < N; j ++) scanf("%d", &mp[i][j]); } printf("%d\n", KM()); } return 0; }
KM 算法求二分图最大权完美匹配(模板题)
标签:for tle mic class 范围 dfs pid 老百姓 完美
原文地址:https://www.cnblogs.com/zlrrrr/p/10670365.html