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

来源:互联网 发布:rpc调用 vscode 插件 编辑:程序博客网 时间:2024/06/05 10:52

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 01 0 10 1 00
 

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;}