洛谷P1894 [USACO4.2]完美的牛栏The Perfect Stall(二分图最大匹配)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhanghaoxian1/article/details/83513303

P1894 [USACO4.2]完美的牛栏The Perfect Stall

题目描述
农夫约翰上个星期刚刚建好了他的新牛棚,他使用了最新的挤奶技术。不幸的是,由于工程问题,每个牛栏都不一样。第一个星期,农夫约翰随便地让奶牛们进入牛栏,但是问题很快地显露出来:每头奶牛都只愿意在她们喜欢的那些牛栏中产奶。上个星期,农夫约翰刚刚收集到了奶牛们的爱好的信息(每头奶牛喜欢在哪些牛栏产奶)。一个牛栏只能容纳一头奶牛,当然,一头奶牛只能在一个牛栏中产奶。
给出奶牛们的爱好的信息,计算最大分配方案。

输入输出格式
输入格式:
第一行 两个整数,N (0 <= N <= 200) 和 M (0 <= M <= 200) 。N 是农夫约翰的奶牛数量,M 是新牛棚的牛栏数量。

第二行到第N+1行 一共 N 行,每行对应一只奶牛。第一个数字 (Si) 是这头奶牛愿意在其中产奶的牛栏的数目 (0 <= Si <= M)。后面的 Si 个数表示这些牛栏的编号。牛栏的编号限定在区间 (1…M) 中,在同一行,一个牛栏不会被列出两次。

输出格式:
只有一行。输出一个整数,表示最多能分配到的牛栏的数量.

输入输出样例
输入样例#1:
5 5
2 2 5
3 2 3 4
2 1 5
3 1 2 5
1 2
输出样例#1:
4
说明
N (0 <= N <= 200)
M (0 <= M <= 200)

代码

#include <cstdio>
#include <string>
#include <cstring>
#define N 50000
using namespace std;

struct arr
{
	int to, nxt;
}a[N];
int n,m,ls[N],link[N],l;
bool v[N];

void add(int x, int y)
{
	a[++l].to = y;
	a[l].nxt = ls[x];
	ls[x] = l;
}

bool find(int x)
{
	for (int i = ls[x]; i; i = a[i].nxt)
		if (!v[a[i].to])
		{
			v[a[i].to] = true;
			if (!link[a[i].to] || find(link[a[i].to])) 
			{
				link[a[i].to] = x;
				return true;
			}
		}
	return false;
}

int main()
{
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
	{
		int s;
		scanf("%d", &s);
		while (s--)
		{
			int x;
			scanf("%d", &x);
			add(i, x);
		} 
	}
	int ans = 0;
	for (int i = 1; i <= n; i++)
	{
		memset(v, false, sizeof(v));
		if (find(i)) ans++;
	}
	printf("%d\n", ans);
}

猜你喜欢

转载自blog.csdn.net/zhanghaoxian1/article/details/83513303