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];
}
}

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

747

被折叠的 条评论
为什么被折叠?



