有几个重要的关于图的结论:
1. 若图中没有孤立点,最大匹配+最小边覆盖=V(V是顶点个数)
2. 最大独立集+最小点覆盖=V
3. 二分图中,最大匹配=最小点覆盖
这道题可以这样建图:左边是行的点右边是列的点,设第i个行星坐标是(xi,yi),就把左边的xi和右边的yi连一条边
这样就要求这个图的最小顶点覆盖(因为最小顶点覆盖保证每条边的两个端点都至少有一个被选中,也就是每个行星都至少在行或列被击中)
二分图中,最小顶点覆盖=最大匹配
于是跑一个最大流就可以了
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <utility>
#include <map>
#include <stack>
#include <set>
#include <vector>
#include <queue>
#include <deque>
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define LL long long
#define Pair pair<int,int>
#define LOWBIT(x) x & (-x)
using namespace std;
const int MOD=2e9;
const int INF=0x7ffffff;
const int magic=348;
int n,k,t;
Pair a[10048];
int head[5048],to[10048],f[10048],nxt[10048],tot=1;
inline void addedge(int s,int t,int l)
{
to[++tot]=t;nxt[tot]=head[s];head[s]=tot;f[tot]=l;
to[++tot]=s;nxt[tot]=head[t];head[t]=tot;f[tot]=0;
}
int depth[5048];
queue<int> q;
bool bfs()
{
int i,x,y;
for (i=0;i<=t;i++) depth[i]=-1;
depth[0]=0;
q.push(0);
while (!q.empty())
{
x=q.front();q.pop();
for (i=head[x];i;i=nxt[i])
{
y=to[i];
if (depth[y]==-1 && f[i])
{
depth[y]=depth[x]+1;
q.push(y);
}
}
}
//for (i=0;i<=t;i++) cout<<depth[i]<<' ';
//cout<<endl;
if (depth[t]==-1) return false; else return true;
}
int dfs(int x,int maxf)
{
if (x==t) return maxf;
int i,y,now,res=0;
for (i=head[x];i;i=nxt[i])
{
y=to[i];
if (depth[y]==depth[x]+1 && f[i])
{
int minf=min(f[i],maxf-res);
now=dfs(y,minf);
f[i]-=now;
f[i^1]+=now;
res+=now;
}
}
return res;
}
int main ()
{
int i,x,y;
scanf("%d%d",&n,&k);
t=n*2+1;
for (i=1;i<=n;i++) addedge(0,i,1);
for (i=n+1;i<=n*2;i++) addedge(i,t,1);
for (i=1;i<=k;i++)
{
scanf("%d%d",&x,&y);
addedge(x,n+y,1);
}
int ans=0;
while (bfs()) ans+=dfs(0,INF);
printf("%d\n",ans);
return 0;
}