原题:http://poj.org/problem?id=1274
大意:裸的二分图匹配,每一头牛给出它喜欢的地方,请你给出最多多少牛能住到它最喜欢的地方
其实匈牙利算法已经有一个讲的很好的blog了,贴一下传送门
https://blog.csdn.net/dark_scope/article/details/8880547
因为这个blog已经通俗的不能再通俗了,所以我就讲讲程序里面的一些细节。
先贴代码后分析:
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=205;
vector<int> m[maxn];
int match[maxn],used[maxn];
int N,M;
bool dfs(int aim){
used[aim]=1;
for(int i=0;i<m[aim].size();i++){
int to=m[aim][i];
if(!match[to]||!used[match[to]]&&dfs(match[to])){
match[to]=aim;
return 1;
}
}
return 0;
}
void solve(){
memset(match,0,sizeof(match));
memset(used,0,sizeof(used));
int res=0;
for(int i=1;i<=N;i++){
memset(used,0,sizeof(used));
if(dfs(i)) res++;
}
cout<<res<<endl;
}
int main(){
while(cin>>N>>M){
for(int i=1;i<=N;i++) m[i].clear();
for(int i=1;i<=N;i++){
int cnt;
scanf("%d",&cnt);
while(cnt--){
int sto; scanf("%d",&sto);
m[i].push_back(sto);
}
}
solve();
}
return 0;
}
if(!match[to]||!used[match[to]]&&dfs(match[to]))
上面这条代码,!match[to] 表示的就是那个地方还没有安排主人就马上安排。
!used[match[to]]&&dfs(match[to]) 这个表示的是假如那个地方有主人了,那么假如其主人在本次更新中还没有挪过位置,那么就请试一下可不可以挪(塞进dfs)
然后其他也没啥好讲的了,又水了一篇博客233