您的位置:首页 > 其它

UVALive 6811 Irrigation Lines (二分图最小点覆盖--匈牙利算法)

2016-08-24 20:07 239 查看
大体题意:

给你一个n*m 的矩形,里面有的是1,有的是0,求最少的竖线或者横线  使得覆盖所有的1!

思路:

二分图的最小点覆盖! 比赛没有搞出来,乱写的,还写了许多贪心!!!

那个样例来说吧!

0 1 0

1 0 1

0 1 0

他最少两条直线就够了!

我们给他标号!

     c1 c2 c3

r1  0   1   0

r2  1   0   1

r3  0   1   0

他所有的边就是r1 - c2    r2--c1  r2 - c3  r3 - c2!

我们要找出最少的点来使得这些点被所有直线所连接!

很明显最少的点事  c2 和 r2  因此答案是2!

有一个定理,二分图的最小点覆盖等于 二分图的最大匹配数!

最大匹配数用匈牙利算法就好了!

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#define ps push_back
using namespace std;
const int maxn = 100 + 10;
char s[maxn][maxn];
vector<int>g[maxn];
int from[maxn*maxn];
bool use[maxn*maxn];
int n,m;
bool dfs(int x){
int len = g[x].size();
for (int i = 0; i < len; ++i){
int k = g[x][i];
if (use[k])continue;
use[k] = 1;
if (from[k] == -1 || dfs(from[k])){
from[k] = x;
return 1;
}
}
return 0;
}
int solve(){
int ans = 0 ;
memset(from,255,sizeof from);
for (int i = 1; i <= n; ++i){
memset(use,0,sizeof use);
if (dfs(i))++ans;
}
return ans;
}
int main(){
int T,kase = 0;
scanf("%d",&T);
while(T--){
scanf("%d %d",&n,&m);
for (int i = 1; i <= n; ++i)g[i].clear();
for (int i = 1; i <= n; ++i){
scanf("%s",s[i]+1);
}
for (int i = 1; i <= n; ++i){
for (int j = 1; j <= m; ++j){
if (s[i][j] == '1'){
g[i].ps(maxn+j);
}
}
}
printf("Case #%d: %d\n",++kase,solve());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