poj 2195 Going Home 最小费用流

http://poj.org/problem?id=2195

题意:m表示人,H表示房子,一个人只能进一个房子,一个房子也只能进去一个人,房子数等于人数,现在要让所有人进入房子,求所有人都进房子最短的路径。

题解:费用流。取超级源点s=0,超级汇点t=N;s与人建边,房子与t建边,这些边费用为0容量为1;然后人与房子建边,容量为1费用为距离。

代码:

#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>

using namespace std;
const int maxn=400;
const int maxm=50005;
const int inf=0x3f3f3f3f;
struct Edge{
	int to,next,cap,flow,cost;
}edge[maxm];
int tol;
int head[maxn];
int pre[maxn],dis[maxn];
bool vis[maxn];
int N;
void init(int n){
	N=n;
	tol=0;
	memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int cap,int cost){
	edge[tol].to=v;
	edge[tol].cost=cost;
	edge[tol].cap=cap;
	edge[tol].flow=0;
	edge[tol].next=head[u];
	head[u]=tol++;
	edge[tol].to=u;
	edge[tol].cost=-cost;
	edge[tol].cap=0;
	edge[tol].flow=0;
	edge[tol].next=head[v];
	head[v]=tol++;
}
bool spfa(int s,int t){
	queue<int>q;
	int i;
	for(i=0;i<N;i++){
		dis[i]=inf;
		vis[i]=false;
		pre[i]=-1;
	}
	dis[s]=0;
	vis[s]=true;
	q.push(s);
	while(!q.empty()){
		int u=q.front();
		q.pop();
		vis[u]=false;
		for(i=head[u];i!=-1;i=edge[i].next){
			int v=edge[i].to;
			if(edge[i].cap>edge[i].flow&&dis[v]>dis[u]+edge[i].cost){
				dis[v]=dis[u]+edge[i].cost;
				pre[v]=i;
				if(!vis[v]){
					vis[v]=true;
					q.push(v);
				}
			}
		}
	}
	if(pre[t]==-1)return false;
	else return true;
}
int mincostmaxflow(int s,int t,int &cost){
	int flow=0;
	cost=0;
	while(spfa(s,t)){
		int Min=inf;
		int i;
		for(i=pre[t];i!=-1;i=pre[edge[i^1].to]){
			if(Min>edge[i].cap-edge[i].flow)Min=edge[i].cap-edge[i].flow;
		}
		for(i=pre[t];i!=-1;i=pre[edge[i^1].to]){
			edge[i].flow+=Min;
			edge[i^1].flow-=Min;
			cost+=edge[i].cost*Min;
		}
		flow+=Min;
	}
	return flow;
}
char mp[105][105];
struct node{
	int x, y;
}man[105],house[105];
int myabs(int x){
	return x>0?x:-x;
}
int len(node a,node b){
	return myabs(a.x-b.x)+myabs(a.y-b.y);
}
int main()
{
	int n,m,i,j;
	int num_man,num_house;
	while(~scanf("%d%d",&n,&m)){
		if(n==0&&m==0)break;
		num_man=0;
		num_house=0;
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				cin>>mp[i][j];
				if(mp[i][j]=='m'){
					man[num_man].x=i;
					man[num_man].y=j;
					num_man++;
				}
				else if(mp[i][j]=='H'){
					house[num_house].x=i;
					house[num_house].y=j;
					num_house++;
				}
			}
		}
		init(2*num_house+2);
		for(i=0;i<num_man;i++){
			addedge(0,i+1,1,0);
			for(j=0;j<num_house;j++){
				addedge(i+1,j+num_house+1,1,len(man[i],house[j]));
			}
		}
		for(i=0;i<num_house;i++)addedge(i+num_house+1,2*num_house+1,1,0);
		int mincost;
		mincostmaxflow(0,2*num_house+1,mincost);
		printf("%d\n",mincost);
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nwpu2017300135/article/details/81454505
今日推荐