USACO ditch

  裸网络流最大流题, 我使用了EdmondsKarp算法来解决这个问题, 其中1是源点, m是汇点。代码如下:

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

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

using namespace std;
const int maxn = 205;
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];      //最短路上p的入弧编号

    void init()
    {
        for(int i=1; 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];         //记录连接e.to的边
                        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("ditch.in", "r", stdin);
    freopen("ditch.out", "w", stdout);
    int n, m;
    scanf("%d%d", &n, &m);
    ek.n = m;
    ek.m = n;
    ek.init();
    for(int i=0; i<n; i++)
    {
        int u, v, f;
        scanf("%d%d%d", &u, &v, &f);
        ek.AddEdge(u, v, f);
    }
    printf("%d
", ek.Maxflow(1, m));
    return 0;
}
原文地址:https://www.cnblogs.com/xingxing1024/p/5151456.html