• HDU 1533 Going Home(KM完美匹配)


    HDU 1533 Going Home

    题目链接

    题意:就是一个H要相应一个m,使得总曼哈顿距离最小

    思路:KM完美匹配,因为是要最小。所以边权建负数来处理就可以

    代码:

    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    using namespace std;
    
    const int MAXNODE = 105;
    
    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];
    	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;
    					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;
    			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[left[i]][i];
    		return ans;
    	}
    } gao;
    
    const int N = 105;
    int n, m;
    char str[N];
    
    struct Point {
    	int x, y;
    	Point() {}
    	Point(int x, int y) {
    		this->x = x;
    		this->y = y;
    	}
    } hp[N], mp[N];
    
    int dis(Point a, Point b) {
    	return abs(a.x - b.x) + abs(a.y - b.y);
    }
    
    int hn, mn;
    
    int main() {
    	while (~scanf("%d%d", &n, &m) && n || m) {
    		hn = mn = 0;
    		for (int i = 0; i < n; i++) {
    			scanf("%s", str);
    			for (int j = 0; j < m; j++) {
    				if (str[j] == 'H') hp[hn++] = Point(i, j);
    				if (str[j] == 'm') mp[mn++] = Point(i, j);
    			}
    		}
    		gao.n = hn;
    		for (int i = 0; i < hn; i++) {
    			for (int j = 0; j < mn; j++) {
    				gao.g[i][j] = -dis(hp[i], mp[j]);
    			}
    		}
    		printf("%d
    ", -gao.km());
    	}
    	return 0;
    }


  • 相关阅读:
    我理解的软件编码规范
    分享:读完这100篇论文,你就能成大数据高手!
    Docker简明教程
    几种源码管理工具的使用
    《构建之法.现代软件工程》教材读后问题
    三层神经网络自编码算法推导和MATLAB实现 (转载)
    aa
    奇异值分解(SVD)原理详解及推导(转载)
    奇异值分解(SVD) --- 几何意义 (转载)
    奇异值分解(SVD)原理详解及推导 (转载)
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/6964452.html
Copyright © 2020-2023  润新知