【网络流】【费用流】[HDU 1533]Going Home

题目描述

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.

输入

2 2

.m

H.

题目解析:实际上不就是模板题目么,直接算距离作为费用, 然后流量为1建立边

#include 
#include 
#include 
#include 
#include 
using namespace std;
const int MAXN = 300;
const int INF = 1e9+7;
const int MAXM = 30070;
struct node{
    int v, cost, cap;
    node *next, *back;
}Edges[MAXM*2+10], *ecnt=Edges, *adj[MAXN+10];
int dis[MAXN+10], res[MAXN+10];
node *Fa[MAXN+10];
void addedge(int u, int v, int ca, int co){
    ++ecnt;
    ecnt->v = v;
    ecnt->cap = ca;
    ecnt->cost = co;
    ecnt->next = adj[u];
    ecnt->back = ecnt+1;
    adj[u] = ecnt;

    ++ecnt;
    ecnt->v = u;
    ecnt->cap = 0;
    ecnt->cost = -co;
    ecnt->next = adj[v];
    ecnt->back = ecnt-1;
    adj[v] = ecnt;
}
int ncnt, s, t;
bool SPFA(){
    for(int i=1;i<=ncnt;i++)
        dis[i]=INF;
    dis[s] = 0;
    queue que;
    que.push(s);
    res[s] = INF;
    while(!que.empty()){
        int u = que.front();
        que.pop();
        for(node *p=adj[u];p;p=p->next){
            if(p->cap == 0) continue;
            if(dis[p->v] <= dis[u] + p->cost) continue;
            dis[p->v] = dis[u] + p->cost;
            Fa[p->v] = p;
            res[p->v] = min(res[u], p->cap);
            que.push(p->v);
        }
    }
    return !(dis[t] == INF);
}
int work(){
    int ret = 0;
    while(SPFA()){
        ret += res[t] * dis[t];
        int now = t;
        while(now != s){
            Fa[now]->cap -= res[t];
            Fa[now]->back->cap += res[t];
            now = Fa[now]->back->v;
        }
    }
    return ret;
}
int H[110][2], hcnt;
int M[110][2], mcnt;
int mabs(int u){return u>0?u:-u;}
int calc(int a, int b){
    return mabs(M[a][0]-H[b][0])+mabs(M[a][1]-H[b][1]);
}
int main(){
    int n, m;
    char str[200];
    while(~scanf("%d%d", &n, &m)&&n&&m){
        hcnt = mcnt=0;
        for(int i=1;i<=n;i++){
            scanf("%s", str);
            for(int j=0;j


你可能感兴趣的:(图论——网络流,图论——费用流)