hdu1532网络流(DINIC)

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :2015
File Name   :
思路:最大流模板题,这个的点不是很多,只有200个,所以选择了用矩阵存图;再就是最大流的算法原理,
寻找增光路径中的瓶颈边的最大流量cur_flow,然后递归每条边减去cue_flow;如果不能在依赖最短路径增广,
就重新bfs扩展最短路径,如果不能扩展就结束算法,不然就继续dfs找增光路径;
*****************************************/
// #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define MEM(a,b) memset(a,b,sizeof a)
#define pk push_back
template<class T> inline T Get_Max(const T&a,const T&b){return a < b?b:a;}
template<class T> inline T Get_Min(const T&a,const T&b){return a < b?a:b;}
typedef long long ll;
typedef pair<int,int> ii;
const int inf = 1 << 30;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int maxn = 210;
int n,m;
int s[maxn][maxn];
int dis[maxn];
bool bfs(){
	queue<int> que;
	MEM(dis,-1);
	dis[1] = 0;
	que.push(1);
	while(!que.empty()){
		int u = que.front();
		que.pop();
		for (int i = 1;i <= n;++i){
			if (dis[i] == -1 && s[u][i]){
				dis[i] = dis[u] + 1;
				que.push(i);
			}
		}
	}
	return dis[n] != -1;
}

int dfs(int to,int cur_flow){
	int ret = cur_flow;
	if (to == n) return cur_flow;
	for (int i = 1;i <= n;++i){
		if (s[to][i] > 0 && dis[to] + 1 == dis[i])//第二个条件是保证最短路路径的
		{
			int flow = dfs(i,Get_Min(cur_flow,s[to][i]));
			if (flow > 0){
				s[to][i] -= flow;
				s[i][to] += flow;
				return flow;
			}
		}
	}
	return 0;
}

int DINIC(){
	int cur_flow;
	int sum = 0;
	while(bfs()){
		while((cur_flow = dfs(1,INF)))
			sum += cur_flow;
	}
	return sum;
}

int main()
{	
	// ios::sync_with_stdio(false);
	freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	while(~scanf("%d%d",&m,&n)){
		int u,v,c;
		MEM(s,0);
		while(m--){
			scanf("%d%d%d",&u,&v,&c);
			s[u][v] += c;
		}
		printf("%d\n",DINIC());
	}
	return 0;
}


你可能感兴趣的:(图论,网络流,最大流)