usaco-4.2.2The Perfect Stall完美的牛栏

来源:互联网 发布:java 解析swf 编辑:程序博客网 时间:2024/06/01 08:17

题目链接http://218.62.22.209:8080/problem.php?cid=1518&pid=6

时间限制: 1 Sec 内存限制: 128 MB
提交: 128 解决: 73
题目描述
农夫约翰上个星期刚刚建好了他的新牛棚,他使用了最新的挤奶技术。不幸的是,由于工程问题,每个牛栏都不一样。第一个星期,农夫约翰随便地让奶牛们进入牛栏,但是问题很快地显露出来:每头奶牛都只愿意在她们喜欢的那些牛栏中产奶。上个星期,农夫约翰刚刚收集到了奶牛们的爱好的信息(每头奶牛喜欢在哪些牛栏产奶)。一个牛栏只能容纳一头奶牛,当然,一头奶牛只能在一个牛栏中产奶。
给出奶牛们的爱好的信息,计算最大分配方案。
输入
第一行 两个整数,N (0 <= N <= 200) 和 M (0 <= M <= 200) 。N 是农夫约翰的奶牛数量,M 是新牛棚的牛栏数量。
第二行到第N+1行 一共 N 行,每行对应一只奶牛。第一个数字 (Si) 是这头奶牛愿意在其中产奶的牛栏的数目 (0 <= Si <= M) 。后面的 Si 个数表示这些牛栏的编号。牛栏的编号限定在区间 (1..M) 中,在同一行,一个牛栏不会被列出两次。

输出
只有一行。输出一个整数,表示最多能分配到的牛栏的数量。
样例输入
5 5
2 2 5
3 2 3 4
2 1 5
3 1 2 5
1 2

样例输出
4

#include <cstdio>#include <iostream>#include <cstring>#define N 10005using namespace std;int n,m;int head[N];int to[N];int nex[N];int match[N];bool v[N];int tot;inline void add(int x,int y){    ++tot;    nex[tot]=head[x];    head[x]=tot;    to[tot]=y;}int dfs(int u){    for(int i=head[u];i;i=nex[i]){        if(!v[to[i]]){            v[to[i]]=1;            if(!match[to[i]]||dfs(match[to[i]])){                match[to[i]]=u;                return 1;            }        }    }    return 0;}int main(){    scanf("%d%d",&n,&m);    for(int i=1;i<=n;i++){        int si;        int y;        scanf("%d",&si);        for(int j=1;j<=si;j++){            scanf("%d",&y);            add(i,y);        }    }    int ans=0;    for(int i=1;i<=n;i++){        memset(v,0,sizeof(v));        if(dfs(i)) ans++;    }    printf("%d",ans);    return 0;}

第二道匈牙利~~

原创粉丝点击