2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
2 10 28通过这个题让我加深了对二分匹配最大权匹配中扩大相等子图的理解。真的是个好题目呀。。。。。。这个题就是反其道而行之。。。#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <climits> #include <cmath> using namespace std; const int N = 105; struct node{ int x, y; }; vector<node>man; vector<node>house; int weight[N][N]; int lx[N], ly[N]; int slack[N]; int match[N]; bool visx[N], visy[N]; int n, m; bool dfs(const int& x) { visx[x] = 1; for (int i = 0; i < m; i ++) { if (visy[i]) continue; int t = weight[x][i]-lx[x]-ly[i]; if (t == 0) { visy[i] = 1; if (match[i] == -1 || dfs(match[i])) { match[i] = x; return true; } } else { slack[i] = min(slack[i], t); } } return false; } void KM() { int temp; memset(ly, 0, sizeof(ly)); for (int i = 0; i < n; i ++) { lx[i] = INT_MAX; for (int j = 0; j < m; j ++) { lx[i] = min(lx[i], weight[i][j]); } } for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) slack[j] = INT_MAX; while (1) { memset(visx, 0, sizeof(visx)); memset(visy, 0, sizeof(visy)); if (dfs(i)) break; temp = INT_MAX; for (int j = 0; j < m; j ++) { if (!visy[j]) temp = min(temp, slack[j]); } for (int j = 0; j < n; j ++) { if (visx[j]) lx[j] += temp; } for (int j = 0; j < m; j ++) { if (visy[j]) ly[j] -= temp; else slack[j] -= temp; } } } } int main() { while (scanf("%d%d", &n, &m), n+m) { man.clear(), house.clear(); node temp; for (int i = 1; i <= n; i ++) { getchar(); for (int j = 1; j <= m; j ++) { char ch = getchar(); if (ch == 'm') { temp.x = i, temp.y = j, man.push_back(temp); } else if (ch == 'H') { temp.x = i, temp.y = j, house.push_back(temp); } } } n = man.size(); m = house.size(); for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { weight[i][j] = abs(man[i].x-house[j].x)+abs(man[i].y-house[j].y); } } memset(match, -1, sizeof(match)); KM(); int ans = 0; for (int i = 0; i < m; i ++) { if (match[i] > -1) ans += weight[match[i]][i]; } printf("%d\n", ans); } return 0; }
原文地址:http://blog.csdn.net/wuhuajunbao/article/details/41985391