标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3299 Accepted Submission(s): 1674
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <vector> 6 #include <queue> 7 #include <cmath> 8 #include <set> 9 using namespace std; 10 11 #define N 105 12 #define inf 999999999 13 14 int max(int x,int y){return x>y?x:y;} 15 int min(int x,int y){return x<y?x:y;} 16 int abs(int x,int y){return x<0?-x:x;} 17 18 struct KM { 19 int n, m; 20 int g[N][N]; 21 int Lx[N], Ly[N], slack[N]; 22 int left[N], right[N]; 23 bool S[N], T[N]; 24 25 void init(int n, int m) { 26 this->n = n; 27 this->m = m; 28 memset(g, 0, sizeof(g)); 29 } 30 31 void add_Edge(int u, int v, int val) { 32 g[u][v] += val; 33 } 34 35 bool dfs(int i) { 36 S[i] = true; 37 for (int j = 0; j < m; j++) { 38 if (T[j]) continue; 39 int tmp = Lx[i] + Ly[j] - g[i][j]; 40 if (!tmp) { 41 T[j] = true; 42 if (left[j] == -1 || dfs(left[j])) { 43 left[j] = i; 44 right[i] = j; 45 return true; 46 } 47 } else slack[j] = min(slack[j], tmp); 48 } 49 return false; 50 } 51 52 void update() { 53 int a = inf; 54 for (int i = 0; i < m; i++) 55 if (!T[i]) a = min(a, slack[i]); 56 for (int i = 0; i < n; i++) 57 if (S[i]) Lx[i] -= a; 58 for (int i = 0; i < m; i++) 59 if (T[i]) Ly[i] += a; 60 } 61 62 int km() { 63 memset(left, -1, sizeof(left)); 64 memset(right, -1, sizeof(right)); 65 memset(Ly, 0, sizeof(Ly)); 66 for (int i = 0; i < n; i++) { 67 Lx[i] = -inf; 68 for (int j = 0; j < m; j++) 69 Lx[i] = max(Lx[i], g[i][j]); 70 } 71 for (int i = 0; i < n; i++) { 72 for (int j = 0; j < m; j++) slack[j] = inf; 73 while (1) { 74 memset(S, false, sizeof(S)); 75 memset(T, false, sizeof(T)); 76 if (dfs(i)) break; 77 else update(); 78 } 79 } 80 int ans = 0; 81 for (int i = 0; i < n; i++) { 82 ans += g[i][right[i]]; 83 } 84 return ans; 85 } 86 }kmm; 87 88 int n, m; 89 char map[N][N]; 90 int g[N][N]; 91 92 struct node{ 93 int x, y; 94 node(){} 95 node(int a,int b){ 96 x=a; 97 y=b; 98 } 99 }a[N], b[N]; 100 101 main() 102 { 103 int i, j, k; 104 int nx, ny; 105 while(scanf("%d %d",&n,&m)==2){ 106 if(n==0&&m==0) break; 107 108 for(i=0;i<n;i++) scanf("%s",map[i]); 109 nx=ny=0; 110 memset(g,0,sizeof(g)); 111 for(i=0;i<n;i++){ 112 for(j=0;j<m;j++){ 113 if(map[i][j]==‘m‘) a[nx++]=node(i,j); 114 if(map[i][j]==‘H‘) b[ny++]=node(i,j); 115 } 116 } 117 kmm.init(nx,ny); 118 for(i=0;i<nx;i++){ 119 for(j=0;j<ny;j++){ 120 kmm.add_Edge(i,j,-(abs(a[i].x-b[j].x)+abs(a[i].y-b[j].y))); 121 } 122 } 123 printf("%d\n",-kmm.km()); 124 } 125 }
标签:
原文地址:http://www.cnblogs.com/qq1012662902/p/4638796.html