码迷,mamicode.com
首页 > 其他好文 > 详细

网络最大流

时间:2015-05-05 23:11:59      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define min( x, y )  (x) < (y) ? (x) : (y)
const int maxn = 100;
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> edges;
    vector<int>  G[maxn];
    int a[maxn];
    int p[maxn];
    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;
        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;
    }
};

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    EdmondsKarp graph;
    int m, n;
    int from , to , cap ;
    while( ~scanf("%d%d",&m , &n) )
    {
        graph.init( graph.n );
        for( int i = 0 ; i < n ; i++ )
        {
            scanf("%d%d%d",&from , &to , &cap );
            graph.AddEdge( from , to , cap );
        }
        cout << "Max flow : " << graph.Maxflow( 0 , m-1 ) << endl;
    }
    return 0;
}

 

网络最大流

标签:

原文地址:http://www.cnblogs.com/zhping/p/4480418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!