POJ 2195-Going Home(KM算法/最小费用最大流算法)

原创 2016年08月30日 21:06:02

Going Home
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 21730   Accepted: 10990

Description

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.

Input

There are one or more test cases in the input. Each case starts with a line giving two integers N and M, where N is the number of rows of the map, and M is the number of columns. The rest of the input will be N lines describing the map. You may assume both N and M are between 2 and 100, inclusive. There will be the same number of 'H's and 'm's on the map; and there will be at most 100 houses. Input will terminate with 0 0 for N and M.

Output

For each test case, output one line with the single integer, which is the minimum amount, in dollars, you need to pay.

Sample Input

2 2
.m
H.
5 5
HH..m
.....
.....
.....
mm..H
7 8
...H....
...H....
...H....
mmmHmmmm
...H....
...H....
...H....
0 0

Sample Output

2
10
28

Source


题目意思:

N行M列,每人可分得一个房子,每人每走一步花费为1,求每人各回各家的最小花费。

解题思路:

这题有两种思路可破:KM算法和最小费用最大流算法。

(一)

套Kuhn-Munkras算法模板,建二分图求解。

下面详细讲讲建图的过程

①扫描读入的图,分别标记出人M房屋H的位置坐标;

②每个人与每间房屋一一对应,比如测试用例

5 5
HH..m
.....
.....
.....
mm..H
M的坐标是A(1,5) B(5,1) C(5,2);H的坐标是X(1,1) Y(1,2) Z(5,5);

那么分别求出AX AY AZ BX BY BZ CX CY CZ路径上对应花费的权值就是二分图中对应边的边权。
因为是求最小权,所以建图时边的权值取相反数,最后所得的ans取相反数。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<malloc.h>
using namespace std;
typedef long long ll;
#define maxn 300
#define INF 0x3f3f3f3f
int nx,ny;//两边的点数
int g[maxn][maxn];//二分图描述
int linker[maxn],lx[maxn],ly[maxn];//y中各点匹配状态,x,y中的点标号
int slack[maxn];
bool visx[maxn],visy[maxn];
int ax[maxn],ay[maxn],bx[maxn],by[maxn];
char Map[maxn][maxn];
bool DFS(int x)
{
    visx[x] = true;
    for(int y = 1; y <= ny; y++)
    {
        if(visy[y])continue;
        int tmp = lx[x] + ly[y] - g[x][y];
        if(tmp == 0)
        {
            visy[y] = true;
            if(linker[y] == -1 || DFS(linker[y]))
            {
                linker[y] = x;
                return true;
            }
        }
        else if(slack[y] > tmp)
            slack[y] = tmp;
    }
    return false;
}
int KM()
{
    memset(linker,-1,sizeof(linker));
    memset(lx,0,sizeof(lx));
    memset(ly,0,sizeof(ly));
    for(int i = 0; i < nx; i++)
    {
        lx[i] = -INF;
        for(int j = 1; j <= ny; j++)
            if(g[i][j] > lx[i])
                lx[i] = g[i][j];
    }
    for(int x = 1; x <= nx; x++)
    {
        for(int i = 1; i <= ny; i++)
            slack[i] = INF;
        while(true)
        {
            memset(visx,false,sizeof(visx));
            memset(visy,false,sizeof(visy));
            if(DFS(x))break;
            int d = INF;
            for(int i = 1; i <= ny; i++)
                if(!visy[i] && d > slack[i])
                    d = slack[i];
            for(int i = 1; i <= nx; i++)
                if(visx[i])
                    lx[i] -= d;
            for(int i = 1; i <= ny; i++)
            {
                if(visy[i])ly[i] += d;
                else slack[i] -= d;
            }
        }
    }
    int res = 0;
    for(int i = 1; i <= nx; i++)
        if(linker[i] != -1)
            res += g[linker[i]][i];
    return -res;
}
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)&&n!=0&&m!=0)
    {
        /*for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                scanf("%d",&g[i][j]);
        nx = ny = n;*/
        memset(g,0,sizeof g);
        nx=ny=0;//二分图顶点的个数
        for(int i=1; i<=n; i++)
            scanf("%s",Map[i]+1);//读入原图
        for(int i=1; i<=n; i++)
            for(int j=1; j<=m; j++)
            {
                if(Map[i][j]=='m')
                {
                    nx++;
                    ax[nx]=i;
                    ay[nx]=j;
                }
                else if(Map[i][j]=='H')
                {
                    ny++;
                    bx[ny]=i;
                    by[ny]=j;
                }
            }
        for(int i=1; i<=nx; i++)
            for(int j=1; j<=ny; j++)
                g[i][j]=-(abs(ax[i]-bx[j])+abs(ay[i]-by[j]));//建图
        printf("%d\n",KM());
    }
    return 0;
}
/**
2 2
.m
H.
5 5
HH..m
.....
.....
.....
mm..H
7 8
...H....
...H....
...H....
mmmHmmmm
...H....
...H....
...H....
0 0
**/

