Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 <= N <= 500). The grid contains K asteroids (1 <= K <= 10,000), which are conveniently located at the lattice points of the grid.
Fortunately, Bessie has a powerful weapon that can vaporize all the asteroids in any given row or column of the grid with a single shot.This weapon is quite expensive, so she wishes to use it sparingly.Given the location of all the asteroids in the field, find the minimum number of shots Bessie needs to fire to eliminate all of the asteroids.
题意:说的是Bessie在玩一个游戏,在一个N*N的方格里面有K个敌人,Bessie可以用炸药包炸死一行或者一列的敌人,求用最少的炸药包炸掉所有人。
题解:刚开始看不知道用什么,后面发现这个跟之前做过的NY的月老的题目很像,说的是男女配对问题,i和j表示男i和女j愿意在一起的几率大,求最大的匹配数。此题是最小的点覆盖数。二分图最小点覆盖=最大匹配。匈牙利算法可解。
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<queue>
using namespace std;
int vit[10005];
int f[10005];
int ans,n,k,tot;
int head[10005];
struct node
{
int u;
int next;
};
node b[10005];
void add(int u,int v)
{
b[tot].u=v;
b[tot].next=head[u];
head[u]=tot++;
}
int dfs(int x)
{
for(int y=head[x];y;y=b[y].next)
{
int k=b[y].u;
if(!vit[k])
{
vit[k]=1;
if(f[k]==0||dfs(f[k]))
{
f[k]=x;
return 1;
}
}
}
return 0;
}
void Search()
{
for(int i=1;i<=n;i++)
{
memset(vit,0,sizeof(vit));
if(dfs(i))
ans++;
}
}
int main()
{
while(~scanf("%d%d",&n,&k))
{
memset(f,0,sizeof(f));
memset(head,0,sizeof(head));
tot=1;
for(int i=1;i<=k;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
}
ans=0;
Search();
printf("%d\n",ans);
}
return 0;
}