poj_2195_going home_ minimum cost maximum flow

Source: Internet
Author: User
Going Home
Time limit:1000ms Memory limit:65536k
Total submissions:20807 accepted:10543

Description
On a grid map there is n little men and N houses. In each unit time, every little mans can move one unit step, either horizontally, or vertically, to a adjacent point. For each little mans, you need to pay a $ fee for every step he moves, until he enters a house. The task is complicated with the restriction, each house can accommodate only one little man.

Your task is to compute the minimum amount of money you need to pay in order to send these n little men into those n Diffe Rent houses. The input is a map of the scenario, a '. ' means an empty space, an ' H ' represents a house on that point, and am ' m ' indica TES There is a little man on this point.

You can think of all the the grid map as a quite large square, so it can hold n little men at the same time; Also, it is the okay if a little man steps on a grid with a house without entering this house.

Input
There is one or more test cases in the input. Each case starts with a line giving-integers n and m, where N is the number of rows of the map, and M are the number of Columns. The rest of the input would be N lines describing the map. Assume both N and M are between 2 and inclusive. There would be the same number of ' H ' s and ' M's on the map; And there'll is at the most houses. Input would terminate with 0 0 for N and M.

Output
For each test case, the output one line with the single integer, which are the minimum amount, in dollars, and you need to pay.

Sample Input

2 2
. m
H.
5 5
HH.. M
.....
.....
.....
Mm.. H
7 8
... H....
... H....
... H....
Mmmhmmmm
... H....
... H....
... H....
0 0

Sample Output

2
10

28


Test instructions: M personal and M house, each house to arrange a person, each move one step costs for 1,

The minimum amount of money that everyone needs after arranging the house.


Manhattan Distance: For example, in the plane, the coordinates (x1, y1) of the I point and coordinates (x2, y2) of the J Point of the Manhattan distance are: D (i,j) =| x1-x2|+| y1-y2|.

Build: Network flow, build a hyper-source 0, super-sink E

1> 0 to build an edge for everyone, with a capacity of 1 costs 0

2> all the people to all houses built a side capacity of 1, the positive costs for use: ABS (X Man-to-house) +abs (Y man-y House).

The reverse is:-forward

3> all houses to the Super Sink (e) to build an edge, E = number of people + all sides + 1. Capacity is 1 and the cost is 0


#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> #include <
Queue> using namespace std;
#define MAX 202 #define INF 0x3f3f3f3f bool Vis[max];
int Dist[max];
int Pre[max];
int Cost[max][max];
int Cap[max][max];

int E, SH, SM, res; struct Node {int x, y;}

Hos[max], Man[max];
   	BOOL SPFA ()//Find the shortest path {int i, u;
	memset (dist,0x3f,sizeof (Dist)); 
    memset (vis,false,sizeof (VIS));
    Queue <int> q;
    Dist[0] = 0;
    Vis[0] = true;
    while (!q.empty ()) Q.pop ();
    Q.push (0);
        while (!q.empty ()) {u = Q.front ();
        Q.pop ();
        Vis[u] = false;
            for (i = 1; I <= E; i++) {if (Cap[u][i] && dist[i] > Dist[u] + cost[u][i])
                {Dist[i] = Dist[u] + cost[u][i];
                Pre[i] = u;
                    if (!vis[i]) {vis[i] = true;
                Q.push (i);
     }       }}} if (Dist[e]! = INF) {return true;
} return false;
    } void Change ()//update traffic {int i, Min;
    Min = INF;
    for (i = E; I! = 0; i = pre[i]) {min = min (min, cap[pre[i]][i]);
        } for (i = E; I! = 0; i = pre[i]) {cap[pre[i]][i] = Min;
        Cap[i][pre[i]] + = Min;
    Res + = cost[pre[i]][i] * Min;
    }} int main () {int I, j, N, M;
        while (scanf ("%d%d", &n,&m) && (n+m)) {char C; SH = 0;
        SM = 0;
        memset (Cap, 0, sizeof (CAP)); for (i = 0; i < n; i++) {for (j = 0; J < m; J + +) {scanf ("\n%c", &A 
                MP;C);
                    if (c = = ' H ') {sh++;
                    hos[sh].x = i;    
                Hos[sh].y = j;
                    } else if (c = = ' m ') {sm++;
                    man[sm].x = i; 
               Man[sm].y = j; }}} E = sh + sm + 1;//for (i = 1; I <= sm; i++)//Hyper source is 0 0 to everyone   {Cap[0][i] = 1;  Capacity of 1 Cost[0][i] = 0; 
	            The cost is 0} for (i = 1; I <= sm; i++)//everyone to each house {for (j = 1; j <= Sh; j + +) {
	            CAP[I][SM+J] = 1;      COST[I][SM+J] = ABS (man[i].x-hos[j].x) + ABS (MAN[I].Y-HOS[J].Y);                                      Forward side cost cost[sm+j][i] =-cost[i][sm+j];
	        Reverse edge Charges}} for (i = 1; I <= sh; i++)//All houses to e-over sinks for e {cap[sm+i][e] = 1;
	    Cost[sm+i][e] = 0;
        } res = 0;
        while (SPFA ()) {change ();
    } printf ("%d\n", res);
} return 0; }



