您的位置:首页 > 其它

杭电2119-Matrix (呵呵,做完这道题感觉自己还可以哈)

2013-08-14 16:05 246 查看

Matrix

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 1376    Accepted Submission(s): 599


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
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.

 

[align=left]Sample Input[/align]

3 3
0 0 0
1 0 1
0 1 0
0

 

[align=left]Sample Output[/align]

2这题大概意思就是给你一个n*m只由0和1组成的矩阵,你可以划掉任意一行或者一列的数字1,问你把矩阵内的1全部划掉最少需要几步?这个题明显的思路是:二分最大匹配,即用匈牙利算法求最大匹配,怎样匹配呢?就是把矩阵的行看做boy,把矩阵的列看做girl,如果矩阵中有数字1,表明这个行(boy)和这个列(girl)想在一起,所以转化一下就是成了HDU上“过山车”这道题了
AC代码+解释:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<iomanip>
#include<queue>
#include<stack>
#include<set>
#include<cmath>
#include<map>
#include<algorithm>
const int MAX=101;
int Map[MAX][MAX];
int girl[MAX];//女生
int boy[MAX];//男生
int mark[MAX];//匹配好了就标记
int pipei[MAX];//谁跟谁匹配,例如pipei[1]=2表示男生1号匹配的是2号女生
int g;//表示女生的个数
int b;//表示男生个数
using namespace std;
bool find(int x)//寻找男生
{
int i;
for(i=0;i<b;i++)
{
if(Map[boy[i]][x]==1&&!mark[boy[i]])
{
mark[boy[i]]=1;
if(pipei[boy[i]]==-1||find(pipei[boy[i]]))//如果该男生没有被匹配或者已经匹配了但是跟这个男生匹配的女生还有别的男生可以匹配那么就把这个男生让出来
{
pipei[boy[i]]=x;//匹配
return true;
}
}
}
return false;
}
int main()
{
int n,m,sum,i,j;
while(cin>>n,n)
{
cin>>m;
memset(Map,0,sizeof(Map));//初始化
memset(pipei,-1,sizeof(pipei));//同上
map<int,int>B;//这里开map容器是记录所有男生以免重复记录
map<int,int>G;//同上
g=0;
b=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
cin>>Map[i][j];
if(Map[i][j]==1)
{
if(B[i]==0)//如果这个男生没有被记录
{
B[i]++;//就加进来并且标记已加入
boy[b++]=i;
}
if(G[j]==0)//同上
{
G[j]++;
girl[g++]=j;
}
}
}
}
sum=0;
for(i=0;i<g;i++)//女生开始匹配男生
{
memset(mark,0,sizeof(mark));
if(find(girl[i]))//如果可以匹配就+1
sum+=1;
}
cout<<sum<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  杭电2119-Matrix
相关文章推荐