《数据结构与算法分析——C语言描述》 第九章 图论算法
graph里面增加一个函数
void setWeight(double weight, EdgeNodePtr p) {
if (p) {
p->weight = weight;
}
}
深度搜索、简单的最大流
Vertex startVex, endVex;//起点,终点
Graph gr;//残余图
Graph gf;//流图
double minWeight;//一条路径的最小权
bool dfs(Vertex v,double prevMin) {//prevMin是用于在其中一条路径中搜索失败的时候恢复状态用的(没有这个变量只有最小值的话可能在后面寻找失败的路径中更改了最小值)
if (v == endVex) {
minWeight = prevMin;
return true;
}
for (EdgeNodePtr p = getEdgeNodePtr(v, gr); p;p=advance(p)) {
if (getWeight(p) == 0)
continue;
double nextMin;
if (prevMin < getWeight(p))
nextMin = prevMin;
else
nextMin = getWeight(p);
if (dfs(getVex(p),nextMin)) {
//成功到达终点后的归
Vertex w = getVex(p);
double weight = getWeight(p);
double newWeight = weight - minWeight;
setWeight(newWeight, p);
insertEdge(v, w, minWeight,gf);
return true;
}
p = advance(p);
}
return false;
}
int main() {
freopen("filein.txt", "r", stdin);
gr = readGraph();
gf = initialize_Graph(5);
for (int i = 0, tag1 = 1, tag2 = 1; (tag1 || tag2) && i < vexNum; i++) {
if (tag1&&indegree(i, gr) == 0) {
startVex = i;
tag1 = 0;
}
if (tag2 && getEdgeNodePtr(i, gr) == NULL) {
endVex = i;
tag2 = 0;
}
}
double sum = 0;
while (dfs(startVex, DBL_MAX))
sum += minWeight;
printf("Maximum Flow:%g\n", sum);
printGraph(gf);
}