AC代码
#include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
#define inf 0x3f3f3f3f
const int N=300;
int n,match[N],f[N];
bool book[N],e[N][N];
int getf(int x)
{
if(f[x]==x)
return x;
return f[x]=getf(f[x]);
}
void merge(int x,int y)
{
int t1=getf(x);
int t2=getf(y);
f[t2]=t1;
}
bool dfs(int x)
{
for(int i=1; i<=n; i++)
{
if(book[i]==0&&e[x][i])
{
book[i]=1;
if(match[i]==-1||dfs(match[i]))
{
match[i]=x;
return 1;
}
}
}
return 0;
}
int main()
{
int m,F,T;
scanf("%d",&T);
while(T--)
{
scanf("%d %d %d",&n,&m,&F);
for(int i=1; i<=n; i++)
f[i]=i;
memset(e,0,sizeof(e));//注意清空,不然WA
memset(match,-1,sizeof(match));//清空。。
for(int i=1; i<=m; i++) //girl and boy never quarrel
{
int x,y;
scanf("%d %d",&x,&y);
e[x][y]=1;
}
for(int i=1; i<=F; i++)//x and y are friends
{
int x,y;
scanf("%d %d",&x,&y);
merge(x,y);
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
int t1=getf(f[i]);
int t2=getf(f[j]);
if(t1==t2)
{
for(int k=1; k<=n; k++)
{
if(e[i][k]||e[j][k])
e[i][k]=e[j][k]=1;
}
}
}
}
int ans=0;
while(1)
{
memset(match,-1,sizeof(match));
int w=0;
for(int i=1; i<=n; i++)
{
memset(book,0,sizeof(book));
w+=dfs(i);
}
if(w==n)
{
ans++;
for(int i=1; i<=n; i++)
{
// if(match[i]!=-1)
e[match[i]][i]=0;
}
}
else
break;
}
printf("%d\n",ans);
}
return 0;
}
参考博客
https://blog.csdn.net/jingdianitnan/article/details/24151631?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-7&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-7