poj3020-二分图匹配-最小路径覆盖

题目链接http://poj.org/problem?id=3020

 *--代表城市,o--代表空地

       给城市安装无线网,一个无线网最多可以覆盖两座城市,问覆盖所有城市最少要用多少无线。

公式:,最小路径覆盖=总节点数-最大匹配数;

那么接下来需要确认的是,

究竟是求 有向二分图的最小路覆盖,还是求 无向二分图的最小路覆盖

因为有向和无向是截然不同的计算方法。

例如输入:

*oo

***

O*o

时,可以抽象为一个数字地图:

100

234

050

任意两个城市(顶点)之间的边是成对出现的

那么我们就可以确定下来,应该 构造无向二分图(其实无向=双向)

无向二分图的最小路径覆盖 = 顶点数 – 最大二分匹配数/2

接下来就是套模板了

#include<cstdio>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#define ll long long
using namespace std;
const int maxn=405;
const int maxm=405*405*2;
char mp[450][450];
int p[maxn][maxn];

int next[4][2]={1,0,0,1,0,-1,-1,0};
struct Edge
{
    int to,next;
}edge[maxm];
int head[maxn],tot;
void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
    edge[tot].to=v;
    edge[tot].next=head[u];
    head[u]=tot++;
}
int linker[maxn];
bool used[maxn];
int un;
bool dfs(int u)
{
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].to;
        if(!used[v])
        {
            used[v]=true;
            if(linker[v]==-1||dfs(linker[v]))
            {
                linker[v]=u;
                return true;
            }
        }
    }
    return false;
}
int hungary()
{
    int res=0;
    memset(linker,-1,sizeof(linker));
    for(int u=1;u<=un;u++)
    {
        memset(used,false,sizeof(used));
        if(dfs(u))res++;//cout<<res<<endl;
    }

    return res;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        init();
        memset(p,0,sizeof(p));
        int n,m;
        char c;
        int cnt=0;
        scanf("%d%d",&n,&m);
        getchar();
        for(int i=0;i<n;i++)
        {
            gets(mp[i]);
        }
        for(int i=0;i<n;i++)
        {


		  for(int j=0;j<m;j++)
		  {
		  	if(mp[i][j]=='*')
		  	   {
		  	   	p[i][j]=++cnt;
		  	   }
		  }
		  }

        un=cnt;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(p[i][j]){
                    for(int k=0;k<4;k++)
                {
                    int xx=i+next[k][0];
                    int yy=j+next[k][1];
                    if(xx<0||xx>=n||yy<0||yy>=m)
                        continue;
                    if(p[xx][yy])
                        {
                            addedge(p[i][j],p[xx][yy]);
                            //cout<<p[i][j]<<" "<<p[xx][yy]<<endl;
                        }
                }
                }
            }
        }
        printf("%d\n",cnt-hungary()/2);
    }
}









 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谷丘-CODER

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值