POJ 1274 The Perfect Stall

来源:互联网 发布:上海大数据开放平台 编辑:程序博客网 时间:2024/06/10 22:40

题意:有n头牛,m个位置,每头牛都有最喜欢的位置,一个位置只能待一头牛,最多能有多少头牛可以待在自己喜欢的位置

解题思路:二分图的最大匹配.裸的二分图,将每头牛和自己喜欢的位置建边,建边的时候点要从0开始,注意位置对应的点一定要加上V,否则牛和位置都是从0开始,就会有重复的点

代码:

#include <iostream>#include <algorithm>#include <cstring>#include <string>#include <cstdio>#include <cmath>#include <vector>using namespace std;const int maxv=100000;int V,m;vector<int> G[maxv];int match[maxv];bool used[maxv];void add_edge(int u,int v){    G[u].push_back(v);    G[v].push_back(u);}bool dfs(int v){    used[v]=true;    for(int i=0;i<G[v].size();i++)    {        int u=G[v][i],w=match[u];        if(w<0||!used[w]&&dfs(w))        {            match[v]=u;            match[u]=v;            return true;        }    }    return false;}int b_match(){    int res=0;    memset(match,-1,sizeof(match));    for(int v=0;v<V;v++)    {        if(match[v]<0)        {            memset(used,0,sizeof(used));            if(dfs(v))            {                res++;            }        }    }    return res;}int main(){    while(scanf("%d%d",&V,&m)==2)    {        for(int i=0;i<V;i++)        {            G[i].clear();        }        int k;        for(int i=0;i<V;i++)        {            scanf("%d",&k);            int x;            while(k--)            {                scanf("%d",&x);                add_edge(i,V+x-1);            }        }        printf("%d\n",b_match());    }    return 0;}/*5 52 2 53 2 3 42 1 53 1 2 51 2 */


原创粉丝点击