(二)

套最小费用最大流算法模板,加超级源点和超级汇点网络流求解。

注意模板使用的时候,minCostMaxflow()的返回值。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#include<malloc.h>
using namespace std;
typedef long long ll;
#define maxn 300

const int MAXN = 10000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge
{
    int to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//节点总个数,节点编号从0~N-1
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].cap = cap;
    edge[tol].cost = cost;
    edge[tol].flow = 0;
    edge[tol].next = head[u];
    head[u] = tol++;
    edge[tol].to = u;
    edge[tol].cap = 0;
    edge[tol].cost = -cost;
    edge[tol].flow = 0;
    edge[tol].next = head[v];
    head[v] = tol++;
}
bool spfa(int s,int t)//找增广路
{
    queue<int>q;
    for(int i = 0; i <= t+2; 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 = 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 minCostMaxflow(int s,int t)//最小费用最大流
{
    int flow = 0;
    int ans=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 - edge[i].flow)
                Min = edge[i].cap - edge[i].flow;
        for(int 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;
        }
        ans+=dis[t];
        flow += Min;
    }
    return ans;
}

int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)&&n!=0&&m!=0)
    {
        int nx,ny,ax[maxn],ay[maxn],bx[maxn],by[maxn];
        char Map[maxn][maxn];
        nx=ny=0;//二分图顶点的个数
        for(int i=1; i<=n; i++)
            scanf("%s",Map[i]+1);//读入原图
        for(int i=1; i<=n; i++)
            for(int j=1; j<=m; j++)
            {
                if(Map[i][j]=='m')
                {
                    nx++;
                    ax[nx]=i;
                    ay[nx]=j;
                }
                else if(Map[i][j]=='H')
                {
                    ny++;
                    bx[ny]=i;
                    by[ny]=j;
                }
            }
        int s=0,t=nx+ny+1;//源点和汇点
        init(t+1);//初始化
        for(int i = 1; i <= nx; i++)
            addedge(s,i,1,0);//源点向各个点加边
        for(int i = nx+1; i <= nx+ny; i++)
            addedge(i,t,1,0);//汇点向各个点加边
        for(int i=1; i<=nx; i++)
            for(int j=1; j<=ny; j++)
            {
                int va=(abs(ax[i]-bx[j])+abs(ay[i]-by[j]));
                //cout<<i<<"->"<<nx+j<<"="<<va<<endl;
                addedge(i,nx+j,1,va);//建图
            }
        printf("%d\n",minCostMaxflow(s,t));
    }
    return 0;
}
/**
2 2
.m
H.
5 5
HH..m
.....
.....
.....
mm..H
7 8
...H....
...H....
...H....
mmmHmmmm
...H....
...H....
...H....
0 0
**/


版权声明:本文为博主原创文章,未经博主允许不得转载,转载请注明出处。

POJ-2195 Going Home (最小费用最大流初学 && 最大权二分匹配—KM算法)

Going Home 最小费用最大流 && 最大权二分匹配,两种解法 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions:...

poj2195Going Home(费用流或KM算法)

这道题目是比较简单的模板题,我用了两种方法写了一下,需要注意的是用KM算法写的时候,因为这个算法本身求得是二分图最大权匹配,而这道题求的是最小,那么应该在加边的时候把权值乘负一#include #i...

POJ 2195 Going Home 费用流模版题(附KM算法,转)

题意: 给出一个n*m的图,其中m是人,H是房子,每个人移动一步需要一块,问所有人移动到房子里的最少花费。 建图: 建立一个超级源点和超级汇点,S=0,T=2*num+1。 从源点到所有的人建立一条流...

HDU 1533Going Home(KM算法求二分图最小权匹配或者最小费用最大流)

On a grid map there are n little men and n houses. In each unit time, every little man can move one ...

poj 2195 Going Home(最小费用最大流)

http://poj.org/problem?id=2195 题意:一个n*m的矩阵,其中每个'm'代表一个人,每个‘H'代表一个房子,且人和房子的数目相同,要求每个人找到一个属于自己的房子,每个房...

poj 2195 Going Home(最小费用最大流)

Going Home Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 18966   Ac...

POJ 2195 Going Home (最小费用最大流)

POJ 2195 Going Home (最小费用最大流)

【最小费用最大流】POJ-2195 Going Home

Going Home Time Limit: 1000MS   Memory Limit: 65536K       Description ...

hdu 1533 || poj 2195 Going Home (最小费用最大流)

题目链接:   poj 2195 题目大意:   给出NxM的地图,'.'表示可以走的,'H'表示家,'m'表示人,H和m的数目相同                   求把所有人移动到H的最小步数 ...

POJ 2195 Going Home (最小费用最大流)

Description On a grid map there are n little men and n houses. In each unit time, every little man...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:POJ 2195-Going Home(KM算法/最小费用最大流算法)
举报原因:
原因补充:

(最多只允许输入30个字)