标签:tab miss body mmm false push nim bing output
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 23515 | Accepted: 11853 |
2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
2 10 28
1 //2017-08-24 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 #include <algorithm> 6 #include <queue> 7 #include <cmath> 8 9 using namespace std; 10 11 const int N = 1000; 12 const int M = 100000; 13 const int INF = 0x3f3f3f3f; 14 int head[N], tot; 15 struct Edge{ 16 int to, next, c, w;//c为容量,w为单位费用 17 }edge[M]; 18 19 void add_edge(int u, int v, int c, int w){ 20 edge[tot].c = c; 21 edge[tot].w = w; 22 edge[tot].to = v; 23 edge[tot].next = head[u]; 24 head[u] = tot++; 25 26 edge[tot].c = 0; 27 edge[tot].w = -w; 28 edge[tot].to = u; 29 edge[tot].next = head[v]; 30 head[v] = tot++; 31 } 32 33 bool vis[N]; 34 int pre[N], dis[N];//pre记录路径,dis记录到源点的最小花费 35 struct MinCostMaxFlow{ 36 int S, T; 37 int flow, cost; 38 void init(int _S, int _T){ 39 S = _S; 40 T = _T; 41 tot = 0; 42 memset(head, -1, sizeof(head)); 43 } 44 bool spfa(){ 45 memset(vis, 0, sizeof(vis)); 46 memset(dis, INF, sizeof(dis)); 47 dis[S] = 0; 48 vis[S] = 1; 49 queue<int> que; 50 que.push(S); 51 while(!que.empty()){ 52 int u = que.front(); 53 que.pop(); 54 for(int i = head[u]; i != -1; i = edge[i].next){ 55 int v = edge[i].to; 56 if(edge[i].c > 0 && dis[v] > dis[u]+edge[i].w){ 57 dis[v] = dis[u] + edge[i].w; 58 pre[v] = i; 59 if(!vis[v]){ 60 vis[v] = true; 61 que.push(v); 62 } 63 } 64 } 65 vis[u] = 0; 66 } 67 return dis[T] != INF; 68 } 69 int dfs(int &flow){ 70 int u, p, sum = INF, ans = 0; 71 for(u = T; u != S; u = edge[p^1].to){ 72 //记录路径上的最小流值 73 p = pre[u]; 74 sum = min(sum, edge[p].c); 75 } 76 for(u = T; u != S; u = edge[p^1].to){ 77 p = pre[u]; 78 edge[p].c -= sum; 79 edge[p^1].c += sum; 80 ans += sum*edge[p].w; 81 } 82 flow += sum; 83 return ans; 84 } 85 int maxflow(){ 86 cost = 0, flow = 0; 87 while(spfa()){//寻找增广路并增广 88 cost += dfs(flow); 89 } 90 return cost; 91 } 92 }mcmf; 93 94 string grid[N]; 95 int x[N], y[N]; 96 97 int main() 98 { 99 std::ios::sync_with_stdio(false); 100 //freopen("inputD.txt", "r", stdin); 101 int n, m; 102 while(cin>>n>>m && (n || m)){ 103 int cnt_m = 0, cnt_h = 0; 104 int s = N-2, t = N-3; 105 mcmf.init(s, t); 106 for(int i = 0; i < n; i++){ 107 cin>>grid[i]; 108 for(int j = 0; j < m; j++){ 109 if(grid[i][j] == ‘H‘){ 110 add_edge(s, cnt_h, 1, 0); 111 x[cnt_h] = i; 112 y[cnt_h++] = j; 113 } 114 } 115 } 116 for(int i = 0; i < n; i++){ 117 for(int j = 0; j < m; j++){ 118 if(grid[i][j] == ‘m‘){ 119 add_edge(cnt_h+cnt_m, t, 1, 0); 120 for(int k = 0; k < cnt_h; k++){ 121 add_edge(k, cnt_h+cnt_m, 1, abs(i-x[k])+abs(j-y[k])); 122 } 123 cnt_m++; 124 } 125 } 126 } 127 cout<<mcmf.maxflow()<<endl; 128 } 129 130 return 0; 131 }
标签:tab miss body mmm false push nim bing output
原文地址:http://www.cnblogs.com/Penn000/p/7425425.html