hdu1533(费用流模板)

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;

const int maxn=1000;  
const int maxm=100000;  
const int INF=0x3f3f3f3f;  

struct Edge  {  
    int to,next,cap,cost;  
    Edge(){}
    Edge(int to,int next,int cap,int cost):to(to),next(next),cap(cap),cost(cost){}
}edge[maxm];  

int first[maxn],tot;  
int pre[maxn],dis[maxn];  
bool vis[maxn];  
int N;        //节点总个数,节点编号从0~N-1  

void init(int n){  
    N=n;  
    tot=0;  
    memset(first,-1,sizeof(first));  
}  
void addedge(int u,int v,int cap,int cost){  
    edge[tot]=Edge(v,first[u],cap,cost);
	first[u]=tot++;  
    edge[tot]=Edge(u,first[v],0,-cost);
	first[v]=tot++;  
}  
bool spfa(int s,int t){  
    queue<int>q;  
    for(int 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(int i= first[u];i!=-1;i=edge[i].next){  
            int v=edge[i].to;  
            if(edge[i].cap&&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;  
        for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){  
            if(Min >edge[i].cap)Min=edge[i].cap;  
        }  
        for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){  
            edge[i].cap-=Min;  
            edge[i^1].cap+=Min;  
            cost+=edge[i].cost*Min;  
        }  
        flow+=Min;  
    }  
    return flow;  
} 
int a[maxn][2],b[maxn][2];
int tot1,tot2;
int main(){
	int n,m,i,j;
	while(scanf("%d%d",&n,&m)!=EOF){
		if(!n&&!m)break;
		tot=0;
		memset(first,-1,sizeof(first));
		tot1=tot2=0;
		char s[150];
		for(i=0;i<n;i++){
			scanf("%s",s);
			for(j=0;j<m;j++){
				if(s[j]=='m'){
					tot1++;
					a[tot1][0]=i;
					a[tot1][1]=j;
				}
				if(s[j]=='H'){
					tot2++;
					b[tot2][0]=i;
					b[tot2][1]=j;
				}
			}
		}
		N=tot1*2+2;
		for(i=1;i<=tot1;i++){
			for(j=1;j<=tot2;j++){
				addedge(i,j+tot1,1,abs(a[i][0]-b[j][0])+abs(a[i][1]-b[j][1]));
			}
		}
		for(i=1;i<=tot1;i++){
			addedge(0,i,1,0);
		}
		for(i=1;i<=tot2;i++){
			addedge(i+tot1,tot1+tot2+1,1,0);
		}
		int cost;
		minCostMaxflow(0,tot1+tot2+1,cost);
		printf("%d\n",cost);
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值