HDU 2813 One fihgt one(KM最大匹配)

来源:互联网 发布:js 自定义日期选择器 编辑:程序博客网 时间:2024/05/16 14:25

HDU 2813 One fihgt one

题目链接

题意:吕布n个武将,曹操m个,问吕布每个武将参加一场战斗,不能跟同一个武将打,问最小受到伤害

思路:显然的KM最大匹配

代码:

#include <cstdio>#include <cstring>#include <cmath>#include <map>#include <string>#include <algorithm>using namespace std;const int MAXNODE = 505;typedef int Type;const Type INF = 0x3f3f3f3f;struct KM {int n, m;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, int m) {this->n = n;this->m = m;for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)g[i][j] = -INF;}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 < m; 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 < m; i++)if (!T[i]) a = min(a, slack[i]);for (int i = 0; i < n; i++)if (S[i]) Lx[i] -= a;for (int i = 0; i < m; i++)if (T[i]) Ly[i] += a;}Type km() {memset(left, -1, sizeof(left));memset(right, -1, sizeof(right));memset(Ly, 0, sizeof(Ly));for (int i = 0; i < n; i++) {Lx[i] = -INF;for (int j = 0; j < m; j++)Lx[i] = max(Lx[i], g[i][j]);}for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) slack[j] = INF;while (1) {memset(S, false, sizeof(S));memset(T, false, sizeof(T));if (dfs(i)) break;else update();}}Type ans = 0;for (int i = 0; i < n; i++)ans += g[i][right[i]];return -ans;}} gao;int n, m, k;map<string, int> hash[2];int hn[2], w;char a[25], b[25];int get(char *str, int now) {if (!hash[now].count(str)) hash[now][str] = hn[now]++;return hash[now][str];}int main() {while (~scanf("%d%d%d", &n, &m, &k)) {gao.init(n, m);hn[0] = hn[1] = 0;hash[0].clear(); hash[1].clear();while (k--) {scanf("%s%s%d", a, b, &w);int u = get(a, 0);int v = get(b, 1);gao.add_Edge(u, v, -w);}printf("%d\n", gao.km());}return 0;}


0 0
原创粉丝点击