Poj 1274 The Perfect Stall(二分图匹配)

时间:2021-10-22 06:14:12

题目链接

题目大意:输入N、M,N代表有N只奶牛,M代表有M个吃饭的地方

                   然后输入N行,每行第一个数字代表后面输入几个数字,后面的数字是牛喜欢吃饭的地方的编号(每个吃饭的地方只能让一个牛吃)

                   然后让你求出来,能在喜欢的地方吃饭的牛的最大数目

Code:

/*
纠结点:怎么把吃饭的地方和奶牛编号对应起来
没关系,一样算,给吃饭的地方也按顺序编上号,这样就处理好了
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int maxn = 2100;
int V; //顶点数
vector<int> G[maxn]; //图的邻接表表示
int match[maxn]; //所匹配的点
int used[maxn]; //DFS中用到的访问顶点

void add_edge(int u, int v)
{
G[u].push_back(v);
G[v].push_back(u);
}

bool dfs(int v)
{
used[v] = true;
for(int i = 0; i < G[v].size(); i++){
int u = G[v][i], w = match[u];
if(w < 0 || !used[w] && dfs(w)){
match[v] = u; match[u] = v;
return true;
}
}
return false;
}

int bipartite_matching()
{
int res = 0;
memset(match, -1, sizeof(match));
for(int v = 0; v < V; v++){
if(match[v] < 0){
memset(used, 0, sizeof(used));
if(dfs(v))
res++;
}
}
return res;
}

int main()
{
int M, N;
while(scanf("%d %d", &N, &M) != EOF){
V = M+N;
for(int i = 0; i < V; i++)
G[i].clear();
for(int i = 0; i < N; i++){
int sum, num;
scanf("%d", &sum);
while(sum--){
scanf("%d", &num);
add_edge(i, N+num-1);
}
}
int tot = bipartite_matching();
cout << tot << endl;
}
return 0;
}