本文主要是介绍HDU 2255 奔小康赚大钱(KM完美匹配),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
HDU 2255 奔小康赚大钱
题目链接
题意:中文题
思路:就是KM的裸题
代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;const int MAXNODE = 305;typedef int Type;
const Type INF = 0x3f3f3f3f;struct KM {int n;Type g[MAXNODE][MAXNODE];Type Lx[MAXNODE], Ly[MAXNODE], slack[MAXNODE];int left[MAXNODE], right[MAXNODE];bool S[MAXNODE], T[MAXNODE];void init(int n) {this->n = n;}void add_Edge(int u, int v, Type val) {g[u][v] = val;}bool dfs(int i) {S[i] = true;for (int j = 0; j < n; j++) {if (T[j]) continue;Type tmp = Lx[i] + Ly[j] - g[i][j];if (!tmp) {T[j] = true;if (left[j] == -1 || dfs(left[j])) {left[j] = i;right[i] = j;return true;}} else slack[j] = min(slack[j], tmp);}return false;}void update() {Type a = INF;for (int i = 0; i < n; i++)if (!T[i]) a = min(a, slack[i]);for (int i = 0; i < n; i++) {if (S[i]) Lx[i] -= a;if (T[i]) Ly[i] += a;}}int km() {for (int i = 0; i < n; i++) {left[i] = -1; right[i] = -1;Lx[i] = -INF; Ly[i] = 0;for (int j = 0; j < n; j++)Lx[i] = max(Lx[i], g[i][j]);}for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) slack[j] = INF;while (1) {for (int j = 0; j < n; j++) S[j] = T[j] = false;if (dfs(i)) break;else update();}}int ans = 0;for (int i = 0; i < n; i++)ans += g[i][right[i]];return ans;}
} gao;int n;int main() {while (~scanf("%d", &n)) {gao.n = n;for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)scanf("%d", &gao.g[i][j]);printf("%d\n", gao.km());}return 0;
}
这篇关于HDU 2255 奔小康赚大钱(KM完美匹配)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!