poj2195(二分图最大匹配,最小费用流)

本文探讨了如何利用KM算法和最小费用流解决一个网格地图上的人与房子之间的最优匹配问题,目标是让人以最短的总路径进入各自的房子。

Going Home
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 21120 Accepted: 10668

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

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

思路1:在哈工大出版的图论及应用上有这个原题,是出在二分图的区域,那本书上的模板有bug,我的博客有改过之后的正确模板:

KM算法模板

这题就是个匹配的问题,有多少人回家,让回家的路总和最短,这就让匹配有了权值,所以得用KM算法,不过KM算法是最优匹配,匹配得出来的是最大值,然而我们要求出来最小值,所以我们用一个最大值减去每条边的值,使大小顺序倒过来,然后跑完KM算法之后用最大值*n-匹配值就是得出的结果了。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;

const int inf=1e9,maxn=110;
int tu[maxn][maxn],match1[maxn],match2[maxn];
int KM(int m,int n)
{
    int s[maxn],t[maxn],l1[maxn],l2[maxn],p,q,ret=0,i,j,k;
    ///l1为左边的匹配分量,l2是右边的匹配分量
    for(i=0; i<m; i++)
    {
        for(l1[i]=-inf,j=0; j<n; j++)
            l1[i]=tu[i][j]>l1[i]?tu[i][j]:l1[i];
        if(l1[i]==-inf)
            return -1;
    }
    for(i=0; i<n; l2[i++]=0);
    memset(match1,-1,sizeof(int)*n);
    memset(match2,-1,sizeof(int)*n);
    for(i=0; i<m; i++)
    {
        memset(t,-1,sizeof(int)*n);
        for(s[p=q=0]=i; p<=q&&match1[i]<0; p++)
        {
            for(k=s[p],j=0; j<n&&match1[i]<0; j++)
                if(l1[k]+l2[j]==tu[k][j]&&t[j]<0)
                {
                    s[++q]=match2[j],t[j]=k;
                    if(s[q]<0)
                        for(p=j; p>=0; j=p)
                            match2[j]=k=t[j],p=match1[k],match1[k]=j;
                }
        }
        if(match1[i]<0)
        {
            for(i--,p=inf,k=0; k<=q; k++)
                for(j=0; j<n; j++)
                    if(t[j]<0&&l1[s[k]]+l2[j]-tu[s[k]][j]<p)
                        p=l1[s[k]]+l2[j]-tu[s[k]][j];
            for(j=0; j<n; l2[j]+=t[j]<0?0:p,j++);
            for(k=0; k<=q; l1[s[k++]]-=p);
        }
    }
    for(i=0; i<m; i++)
        ret+=tu[i][match1[i]];
    return ret;
}

char x[110][110];
struct hh
{
    int x,y;
    hh(int xx,int yy)
    {
        x=xx,y=yy;
    }
};
vector<hh>hou;
vector<hh>man;

int real(int x)
{
    if(x<0)
        return -x;
    return x;
}

int main()
{
    int m,n;
    while(~scanf("%d%d",&n,&m)&&m+n)
    {
        hou.clear();
        man.clear();
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
            {
                scanf(" %c",&x[i][j]);
                if(x[i][j]=='H')
                {
                    hh t(i,j);
                    hou.push_back(t);
                }
                else if(x[i][j]=='m')
                {
                    hh t(i,j);
                    man.push_back(t);
                }
            }
        int l=hou.size();
        for(int i=0; i<l; i++)
            for(int j=0; j<l; j++)
                tu[i][j]=100000-(real(hou[i].x-man[j].x)+real(hou[i].y-man[j].y));
        printf("%d\n",100000*l-KM(l,l));
    }
    return 0;
}

思路2:这题由于是要求总的最短路径,那么我们可以想到用最小费用流来解决这个问题。

我的博客有最小费用流的模板:最小费用流模板


#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const   int oo=1e9;
const   int mm=11111111;
const   int mn=888888;
int node,src,dest,edge;
int ver[mm],flow[mm],cost[mm],nex[mm];
int head[mn],dis[mn],p[mn],q[mn],vis[mn];
/**这些变量基本与最大流相同,增加了cost 表示边的费用,p记录可行流上节点对应的反向边*/
void prepare(int _node,int _src,int _dest)
{
    node=_node,src=_src,dest=_dest;
    for(int i=0; i<node; i++)head[i]=-1,vis[i]=0;
    edge=0;
}
void addedge(int u,int v,int f,int c)
{
    ver[edge]=v,flow[edge]=f,cost[edge]=c,nex[edge]=head[u],head[u]=edge++;
    ver[edge]=u,flow[edge]=0,cost[edge]=-c,nex[edge]=head[v],head[v]=edge++;
}
bool spfa()/**spfa 求最短路,并用 p 记录最短路上的边*/
{
    int i,u,v,l,r=0,tmp;
    for(i=0; i<node; ++i)dis[i]=oo;
    dis[q[r++]=src]=0;
    p[src]=p[dest]=-1;
    for(l=0; l!=r; (++l>=mn)?l=0:l)
        for(i=head[u=q[l]],vis[u]=0; i>=0; i=nex[i])
            if(flow[i]&&dis[v=ver[i]]>(tmp=dis[u]+cost[i]))
            {
                dis[v]=tmp;
                p[v]=i^1;
                if(vis[v]) continue;
                vis[q[r++]=v]=1;
                if(r>=mn)r=0;
            }
    return p[dest]>-1;
}
int SpfaFlow()/**源点到汇点的一条最短路即可行流,不断的找这样的可行流*/
{
    int i,ret=0,delta;
    while(spfa())
    {
        for(i=p[dest],delta=oo; i>=0; i=p[ver[i]])
            if(flow[i^1]<delta)delta=flow[i^1];
        for(i=p[dest]; i>=0; i=p[ver[i]])
            flow[i]+=delta,flow[i^1]-=delta;
        ret+=delta*dis[dest];
    }
    return ret;
}

