USACO Stall

  这个题的意思是有N个奶牛, M个围栏, 一个奶牛喜欢并且只会在某个围栏中产奶, 最多能使几个奶牛同时产奶?可以构造这样的一个图,这个图的源点指向每个奶牛, 每个奶牛指向自己喜欢的围栏, 每个围栏指向汇点, 求解一次最大流即可。代码如下:

/*
    ID: m1500293
    LANG: C++
    PROG: stall4
*/

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;
const int maxn = 450;
const int INF = 0x3fffffff;

struct Edge
{
    int from, to, cap, flow;
    Edge(int u, int v, int c, int f):from(u), to(v), cap(c), flow(f){}
};

struct EdmondsKarp
{
    int n, m;              //n个顶点 m条边
    vector<Edge> edges;
    vector<int> G[maxn];
    int a[maxn];           //起点到i的可改进量
    int p[maxn];           //最短路树上的入弧编号

    void init()
    {
        for(int i=0; i<n; i++) G[i].clear();
        edges.clear();
    }
    void AddEdge(int from, int to, int cap)
    {
        edges.push_back(Edge(from, to, cap, 0));
        edges.push_back(Edge(to, from, 0, 0));
        m = edges.size();
        G[from].push_back(m-2);
        G[to].push_back(m-1);
    }
    int Maxflow(int s, int t)
    {
        int flow = 0;
        for(;;)
        {
            memset(a, 0, sizeof(a));
            queue<int> Q;
            Q.push(s);
            a[s] = INF;
            while(!Q.empty())
            {
                int x = Q.front(); Q.pop();
                for(int i=0; i<G[x].size(); i++)
                {
                    Edge &e = edges[G[x][i]];
                    if(!a[e.to] && e.cap>e.flow)
                    {
                        p[e.to] = G[x][i];
                        a[e.to] = min(a[x], e.cap-e.flow);
                        Q.push(e.to);
                    }
                }
                if(a[t]) break;
            }
            if(!a[t]) break;
            for(int u=t; u!=s; u=edges[p[u]].from)
            {
                edges[p[u]].flow += a[t];
                edges[p[u]^1].flow -= a[t];
            }
            flow += a[t];
        }
        return flow;
    }
}ek;

int main()
{
    freopen("stall4.in", "r", stdin);
    freopen("stall4.out", "w", stdout);
    int N, M;
    scanf("%d%d", &N, &M);   //N头奶牛  M个围栏
    ek.n = N+M+2;
    ek.init();
    for(int i=1; i<=N; i++)
    {
        ek.AddEdge(0, i, 1);
        int num;
        scanf("%d", &num);
        while(num--)
        {
            int t;
            scanf("%d", &t);
            ek.AddEdge(i, N+t, 1);
        }
    }
    for(int i=1; i<=M; i++)
        ek.AddEdge(N+i, N+M+2-1, 1);
    printf("%d\n", ek.Maxflow(0, N+M+2-1));
    return 0;
}

 

posted @ 2016-01-23 23:45  xing-xing  阅读(149)  评论(0编辑  收藏  举报