大意:给你一个0/1矩阵,以及一把枪,一枪可以打掉同一行或者同一列上的1,问你最少几次可以把1全部变为0?
思路:我们以x,y轴为顶点建立二分图,如果数字为1的话,那么就连一条边,其实就转换成了最小顶点覆盖的问题,然后用ED算法求二分最大匹配即可.
注意:
1、最大的匹配顶点数应该为n,所以for(int i = 1; i <= n; i++) ED(i);
2、矩阵数据范围是1~100,所以最大的边数应该是100*100才对,否则RE.
CODE:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define MAXN 110
#define MAXM 110*110
struct Edge
{
int v, next;
}edge[MAXM];
int n, m;
int cnt;
int tot;
int first[MAXN], link[MAXN];
bool vis[MAXN];
void init()
{
cnt = 0;
tot = 0;
memset(first, -1, sizeof(first));
memset(link, -1, sizeof(link));
}
void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u]; first[u] = cnt++;
}
int ED(int u)
{
for(int e = first[u]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
if(!vis[v])
{
vis[v] = true;
if(link[v] == -1 || ED(link[v]))
{
link[v] = u;
return true;
}
}
}
return false;
}
void solve()
{
int ans = 0;
for(int i = 1; i <= n; i++)
{
memset(vis, false, sizeof(vis));
if(ED(i)) ans++;
}
printf("%d\n", ans);
}
int main()
{
while(scanf("%d", &n) && n)
{
init();
scanf("%d", &m);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
int map;
scanf("%d", &map);
if(map)
{
read_graph(i, j);
}
}
}
solve();
}
return 0;
}
#include<cstring>
#include<cstdio>
using namespace std;
#define MAXN 110
#define MAXM 110*110
struct Edge
{
int v, next;
}edge[MAXM];
int n, m;
int cnt;
int tot;
int first[MAXN], link[MAXN];
bool vis[MAXN];
void init()
{
cnt = 0;
tot = 0;
memset(first, -1, sizeof(first));
memset(link, -1, sizeof(link));
}
void read_graph(int u, int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u]; first[u] = cnt++;
}
int ED(int u)
{
for(int e = first[u]; e != -1; e = edge[e].next)
{
int v = edge[e].v;
if(!vis[v])
{
vis[v] = true;
if(link[v] == -1 || ED(link[v]))
{
link[v] = u;
return true;
}
}
}
return false;
}
void solve()
{
int ans = 0;
for(int i = 1; i <= n; i++)
{
memset(vis, false, sizeof(vis));
if(ED(i)) ans++;
}
printf("%d\n", ans);
}
int main()
{
while(scanf("%d", &n) && n)
{
init();
scanf("%d", &m);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
int map;
scanf("%d", &map);
if(map)
{
read_graph(i, j);
}
}
}
solve();
}
return 0;
}