二分图查找,使用dfs匈牙利法:
#include<iostream>
using namespace std;
const int MAX=501;
int n,m;
int mx[MAX],my[MAX],vist[MAX],g[MAX][MAX];
bool search(int u)
{
int j;
//cout << "起点" << u << " ";
for(j=1;j<=n;j++)
{
if(g[u][j] && !vist[j])
{
vist[j]=true;
if(my[j]==-1 || search(my[j]))
{
//cout <<"边" << u <<j << " " << endl;
mx[u]=j;
my[j]=u;
return true;
}
}
}
return false;
}
int main()
{
int i,tempx,tempy,count=0;
//freopen("infor3014.txt","r",stdin);
memset(mx,-1,sizeof(mx));
memset(my,-1,sizeof(my));
memset(g,0,sizeof(g));
cin >> n >> m;
for(i=1;i<=m;i++)
{
cin >> tempx >> tempy;
g[tempx][tempy]=1;
}
for(i=1;i<=n;i++)
{
memset(vist,false,sizeof(vist));
if(mx[i]==-1)
{
if(search(i))
count++;
}
}
//fclose(stdin);//关闭文件
cout << count << endl;
return 0;
}