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

codevs1993 草地排水

2015-06-30 21:08 676 查看
题目描述                   在农夫约翰的农场上,每逢下雨,Bessie最喜欢的三叶草地就积聚了一潭水。这意味着草地被水淹没了,并且小草要继续生长还要花相当长一段时间。因此,农夫约翰修建了一套排水系统来使贝茜的草地免除被大水淹没的烦恼(不用担心,雨水会流向附近的一条小溪)。作为一名一流的技师,农夫约翰已经在每条排水沟的一端安上了控制器,这样他可以控制流入排水沟的水流量。
农夫约翰知道每一条排水沟每分钟可以流过的水量,和排水系统的准确布局(起点为水潭而终点为小溪的一张网)。需要注意的是,有些时候从一处到另一处不只有一条排水沟。
根据这些信息,计算从水潭排水到小溪的最大流量。对于给出的每条排水沟,雨水只能沿着一个方向流动,注意可能会出现雨水环形流动的情形。
输入描述               第1行: 两个用空格分开的整数N (0 <= N <= 200) 和 M (2 <= M <= 200)。N是农夫John已经挖好的排水沟的数量,M是排水沟交叉点的数量。交点1是水潭,交点M是小溪。
第二行到第N+1行: 每行有三个整数,Si, Ei, 和 Ci。Si 和 Ei (1 <= Si, Ei <= M) 指明排水沟两端的交点,雨水从Si 流向Ei。Ci (0 <= Ci <= 10,000,000)是这条排水沟的最大容量。
输出描述               输出一个整数,即排水的最大流量。
样例输入              
5 4
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10
样例输出 Sample Output50

由于数据弱,用没有优化的EK就可以过去了。
通过这个题,我弄明白了“建立反向边”的作用。之前看其他资料说“建立反向边就是给程序反悔的机会”,但始终不得要领。通过这个题,终于将其弄明白。
如这组数据:
7 6
1 2 10000
2 3 10000
3 6 10000
1 4 8000
4 3 8000
2 5 6000
5 6 6000
如图所示:


如果直接执行bfs后选择的可增广路有可能是1,2,3,6,如果没有反向边,那么就会将1,2,3,6的容量直接减为0,然后就得到了答案10000.但是实际上答案是16000,这就是退流的作用。那么,16000的流量从1开始,8000:1,4,3,6;2000:1,2,3,6;6000:1,2,5,6.所以第一次选择1,2,3,6之后,建立反向边后如图:



如此就可以再反向边上进行退流,即“给程序反悔的机会”。

如此,执行没有任何优化的EK这个题就可以过了。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;

struct ForwardStar
{
int u, v, c;
int next;
} graphic[1000];
int n, m;
int point[1000];
int path[1000];
queue<int> q;

bool Spfa(int s, int v)
{
int dis[1000];
bool y[1000], yy = false;
int h, i, j;
memset(dis, 0x7f, sizeof(dis));
memset(y, 0, sizeof(y));
memset(path, 0, sizeof(path));
q.push(s);
dis[s] = 0;
y[s] = true;
while (!q.empty())
{
h = q.front();
q.pop();
if (h == v)
{
yy = true;
break;
}
i = point[h];
while (i != 0)
{
if ((dis[graphic[i].v] > dis[h] + 1) && (graphic[i].c > 0))
{
dis[graphic[i].v] = dis[h] + 1;
if (y[graphic[i].v] != true)
{
q.push(graphic[i].v);
y[graphic[i].v] = true;
}
path[graphic[i].v] = i;
}
i = graphic[i].next;
}
y[h] = true;
}
while (!q.empty()) q.pop();
return yy;
}

int Ek(int s, int v)
{
int maxFlow = 0, i;
int e = 0x7fffffff;
while (Spfa(s, v))
{
i = v;
e = 0x7fffffff;
while (i != s)
{
i = path[i];
e = min(e, graphic[i].c);
i = graphic[i].u;
}
i = v;
while (i != s)
{
i = path[i];
graphic[i].c -= e;
if (graphic[i].u == graphic[i + 1].u && graphic[i].v == graphic[i + 1].v) graphic[i + 1].c += e;
else graphic[i - 1].c += e;
i = graphic[i].u;
}
maxFlow += e;
}
return maxFlow;
}

int main()
{
cin >> m >> n;
int a, b, c, d = 0;
for (int i = 1; i <= m; i++)
{
cin >> a >> b >> c;
d++;
graphic[d].u = a;
graphic[d].v = b;
graphic[d].c = c;
if (point[a] == 0)
{
point[a] = d;
path[a] = d;
}
else
{
graphic[path[a]].next = d;
path[a] = d;
}
d++;
graphic[d].u = b;
graphic[d].v = a;
graphic[d].c = 0;
if (point[b] == 0)
{
point[b] = d;
path[b] = d;
}
else
{
graphic[path[b]].next = d;
path[b] = d;
}
}
memset(path, 0, sizeof(path));
cout << Ek(1, n) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codevs 网络流