POJ1274_The Perfect Stall_二分图匹配模板题

来源:互联网 发布:python 日期月份加减 编辑:程序博客网 时间:2024/06/15 00:50

题意

给n头牛和m个牛棚,一头牛只能在特定的牛棚产奶,一个牛棚只能同时容纳一头牛。求最大产奶数的牛和牛棚匹配方案。

思路

二分图匹配的模板题

题目链接

http://poj.org/problem?id=1274

AC代码

#include<cstdio>#include<iostream>#include<vector>#include<cstring>using namespace std;const int maxn = 200 + 10;int n, m;vector<int> G[maxn * 2];//存图int match[maxn * 2];//存匹配bool usd[maxn * 2];//一次dfs中的访问标记//添加边void Add(int a, int b){    G[a].push_back(b);    G[b].push_back(a);}//dfs找增广路bool dfs(int v){    usd[v] = true;    for(int i= 0; i< G[v].size(); i++)    {        int u = G[v][i], w = match[u];        if(w < 0 || !usd[w] && dfs(w))        {            match[v] = u;            match[u] = v;            return true;        }    }    return false;}//最大匹配int max_match(){    int res = 0;    memset(match, -1, sizeof match);    for(int v= 0; v< n; v++)        if(match[v] < 0)    {        memset(usd, false, sizeof usd);        if(dfs(v)) res ++;    }    return res;}int main (){    while(scanf("%d %d", &n, &m) != EOF)    {        for(int i= 0; i<= n+m; i++)                G[i].clear();        for(int i= 0; i< n; i++)        {            int s;            scanf("%d", &s);            while(s--)            {                int t;                scanf("%d", &t);                Add(i, n+t);//添加边            }        }        cout << max_match() << endl;    }    return 0;}
原创粉丝点击