网络流 DFS实现

本文介绍了一种基于深度优先搜索(DFS)的网络流算法实现,并通过C++代码详细展示了算法的具体步骤。从输入源点和终点开始,构建网络流模型,通过不断寻找增广路径来更新流量矩阵,直到无法找到新的增广路径为止。

Hello,everyone.See you again.Today i want to show you the algorithm of network flow based on DFS.It is easy,and next i will show you the other ways to solve the network flow problem.

Have fun coding,i_human.Have fun coding,everyone!


THE CODE:

// 网络流算法.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#define a 100

using namespace std;

int rec[a][a];//过程中记录作用,以点为对象
int tmp[a];   //记录作用,记录路径
int cap[a][a];
int flow[a][a];
int n,e;
int s,t;//源点终点
int summary=0;
int sum();
bool judge();

int main()
{
	cin>>s>>t;
	int u,v,w;
	cin>>n>>e;
	for(int i=0;i<a;i++)
		for(int j=0;j<a;j++)
		{
			flow[i][j]=0;
			cap[i][j]=0;
			rec[i][j]=0;
		}
	for(int i=0;i<a;i++)
		tmp[i]=0;
	tmp[1]=s;
	for(int i=0;i<e;i++)
	{
		cin>>u>>v>>w;
		cap[u][v]=w;
		rec[u][0]++;
		rec[u][rec[u][0]]=v;
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=0;j<=n;j++)
			cout<<rec[i][j]<<" ";
		cout<<endl;
	}
	while(judge())
	{
		summary=sum();
	}
	cout<<summary<<endl;
	system("pause");
	return 0;
}

int sum()
{
	int min=a;
	int tem=2;
	int k=rec[s][0];
	int first=s;
	int l;
	while(first!=t && rec[first][0]!=0)
	{
		if(cap[first][rec[first][k]]<min)
			min=cap[first][rec[first][k]];
		tmp[tem]=rec[first][k];
		tem++;
		l=first;
		first=rec[first][k];
		k=rec[first][0];
	}
	if(first==t)
	{
		for(int i=0;i<tem-2;i++)
		{
			cap[tmp[i+1]][tmp[i+2]]-=min;
			if(cap[tmp[i+1]][tmp[i+2]]==0)
				rec[tmp[i+1]][0]--;
		}
		summary+=min;
	}
	else
		rec[l][0]--; //去除无用边,以便进行循环	
	return summary;
}

bool judge()
{
	int i=s;
	while(1)
	{
		if(rec[i][0]==0)
			return 0;
		if(rec[i][1]==t)
			return 1;
		i=rec[i][1];
	}
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值