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

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<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int num,head[80010],n,m,s,link[40010];
bool vis[40010];
struct node{
    int to,pre;
}e[80010];
void Insert(int from,int to){
    e[++num].to=to;
    e[num].pre=head[from];
    head[from]=num;
}
bool dfs(int x){
    for(int i=head[x];i;i=e[i].pre){
        int to=e[i].to;
        if(vis[to]==0){
            vis[to]=1;
            if(link[to]==0||dfs(link[to])){
                link[to]=x;
                return 1;
            }
        }
    }
    return 0;
}
int main(){
    scanf("%d%d",&n,&m);int x;
    for(int i=1;i<=n;i++){
        scanf("%d",&s);
        for(int j=1;j<=s;j++){
            scanf("%d",&x);
            Insert(i,x);
        }
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        memset(vis,0,sizeof(vis));
        if(dfs(i))ans++;
    }
    printf("%d",ans);
}
原文地址:https://www.cnblogs.com/thmyl/p/7348682.html