POJ 3041 Asteroids
题意:用最少的射击来消灭图中的小行星。
关键是建图转化,建一个 横坐标到纵坐标的二分图,有障碍的点的位置上的值赋值为1,然后根据题意求的是二分图的最小点覆盖数,根据一个定理,知道最小点覆盖数=最大匹配数
AC
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
const int maxn=1010;
int vis[maxn],match[maxn],g[maxn][maxn];
int n;
bool dfs(int k)
{
for(int j=1;j<=n;j++)
{
if(g[k][j] && !vis[j])
{
vis[j]=1;
if(match[j]==-1 || dfs(match[j]))
{
match[j]=k;
return true;
}
}
}
return false;
}
int Hungary()
{
int all=0;
memset(match,0xff,sizeof(match));
for(int i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
if( dfs(i) )
all++;
}
return all;
}
int main()
{
int k;
scanf("%d%d",&n,&k);
memset(g,0,sizeof(g));
for(int i=1;i<=k;i++)
{
int u,v;
scanf("%d%d",&u,&v);
g[u][v]=1;
}
int ans=Hungary();
printf("%d\n",ans);
return 0;
}
错误代码
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
const int maxn=1000;
int vis[maxn],match[maxn],g[maxn][maxn];
int n,k;
bool dfs(int p)
{
for(int j=1;j<=n;j++)
{
if(g[p][j] && !vis[j])
{
vis[j]=1;
if(match[j]==-1 || dfs(match[j]))
{
match[j]=p;
return true;
}
}
}
return false;
}
int Hungary()
{
int all;
memset(match,0xff,sizeof(match));
for(int i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
if( dfs(i) )
all++;
}
return all;
}
int main()
{
scanf("%d%d",&n,&k);
memset(g,0,sizeof(g));
for(int i=1;i<=k;i++)
{
int u,v;
scanf("%d%d",&u,&v);
g[u][v]=1;
}
int ans=Hungary();
printf("%d\n",ans);
return 0;
}