| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 54766 | Accepted: 20880 |
Description
Input
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
哈哈,第一道网络流!!!
模板一次敲对,基础理解差不多了吧!
在代码中解释一下吧!
本来就只有Edmonds-karp算法,现在补上Dinic算法。
AC代码如下:
Edmonds-karp算法如下:
#include<iostream>
#include<cstring>
#include<queue>
#define inf 100000000
using namespace std;
int n,m;
int map[205][205],p[205];//map存网络图,p[]记录下标的流的来源;
int f[205];//用于增广路的最大增流量统计
int bfs(int s,int e)
{
int i,j;
queue <int > q;
for(i=1;i<=n;i++)
{p[i]=-1;}
f[1]=inf;
int a,b;
q.push(s);
while(!q.empty())
{
b=q.front();
q.pop();
if(b==e)//找到终点
break;
for(i=2;i<=n;i++)
{
if(map[b][i]>0&&p[i]==-1)
{
p[i]=b;
f[i]=min(f[b],map[b][i]);
q.push(i);
}
}
}
if(p[e]==-1)//没有增广路了
return -1;
else return f[e];
}
int maxflow(int s,int e)
{
int i,j;
int in;
int ans=0;
in=bfs(s,e);//用BFS找增广路
while(in!=-1)
{
int k=e;
while(k!=s)
{
map[p[k]][k]-=in;//增减时满足正向和反向的转化关系
map[k][p[k]]+=in;
k=p[k];
}
ans+=in;//统计增流
in=bfs(s,e);
}
return ans;
}
int main()
{
int i,j;
int a,b,c;
while(cin>>m>>n)
{
memset(map , 0 , sizeof map );
for(i=1;i<=m;i++)
{
cin>>a>>b>>c;
map[a][b]+=c;//可能存在同等性质的流道,累加就行了
}
cout<<maxflow(1,n)<<endl;
}
return 0;
}
Dinic算法如下:
#include<iostream>
#include<cstring>
#include<queue>
#define inf 100000000
#define min(a,b) (a<b?a:b)
using namespace std;
int n,m;
int map[205][205],cs[205];
int bfs ()
{
int i,a,b;
queue <int > q;
memset(cs , -1 , sizeof cs);
cs[1]=0;
q.push(1);
while(!q.empty())
{
a=q.front ();
q.pop();
for(i=1;i<=n;i++)
{
if(cs[i]<0&&map[a][i]>0)
{
cs[i]=cs[a]+1;
q.push(i);
}
}
}
if(cs[n]==-1)
return 0;
else return 1;
}
int dfs(int x,int mf)
{
int i,j;
int a;
if(x==n)
return mf;
for(i=1;i<=n;i++)
{
if(cs[i]==cs[x]+1&&map[x][i]>0&&(a=dfs(i,min(mf,map[x][i]))))
{
map[x][i]-=a;
map[i][x]+=a;
return a;
}
}
return 0;
}
int main()
{
int i,j;
int a,b,c;
int sum;
while(cin>>m>>n)
{
memset(map,0,sizeof map);
for(i=1;i<=m;i++)
{
cin>>a>>b>>c;
map[a][b]+=c;
}
int ans=0;
while(bfs())//不断构建层次图
{
while(sum=dfs(1,inf))//搜索路径
ans+=sum;
}
cout<<ans<<endl;
}
return 0;
}
POJ 1273 Drainage Ditches,布布扣,bubuko.com
原文地址:http://blog.csdn.net/hanhai768/article/details/37692385