Poj 1459 Power Network 最大流


        Poj的1459题Power Network,很明显的最大流算法,只要添加一个源点S,一个汇点T即可。

       使用Edmonds_Karp算法可以很快的求出最大流。

       不过有一点需要注意,测试数据中容量C不累加,即C[i][j] += c是错误的。我在这里被坑了好久。

#include <iostream>
#include <string>
#include <queue>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

#define MAXNODE 1000
#define INF  999999
typedef int REAL;

REAL Capacity[MAXNODE][MAXNODE];
REAL Flow[MAXNODE][MAXNODE];
REAL MinFlow[MAXNODE];
int  Pre[MAXNODE];

int S, T;
int n;


REAL maxFlow()
{
    REAL sumFlow = 0;

    while(true)
    {
        memset(Pre, -1, sizeof(Pre));

        queue<int>Q;
        Q.push(S);

        MinFlow[S] = INF;
        Pre[S] = S;

        while(!Q.empty())
        {
            int node = Q.front();
            Q.pop();

            //cout << "Visit node :" << node << endl;
            if(node == T){
               // cout << "break" << endl;
                break;
            }

            for(int i = 0; i <= n; i++)
            {
                if(Pre[i] == -1 && Capacity[node][i] > Flow[node][i])
                {
                    Pre[i] = node;
                    MinFlow[i] = MinFlow[node] < Capacity[node][i] - Flow[node][i] ? MinFlow[node] : Capacity[node][i] - Flow[node][i] ;

                    Q.push(i);
                }
            }
        }

        if(Pre[T] == -1)
            break;

        sumFlow +=  MinFlow[T];

        int nowNode = T;
        int preNode;
        while(nowNode != S)
        {
            preNode = Pre[nowNode];

            Flow[preNode][nowNode] += MinFlow[T];
            Flow[nowNode][preNode] -= MinFlow[T];

            nowNode = preNode;
        }
    }

    return sumFlow;
}


int main()
{
    //freopen("data.txt", "r", stdin);

    int np, nc, e;

    while(scanf("%d%d%d%d", &n, &np, &nc, &e) != EOF)
    {
            memset(Capacity, 0, sizeof(Capacity));
            memset(Flow, 0, sizeof(Flow));
            n++;
            S = 0;
            T = n;

            int u, v;
            REAL c;

            while(e--)
            {
                while(getchar() != '(');

                scanf("%d,%d)%d", &u, &v, &c);

                //printf("%d %d --> %d\n", u,v,c);
                Capacity[u+1][v+1] = c;
            }

            while(np--)
            {
                while(getchar() != '(');

                scanf("%d)%d", &v, &c);

                //printf("%d %d --> %d\n", u,v,c);
                Capacity[S][v+1] = c;
            }

            while(nc--)
            {
                while(getchar() != '(');

                scanf("%d)%d", &u, &c);

                //printf("%d %d --> %d\n", u,v,c);
                Capacity[u+1][T] = c;
            }

            cout << maxFlow() << endl;
    }


    return 0;
}

点赞