struct hh
{
    int x,y;
    hh(int xx,int yy)
    {
        x=xx,y=yy;
    }
};
vector<hh>hou;
vector<hh>man;

int real(int x)
{
    if(x<0)
        return -x;
    return x;
}
char x[110][110];
int main()
{
    int m,n;
    while(~scanf("%d%d",&n,&m)&&n+m)
    {
        hou.clear();
        man.clear();
        for(int i=0; i<n; i++)
            for(int j=0; j<m; j++)
            {
                scanf(" %c",&x[i][j]);
                if(x[i][j]=='H')
                {
                    hh t(i,j);
                    hou.push_back(t);
                }
                else if(x[i][j]=='m')
                {
                    hh t(i,j);
                    man.push_back(t);
                }
            }
        int l=hou.size();
        prepare(2*l+2,2*l,2*l+1);
        for(int i=0; i<l; i++)
            for(int j=0; j<l; j++)
                addedge(i,j+l,1,real(hou[i].x-man[j].x)+real(hou[i].y-man[j].y));
        for(int i=0; i<l; i++)
            addedge(2*l,i,1,0),addedge(i+l,2*l+1,1,0);
        printf("%d\n",SpfaFlow());
    }
    return 0;
}


### 关于二分图最小顶点覆盖的算法实现 #### 1. 最小顶点覆盖的概念 最小顶点覆盖是指在一个二分图中选取尽可能少的节点,使得这些节点能够覆盖所有的边。换句话说,对于每一条边 (u, v),至少有一个端点 u 或 v 被选入覆盖集中。 根据 König 定理,在任意无向二分图中,最小顶点覆盖的数量等于该最大匹配数量[^1]。 --- #### 2. 算法原理 为了求解二分图的最小顶点覆盖,通常采用 **匈牙利算法** 来计算最大匹配数。具体过程如下: - 构建一个二分图 G(X,Y,E),其中 X 和 Y 是两个互不相交的节点集合,E 表示连接它们的边。 - 使用匈牙利算法找到二分图最大匹配 M。 - 基于最大匹配的结果,通过以下方式构造最小顶点覆盖: - 将左侧未被匹配的节点加入到覆盖集中; - 对右侧已被匹配的节点也加入到覆盖集中。 最终得到的覆盖集大小即为最小顶点覆盖的数量[^2]。 --- #### 3. 实现代码 以下是基于 Python 的实现代码,利用匈牙利算法完成二分图最小顶点覆盖的计算: ```python from collections import defaultdict def hungarian_algorithm(graph, n, m): """ 匈牙利算法用于寻找二分图最大匹配 :param graph: 邻接表表示的二分图 {X -> [Y]} :param n: 左侧节点数目 :param m: 右侧节点数目 :return: 最大匹配结果 """ match_y = [-1] * m # 记录右侧节点对应的匹配关系 visited = None # 当前轮次访问标记 def dfs(u): for v in graph[u]: if not visited[v]: visited[v] = True if match_y[v] == -1 or dfs(match_y[v]): match_y[v] = u return True return False matching_count = 0 for i in range(n): visited = [False] * m if dfs(i): matching_count += 1 return matching_count, match_y def min_vertex_cover(graph, n, m): """ 求解二分图的最小顶点覆盖 :param graph: 邻接表表示的二分图 {X -> [Y]} :param n: 左侧节点数目 :param m: 右侧节点数目 :return: 最小顶点覆盖集合 """ max_matching, match_y = hungarian_algorithm(graph, n, m) cover_x = set() # 左侧需要覆盖的节点 cover_y = set() # 右侧需要覆盖的节点 unmatched_in_x = set(range(n)) # 初始认为所有左侧节点都未匹配 matched_in_y = set() for y in range(m): # 找出右侧已匹配的节点 if match_y[y] != -1: unmatched_in_x.discard(match_y[y]) # 如果某个左侧节点参与了匹配,则移除 matched_in_y.add(y) cover_x.update(unmatched_in_x) # 添加左侧未匹配的节点 cover_y.update(set(range(m)) - matched_in_y) # 添加右侧未匹配的节点 return list(cover_x), list(cover_y) # 测试用例 if __name__ == "__main__": # 输入邻接表形式的二分图 graph = { 0: [0, 1], 1: [0, 2], 2: [1, 3] } n = 3 # 左侧节点数 m = 4 # 右侧节点数 result_x, result_y = min_vertex_cover(graph, n, m) print(f"左侧需覆盖的节点: {result_x}") print(f"右侧需覆盖的节点: {result_y}") ``` 上述代码实现了二分图的最小顶点覆盖功能,核心部分依赖匈牙利算法来获取最大匹配,并据此推导出覆盖所需的节点集合[^3]。 --- #### 4. 应用实例 考虑 POJ 3041 Asteroids 这道题目,其本质是一个二分图最小顶点覆盖问题。给定一组障碍物坐标,将其转化为二分图模型后,可以通过以上方法高效解决。最终输出的是满足条件的最小射击次数[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值