题目链接:
On a grid map there are n little men and n houses. In each unit time, every little man can move one unit step, either horizontally, or vertically, to an adjacent point. For each little man, you need to pay a $1 travel fee for every step he moves, until he enters a house. The task is complicated with the restriction that 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 different 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' indicates there is a little man on that point.
You can think of each point on the grid map as a quite large square, so it can hold n little men at the same time; also, it is okay if a little man steps on a grid with a house without entering that house.
题意描述:在n*m的矩阵格子里有x个人要走到x个房间里,每个房间里只能放一人,人在目前所在的格子处向上下左右相邻的格子走一步就花费1美元,问最后全部的人走到房间后最小的花费。
算法分析:这道题可以用KM算法或者最小费用最大流算法解之,这里讲解一下最小费用最大流的方法。
新增源点from和汇点to,from->人(w为1,cost为0)
房子->to(w为1,cost为0)
每个人->每间房(w为1,cost为最短路径的美元花费)
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #define inf 0x7fffffff 10 using namespace std; 11 const int maxn=10000+100; 12 const int M = 40000+100; 13 14 int n,m,from,to; 15 struct node 16 { 17 int v,flow,cost; 18 int next; 19 }edge[M*4]; 20 int head[maxn],edgenum; 21 int dis[maxn],pre[maxn],pid[maxn],vis[maxn]; 22 23 void add(int u,int v,int flow,int cost) 24 { 25 edge[edgenum].v=v ;edge[edgenum].flow=flow ; 26 edge[edgenum].cost=cost ;edge[edgenum].next=head[u]; 27 head[u]=edgenum++; 28 29 edge[edgenum].v=u ;edge[edgenum].flow=0; 30 edge[edgenum].cost=-cost ;edge[edgenum].next=head[v]; 31 head[v]=edgenum++; 32 } 33 34 int spfa() 35 { 36 for (int i=1 ;i<=to ;i++) 37 { 38 dis[i]=inf; 39 vis[i]=0; 40 } 41 queue Q; 42 Q.push(from); 43 dis[from]=0; 44 vis[from]=1; 45 while (!Q.empty()) 46 { 47 int u=Q.front() ;Q.pop() ; 48 vis[u]=0; 49 for (int i=head[u] ;i!=-1 ;i=edge[i].next) 50 { 51 int v=edge[i].v; 52 if (edge[i].flow>0 && dis[v]>dis[u]+edge[i].cost) 53 { 54 dis[v]=dis[u]+edge[i].cost; 55 pre[v]=u; 56 pid[v]=i; 57 if (!vis[v]) 58 { 59 vis[v]=1; 60 Q.push(v); 61 } 62 } 63 } 64 } 65 return dis[to]; 66 } 67 68 int mincost() 69 { 70 int aug=0,maxflow=0; 71 int ans=0,tmp=0; 72 while (1) 73 { 74 tmp=spfa(); 75 if (tmp==inf) break; 76 aug=inf; 77 for (int i=to ;i!=from ;i=pre[i]) 78 { 79 if (edge[pid[i] ].flow