POJ 1273 Drainage Ditches

http://poj.org/problem?id=1273

基本最大流问题  

基本介绍

http://www.cnblogs.com/north_dragon/archive/2010/05/23/1741951.html

通俗证明

http://blog.csdn.net/kdqzzxxcc/article/details/7881169

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using std::queue;
const int maxn = 205, INF = (1<<31 - 1);
int flow[maxn], c[maxn][maxn];
int n, m, pre[maxn];
queue<int> q;
int min(int a, int b)
{ return a<=b ?a :b ; }
int bfs(int src, int des)
{
    int i;
    while(!q.empty())
        q.pop();
    for(i=1; i<=m; i++)
    {
        pre[i] = -1 ;
    }
    q.push(src);
    flow[src] = INF;
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        for(int v=1; v<=m && pre[des]==-1; v++)
        {
            if(c[u][v]>0 && pre[v]==-1)
            {
                pre[v] = u;
                flow[v] = min(flow[u], c[u][v]);
                q.push(v);
            }
        }
    }
    if(pre[des] == -1) //v>m退出肯定存在环路
        return -1;
    else
        return flow[des];
}
int maxFlow(int src, int des)
{
    int sumFlow = 0, increase, u;
    while(increase = bfs(src,des), increase != -1)
    {
        for(u=des; u!=src; u=pre[u])
        {
            c[u][pre[u]] += increase;
            c[pre[u]][u] -= increase;
        }
        sumFlow += increase ;
    }
    return sumFlow;
}
int main()
{    
    int a, b, d;
    while(scanf("%d %d", &n, &m)!=EOF)
    {
        memset(c, 0, sizeof(c));
        for(int i=1; i<=n; i++)
        {
            scanf("%d %d %d", &a, &b, &d);
            c[a][b] += d;     //  重边啊!
        }
        printf("%d\n", maxFlow(1, m));
    }
    
    return 0;
}

 

posted @ 2013-03-04 17:07  April_Tsui  阅读(132)  评论(0编辑  收藏  举报