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

POJ 1149 PIGS ( 网络流 )

时间:2015-07-02 06:37:10      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:网络   poj   

主要是建图有些小烦,若几个节点流量的来源或者去向完全相同,且流量为 INF,将它们合并成一个节点。
若从两点间有且仅有一条容量为 INF 的边,将两点合并成一个节点。

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int INF = 0x7fffffff;
const int MAXN = 110;

int capacity[MAXN][MAXN], flow[MAXN][MAXN];
int parent[MAXN], residual[MAXN];
int max_flow, node_num;


void edmond_karp( int source, int target ) {

    queue< int > Q;
    memset( flow, 0, sizeof( flow ) );
    memset( parent, 0, sizeof( parent ) );
    max_flow = 0;

    while ( true ) {
        memset( residual, 0, sizeof( residual ) );
        residual[source] = INF;
        Q.push( source );
        while ( !Q.empty() ) {
            int u = Q.front();
            Q.pop();
            for( int v = 0; v <= node_num + 1; ++v ) {
	            if( !residual[v] && capacity[u][v] > flow[u][v] ) {
	                parent[v] = u;
					Q.push( v );
	                residual[v] = residual[u] < capacity[u][v] - flow[u][v] ? residual[u] : capacity[u][v] - flow[u][v];
				}
			}
        }

        if( residual[target] == 0 )
			break;

        for( int u = target; u != source; u = parent[u] ) {
            flow[parent[u]][u] += residual[target];
            flow[u][parent[u]] -= residual[target];
        }

        max_flow += residual[target];

    }

}


int main() {

	int pighouses_num, customers_num;
    int pighouses_capacity[1010];
    int visited_by_somebody[1010];

    while( cin >> pighouses_num >> customers_num ) {      
		memset( capacity, 0, sizeof( capacity ) );
		memset( visited_by_somebody, 0, sizeof( visited_by_somebody ) );       
        int source = 0, target = customers_num + 1;
        node_num = customers_num;

        for( int i = 1; i <= pighouses_num; ++i )
            cin >> pighouses_capacity[i];

        for( int i = 1; i <= customers_num; ++i ) {	

			int keys_num;
            cin >> keys_num;

            for( int j = 0; j < keys_num; ++j ) {

				int temp;
                cin >> temp;

                if( visited_by_somebody[temp] == 0 )
                    capacity[source][i] += pighouses_capacity[temp];
                else
                    capacity[visited_by_somebody[temp]][i] = INF;
                visited_by_somebody[temp] = i;

            }

            cin >> capacity[i][target];

        }

        edmond_karp( source, target );
        cout << max_flow << endl;

    }

    return 0;

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

POJ 1149 PIGS ( 网络流 )

标签:网络   poj   

原文地址:http://blog.csdn.net/pandora_madara/article/details/46718715

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