版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/readlnh/article/details/52759695
题意
有n个奶牛和m个谷仓,现在每个奶牛有自己喜欢去的谷仓,并且它们只会去自己喜欢的谷仓吃东西,问最多有多少奶牛能够吃到东西。
输入第一行给出n与m
接着n行
每行第一个数代表这个奶牛喜欢的谷仓的个数s,后面接着s个数代表这个奶牛喜欢哪个谷仓
思路
典型的二分图匹配,n头牛和m个谷仓都抽象成点,如果某头牛喜欢某个谷仓的话就连一条边,然后求二分匹配。思维上没什么特殊的地方,这里实现上我用的是匈牙利算法,对于整个图,分别是矩阵表示和临接表(前向星)表示。
代码
矩阵
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int kMaxn = 200 + 5;
bool g[kMaxn][kMaxn];
int match[kMaxn];
bool vis[kMaxn];
int n,m;
bool Dfs(int u) {
for(int v = 1; v <= m; v++) {
if(!vis[v] && g[u][v]) {
vis[v] = true;
if(match[v] == -1 || Dfs(match[v])) {
match[v] = u;
return true;
}
}
}
return false;
}
int MaxMatch() {
memset(match, -1, sizeof(match));
int ans = 0;
for(int i = 1; i <= n; i++) {
memset(vis, false, sizeof(vis));
ans += Dfs(i);
}
return ans;
}
int main() {
while(~scanf("%d %d", &n, &m)) {
memset(g, false, sizeof(g));
for(int i = 1; i <= n; i++) {
int s;
scanf("%d", &s);
while(s--) {
int x;
scanf("%d", &x);
g[i][x] = true;
}
}
printf("%d\n", MaxMatch());
}
return 0;
}
前向星
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int kMaxn = 200 + 5;
struct Edge {
int from,to;
int next;
}g[kMaxn * kMaxn];
int head[kMaxn];
int match[kMaxn];
bool vis[kMaxn];
int n,m;
int top;
void Init() {
memset(head, -1, sizeof(head));
top = 0;
}
void AddEdge(int from, int to) {
g[top] = (Edge){from, to, head[from]};
head[from] = top++;
}
bool Dfs(int u) {
for(int i = head[u]; i != -1; i = g[i].next) {
int v = g[i].to;
if(!vis[v]) {
vis[v] = true;
if(match[v] == -1 || Dfs(match[v])) {
match[v] = u;
return true;
}
}
}
return false;
}
int MaxMatch() {
memset(match, -1, sizeof(match));
int ans = 0;
for(int i = 1; i <= n; i++) {
memset(vis, false, sizeof(vis));
ans += Dfs(i);
}
return ans;
}
int main() {
while(~scanf("%d %d", &n , &m)) {
Init();
for(int i = 1; i <= n; i++) {
int s;
scanf("%d", &s);
while(s--) {
int x;
scanf("%d", &x);
AddEdge(i, x);
}
}
printf("%d\n", MaxMatch());
}
return 0;
}