这题是一道DAG图的最小路径覆盖问题。
DAG图的最小路径覆盖:
用尽量少的不相交简单路径覆盖有向无环图(DAG)G的所有顶点,这就是DAG图的最小路径覆盖问题。
方法主体是:DAG图的最小路径覆盖数=节点数(n)- 最大匹配数(m)
在题目中,将所有地点(1,2,3...n)都当做两份,形成共含有2n个节点的二分图。然后寻找到最大匹配,在以节点数n减去最大匹配数就可以了。
匈牙利算法,代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=125;
bool visit[maxn];
int match[maxn],head[maxn];
int key[maxn*maxn],next[maxn*maxn];
int num;
void hash(int a,int b)
{
key[num]=b;
next[num]=head[a];
head[a]=num++;
}
bool find(int start)
{
int temp;
for(int i=head[start];i!=-1;i=next[i])
{
temp=key[i];
if(!visit[temp])
{
visit[temp]=true;
if(match[temp]==-1||find(match[temp]))
{
match[temp]=start;
return true;
}
}
}
return false;
}
int result(int min)
{
int sum=0;
for(int i=1;i<=min;i++)
{
memset(visit,false,sizeof(visit));
if(find(i))
sum++;
}
return sum;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,m;
scanf("%d%d",&n,&m);
num=0;
memset(head,-1,sizeof(head));
memset(match,-1,sizeof(match));
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
hash(a,b);
}
printf("%d\n",n-result(n));
}
return 0;
}