您的位置:首页 > 理论基础 > 计算机网络

NBU 2430 war of energy

2016-07-01 23:42 417 查看

NBU 2430 war of energy

题目:

Description

This is a war, we need energy.As the person in charge of the Energy Agency, you need to know the quantity of energy transmission around.

Suppose there are n cities, and then the m pipelines, each pipeline to connect the two cities, for geographical reasons, the pipeline flow. Ask how many units of energy from the city ato the city b, and can transport up to.

Input

The input includes several cases. For each case, the first line contains two space-separated integers, N (0 < = N < = 200) and M (2 < = M < = 40000). N is the number of city. M is the number of pipeline.

Each of the following M lines contains three integers, Si, Ei, and Ci. Si and Ei (1 <= Si, Ei <= N) Energy will flow through this pipeline from Si to Ei. Ci (0 <= Ci <= 100000) is the maximum rate at which Energy will flow through the pipeline

Output

Output maximum flow from city 1 to city n.

Sample Input

4 5

1 2 40

1 4 20

2 4 20

2 3 30

3 4 10

Sample Output

50

题意:

输入N,M分别为结点数和边数,

接下来会输入M行,分别为a,b,c,表示结点a和结点b之间有边且边的流量为c,

求结点1到结点N的最大流量。

思路:

这是一个典型的最大流问题,先对样例进行分析,根据样例画出来的图如下:



图片有点丑。。但是对于解题没有影响,从图中我们可以看出1到4的路有好多条,比如1-4,1-2-4,1-2-3-4,接着我们来模拟增广路算法,一开始最大流为0,找到1-4这条通路,在这条路上最大可以流过20个单位的水流,所以最大流加上20,再看1-2-4,这条路上最大可以流过20个单位,所以再加上20,最后看1-2-3-4,最大可流10单位,所以最大流再加上10,所以最后最大流为50。

由于这个题目数据不是很大,所以我们只需要用个增广路算法就可以求得最大流。

代码:

#include<iostream>
#include<queue>
using namespace std;
#define MAXN 210
#define INF 0x7FFFFFFF
int n,m,map[MAXN][MAXN],path[MAXN],flow[MAXN],start,end;
queue<int>q;
int BFS(){
int i,t;
while(!q.empty()){
q.pop();
}
memset(path,-1,sizeof(path));
path[start]=0;
flow[start]=INF;
q.push(start);
while(!q.empty()){
t=q.front();
q.pop();
for(i=1;i<=n;i++){
if(i!=start&&path[i]==-1&&map[t][i]){
flow[i]=flow[t]<map[t][i]?flow[t]:map[t][i];
q.push(i);
path[i]=t;
}
}
}
if(path[end]==-1){
return -1;
}
return flow
;
}
int EK(){
int max_flow=0,step,now,before;
while((step=BFS())!=-1){
max_flow+=step;
now=end;
while(now!=start){
before=path[now];
map[before][now]-=step;
map[now][before]+=step;
now=before;
}
}
return max_flow;
}
int main(){
int i,x,y,val;
while(~scanf("%d%d",&n,&m)){
memset(map,0,sizeof(map));
for(i=0;i<m;i++){
scanf("%d%d%d",&x,&y,&val);
map[x][y]+=val;
}
start=1;
end=n;
printf("%d\n",EK());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络流 NBU