POJ - 1273 Drainage Ditches(最大流)

来源:互联网 发布:windows控制台程序作用 编辑:程序博客网 时间:2024/06/10 04:49

裸的最大流,贴上刘汝佳紫书上的模板就能过。


#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <algorithm>#include <cstring>#include <queue>#include <vector>using namespace std;const int maxn=420;const int INF=0x3f3f3f3f;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;    vector<Edge> edge;    vector<int> G[maxn];    int a[maxn];    int p[maxn];    void init(int n)    {        for(int i=1; i<=n; i++)            G[i].clear();        edge.clear();    }    void AddEdge(int from, int to, int cap)    {        edge.push_back(Edge(from, to, cap, 0));        edge.push_back(Edge(to, from, 0, 0));        m=edge.size();        G[from].push_back(m-2);        G[to].push_back(m-1);    }    int Maxflow(int s, int t)    {        int flow=0;        while(1)        {            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=edge[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=edge[p[u]].from)            {                edge[p[u]].flow+=a[t];                edge[p[u]^1].flow-=a[t];            }            flow+=a[t];        }        return flow;    }}solver;int main(){    int n, m;    while(~scanf("%d%d", &m, &n))    {        solver.init(n);        while(m--)        {            int u, v, c;            scanf("%d%d%d", &u, &v, &c);            solver.AddEdge(u, v, c);        }        printf("%d\n", solver.Maxflow(1, n));    }    return 0;}


0 0
原创粉丝点击