poj 2195 Going Home (费用流)

水题,直接搞。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
#define B(x) (1<<(x))
using namespace std;
void cmax(int& a,int b){ if(b>a)a=b; }
void cmin(int& a,int b){ if(b<a)a=b; }
typedef long long ll;
const int oo=0x3f3f3f3f;
const ll OO=1LL<<61;
const int MOD=1000007;
const int maxn=302020;
const int maxm=1602020;
struct EDGE{
    int v,next,c,f,cost;
}E[maxm<<1];
int head[maxn],tol;
int dis[maxn],pre[maxn];
int vis[maxn];

void Init(){
    memset(head,-1,sizeof head);
    tol=0;
}

void add_edge(int u,int v,int f,int cost){
    E[tol].v=v;
    E[tol].c=f;
    E[tol].f=0;
    E[tol].cost=cost;
    E[tol].next=head[u];
    head[u]=tol++;

    E[tol].v=u;
    E[tol].c=0;
    E[tol].f=0;
    E[tol].cost=-cost;
    E[tol].next=head[v];
    head[v]=tol++;
}

bool Spfa(int s,int t){

    for(int i=0;i<=t;i++){
        pre[i]=-1;
        dis[i]=oo;
        vis[i]=0;
    }
    dis[s]=0;
    vis[s]=1;
    queue<int>q;
    q.push(s);
    while(!q.empty()){
        int u=q.front();q.pop();
        vis[u]=0;
        for(int i=head[u];i!=-1;i=E[i].next){
            int v=E[i].v;
            if(E[i].c>E[i].f&&dis[v]>dis[u]+E[i].cost){
                dis[v]=dis[u]+E[i].cost;
                pre[v]=i;
                if(!vis[v]){
                    vis[v]=1;
                    q.push(v);
                }
            }
        }
    }
    return dis[t]!=oo;
}

int min_cost_maxflow(int s,int t,int& cost){
    int flow=0;
    cost=0;
    while(Spfa(s,t)){
        int Min=oo;
        for(int i=pre[t];i!=-1;i=pre[E[i^1].v]){
            if(Min>E[i].c-E[i].f)
                Min=E[i].c-E[i].f;
        }
        for(int i=pre[t];i!=-1;i=pre[E[i^1].v]){
            E[i].f+=Min;
            E[i^1].f-=Min;
            cost+=Min*E[i].cost;
        }
        flow+=Min;
    }
    return flow;
}

char maze[205][205];
struct Node{
    int x,y;
    Node(){}
    Node(int x_,int y_){ x=x_; y=y_; }
}a[maxn],b[maxn];

int Dis(Node n1,Node n2){
    return abs(n1.x-n2.x)+abs(n1.y-n2.y);
}

int main(){
    //freopen("G:\\read.txt","r",stdin);
    int n,m,s,t;
    while(scanf("%d%d",&n,&m)!=EOF){
        if(n==0&&m==0)break;
        for(int i=0;i<n;i++)scanf("%s",maze[i]);
        int n1=0,n2=0;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(maze[i][j]=='H')b[n2++]=Node(i,j);
                if(maze[i][j]=='m')a[n1++]=Node(i,j);
            }
        }
        Init();
        s=n1+n2+1;
        t=s+1;
        for(int i=0;i<n1;i++){
            for(int j=0;j<n2;j++){
               add_edge(i,j+n1,1,Dis(a[i],b[j]));
            }
        }
        for(int i=0;i<n1;i++)add_edge(s,i,1,0);
        for(int i=0;i<n2;i++)add_edge(i+n1,t,1,0);
        int cost;
        min_cost_maxflow(s,t,cost);
        printf("%d\n",cost);
    }
    return 0;
}
/*

*/


你可能感兴趣的:(poj 2195 Going Home (费用流))