我的第一道二分圖匹配題,把矩陣構造爲二分圖由兩部分點集構成,座標(x,y)出遊障礙物即可看爲集合A中的x與集合B中的y鄰接,問題就轉化成爲選擇最少的一些點(x或y),使得從這些點與所有的邊相鄰,即轉化爲了最小點覆蓋問題。由二分圖最大匹配的König定理:最小點覆蓋數 = 最大匹配數。用匈牙利算法即可求值。
#include<iostream>
using namespace std;
const int MAXN = 501;
bool vis[MAXN];
int result[MAXN];
bool space[MAXN][MAXN];
bool refresh(int i,int n)
{
for(int j=1;j!=n+1;j++)
{
if(!vis[j] && space[i][j]==1)
{
vis[j]=true;
if(result[j]==0 || refresh(result[j],n))
{
result[j] = i;
return true;
}
}
}
return false;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
int ans(0);
memset(result,0,sizeof(result));
while(m--)
{
int a,b;cin>>a>>b;
space[a][b] = true;
}
for(int i=1;i!=n+1;i++)
{
memset(vis,0,sizeof(vis));
if(refresh(i,n))
ans++;
}
cout<<ans<<endl;
}
return 0;
}