Templates on the Challenge program


#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm> #include <
vector> #include <queue> #define MAX namespace using Std;  
struct LOC {int x, y;  
}coordinate[max];  struct Edge {int to,cap,cost,rev;  
End, capacity, cost, reverse side};  Vector<edge> G[max];  
adjacency Table of graph queue<int> Q;  
Char Map[max][max];   int Dist[max];  Record shortest path int Prevv[max];  The shortest-circuiting precursor point int preve[max];  
The edge bool Vis[max of the precursor point);  
int n,m;  
int sh,sm; 

int E; Add an edge void Add_edge (int from,int to,int cap,int cost) (int.) {G[from].push_back) {To,ca (Edge) to the graph, from the from-to-to capacity for cap costs  
    P,cost,g[to].size ()});  
G[to].push_back (Edge) {from,0,-cost,g[from].size ()-1});  
    } int Min_cost_flow (int f)//SPFA to find the shortest path and record the route {int res=0;  
    int u,v;  
        while (f>0) {memset (dist,0x3f,sizeof (Dist));  
        memset (vis,0,sizeof (VIS));  
        dist[0]=0;  
        Vis[0]=1;  
        Q.push (0); while (!  
    Q.empty ())    {U=q.front ();  
            Q.pop (); vis[u]=0;  
                For (V=0;v<g[u].size (); v++) {Edge &e=g[u][v];  
                    if (e.cap>0&&dist[e.to]>dist[u]+e.cost) {dist[e.to]=dist[u]+e.cost;  
                    Prevv[e.to]=u;  
                    Preve[e.to]=v;  
                        if (!vis[e.to]) {Q.push (e.to);  
                    Vis[e.to]=1;  
        }}}} f-=1; 
        Res+=dist[e];  
            for (V=e;v!=0;v=prevv[v])//change path traffic {Edge &e = g[prevv[v]][preve[v]];
			E.cap-= 1;   
            G[v][e.rev].cap + = 1;  
        G[e.to][e.rev].cap + = 1;  
}} return res;
		} int main () {while (scanf ("%d%d", &n,&m) && (n+m)) {int i,j,k;
		GetChar ();
		SH = 0,sm = 0; for (i=0;i<max;i++) {g[i].clear ();
			} for (i=0;i<n;i++) {gets (map[i]);
					for (j=0;j<m;j++) {if (map[i][j] = = ' H ') {sh + +;
					coordinate[sh].x = i;
					Coordinate[sh].y = j; Add_edge (0,sh,1,0);//Super Source Connection Everyone}}} for (i=0;i<n;i++) {for (j=0;j<m;j++) {if (map[i][j] =
					= ' m ') {SM + +; 
					for (k=1;k<=sh;k++) {Add_edge (K,sh+sm,1,abs (coordinate[k].x-i) +abs (coordinate[k].y-j));//each person connects to each house
		}}}} E = Sh+sm+1;
		for (i=sh+1;i<e;i++) {Add_edge (i,e,1,0);//each house is connected to the super sink point} int f = min (SH,SM);
	printf ("%d\n", Min_cost_flow (f));
} return 0;
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.