您的位置:首页 > 其它

HDU 2119 Matrix(二分图最小顶点覆盖)

2017-09-04 10:28 447 查看
Matrix
Time Limit: 5000/1000 MS (Java/Others)    
Memory Limit: 32768/32768 K (Java/Others)

Problem Description

Give you a matrix(only contains 0 or 1),every time you can select a row or a column and delete all the '1' in this row or this column .

Your task is to give out the minimum times of deleting all the '1' in the matrix.

 

Input

There are several test cases.

The first line contains two integers n,m(1<=n,m<=100), n is the number of rows of the given matrix and m is the number of columns of the given matrix.

The next n lines describe the matrix:each line contains m integer, which may be either ‘1’ or ‘0’.

n=0 indicate the end of input.

Output

For each of the test cases, in the order given in the input, print one line containing the minimum times of deleting all the '1' in the matrix.

Sample Input

3 3 

0 0 0

1 0 1

0 1 0

0

 

Sample Output

2

 

题目意思是说:给你一个N*M的矩阵,矩阵中只有数字0和1,每次可以选择一行或者一列,消灭数字1,问最小要操作多少次可以把所有的消灭掉。

这个问题可以抽象为二分图最小边覆盖问题。

首先我们可以建一张二分图,点集X是行,点集Y为列,如果该行改列有数字1,

就连接这两个点。

这样我们就得到了一个二分图。

因为我们选择的是一行或者一列消灭数字1,也就是在N*M个点中选择一个点。

选中这个点以后,与之相连的边都消失。
现在我们要选最少的点,让所有的边都消失,那么这个就符合最小顶点覆盖的定义。

继而题目转换为求最小顶点覆盖,而最小顶点覆盖=最大匹配书,继而我们只需要求得最大匹配数即可

相似的题目还有POJ3401,点我传送 (๑ •̀ㅂ•́) ✧

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<functional>
#define maxn 1005
using namespace std;

int e[maxn][maxn];
int cy[maxn],vis[maxn];
int n,m,ans;

int path(int u)
{
for(int v=1;v<=m;v++)
{
if(e[u][v]&&!vis[v])
{
vis[v]=1;
if(cy[v]==0||path(cy[v]))
{
cy[v]=u;
return 1;
}
}
}
return 0;
}
int MaxMatch()
{
int sum=0;
memset(cy,0,sizeof(cy));
for(int i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
sum+=path(i);
}
return sum;
}

int main()
{
int i,j,a;
while(scanf("%d",&n),n)
{
memset(e,0,sizeof(e));
scanf("%d",&m);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
scanf("%d",&a);
if(a==1)
e[i][j]=1;
}
ans=MaxMatch();
printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图论 二分图