hdu2119(二分图+最小点覆盖+匈牙利算法)

Matrix

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1312    Accepted Submission(s): 574


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
 
本题的意思是给你一个矩阵,一次操作只能将一行或一列的1全变为0,问最少需要几次能够将矩阵中的1全变为0
若将1的行号作为二分图的一部分顶点,1的列号作为二分图的另一部分顶点,然后连一条边,就构成一个二分图,题目即求二分图的最小点覆盖,有理论:
一个二分图中的最大匹配数等于这个图中的最小点覆盖数,及转化为求二分图的最大匹配数,运用匈牙利算法可以快速求得
 
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;

const int MAX=110;
int M[MAX][MAX];

//二分图匹配(匈牙利算法的DFS实现)
//初始化:g[][]两边顶点的划分情况
//建立g[i][j]表示i->j的有向边就可以了,是左边向右边的匹配
//g没有边相连则初始化为0
//uN是匹配左边的顶点数,vN是匹配右边的顶点数
//调用:res=hungary();输出最大匹配数
//优点:适用于稠密图,DFS找增广路,实现简洁易于理解
//时间复杂度:O(VE)
//****************************************************************
//顶点编号从0开始的
const int MAXN=510;
int uN,vN;//u,v数目
int g[MAXN][MAXN];
int linker[MAXN];
bool visited[MAXN];
bool dfs(int u)//从左边开始找增广路径
{
    int v;
    for(v=0;v<vN;v++)//这个顶点编号从0开始,若要从1开始需要修改
      if(g[u][v]&&!visited[v])
      {
          visited[v]=true;
          if(linker[v]==-1||dfs(linker[v]))
          {//找增广路,反向
              linker[v]=u;
              return true;
          }
      }
    return false;//这个不要忘了,经常忘记这句
}
int hungary()
{
    int res=0;
    int u;
    memset(linker,-1,sizeof(linker));
    for(u=0;u<uN;u++)
    {
        memset(visited,0,sizeof(visited));
        if(dfs(u)) res++;
    }
    return res;
}
//****************************************************

int main()
{
	int i,j;
	while(~scanf("%d",&uN),uN)
	{
		scanf("%d",&vN);
		memset(g,0,sizeof(g));
		for(i=0;i<uN;i++)
		{
			for(j=0;j<vN;j++)
			{
			    scanf("%d",&M[i][j]);
				if(M[i][j])
					g[i][j]=1;
			}
		}

		printf("%d\n",hungary());
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值