题目所求为最小路径覆盖。注意图为 有向无环图
最小路径覆盖=图的顶点数- 图的最大匹配数
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int map[150][150],match[150];
bool vis[150];
int n,m;
bool dfs(int i){
for (int j=1;j<=n;j++){
if (!vis[j]&&map[i][j]){
vis[j]=true;
if (match[j]==-1|| dfs(match[j])){
match[j]=i;
return true;
}
}
}
return false;
}
int Match(){
int ret=0;
memset(match,-1,sizeof(match));
for (int i=1;i<=n;i++){
memset(vis,false,sizeof(vis));
ret+=dfs(i);
}
return ret;
}
int main(){
int cases,u,v;
scanf("%d",&cases);
while (cases--){
scanf("%d%d",&n,&m);
memset(map,0,sizeof(map));
for (int i=1;i<=m;i++){
scanf("%d%d",&u,&v);
map[u][v]=1;
}
printf("%d\n",n-Match());
}
return 0;
}