您的位置:首页 > 大数据 > 人工智能

hdu1532 Drainage Ditches

2015-08-24 19:49 525 查看
裸的一道网络流 主要边是单向的 会有重边 别的就没什么了

最近开始学网络流了 并没有想象中的那么难理解 这题用的EK算法过的 EK算法还是很好理解的 只是不够快 版子是按照刘汝佳的书上敲的 感觉还是挺优美的

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
#include<set>
#define scnaf scanf
#define cahr char
#define bug puts("bugbugbug");
using namespace std;
typedef long long ll;
const int maxn=1e5+100;
const int INF=1e9+500;
struct Edge
{
    int from,to,cap,flow;
    Edge(int a,int b,int c,int d):from(a),to(b),cap(c),flow(d) {}
};
struct EdmondsKarp//EK 还是蛮好理解的
{
    int n,m;
    vector<Edge> edges;//边数的两倍
    vector<int> G[maxn];//邻接表,G[i][j]表示节点i的第j条边在e数组中的序号
    int a[maxn];//当起点到i的可改进量
    int p[maxn];//最短路树上p的入弧编号

    void init(int n)
    {
        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;
        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=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;
    }
};
int main()
{
    int m,n;
    while(~scanf("%d%d",&m,&n))
    {
        EdmondsKarp z;
        z.init(n);
        for(int i=0;i<m;i++)
        {
            int a,b,c;
            scnaf("%d%d%d",&a,&b,&c);
            z.AddEdge(a,b,c);
        }
        printf("%d\n",z.Maxflow(1,n));
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: