Fold_Fulkerson

hdoj 1532 Drainage Ditches

每次bfs找到一个增广路径,然后根据路径添加反向弧,得到残余网络。直到找不到增广路径。

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

const int inf = 210000000;
int n, m, mp[202][202], P[202];
vector<int> vec[202];

void init() {
	int i, j, a, b, c;
	for( i=0; i<=m; ++i ) {
		vec[i].clear();
		for( j=0; j<=m; ++j) {
			mp[i][j] = inf;
		}
	}

	for( i=0; i<n; ++i ) {
		scanf( "%d %d %d", &a, &b, &c );
		if( mp[a][b] == inf ) {
			vec[a].push_back(b);
			mp[a][b] = c;
		} else mp[a][b] += c;
	}
}


int min( int a, int b) { return a < b ? a : b ; }


int bfs() {
	int Min[202], i, sz, u, v;
	bool mark[202];
	queue<int> Q;
	for( i=0; i<=m; ++i ) {
		Min[i] = inf;
		mark[i] = 0;
		P[i] = i;
	}

	Q.push( 1 );
	mark[1] = 1;
	while( !Q.empty() ) {
		u = Q.front();
		Q.pop();
		sz = vec[u].size();
		for( i=0; i<sz; ++i ) {
			v = vec[u][i];
			if( !mark[v] && mp[u][v] > 0 ) {
				Min[v] = min( Min[u], mp[u][v] );
				mark[v] = 1;
				P[v] = u;
				Q.push(v);
			}
		}
	}
	return Min[m];
}



void Fold_Fulkerson() {
	int a, ans = 0, f, s;
	while( (a = bfs()) != inf ) {
		ans += a;
		s = m;
		f = P[s];
		while( f != s ) {
			
			mp[f][s] -= a;
			mp[s][f] += a;
			s = f;
			f = P[s];
		}
	}

	printf( "%d\n", ans );
}



int main() {
//	freopen( "c:/aaa.txt", "r", stdin );
	while( scanf("%d %d", &n, &m) == 2 ) {
		init();
		Fold_Fulkerson();
	}
	return 0;
}

posted on 2011-03-11 13:17  CrazyAC  阅读(287)  评论(0编辑  收藏  举报