【问题标题】:maxflow algorithm return zero as resultmaxflow 算法返回零作为结果
【发布时间】:2011-11-04 11:33:06
【问题描述】:

以下代码返回零作为输出,请告诉我有什么问题?

#include<iostream>
#define MAX 100
using namespace std;
int graph[MAX][MAX];
int queue[MAX];
int head,tail;
int parent[MAX];
int V,E;
int s,t,fTotal;
int F[MAX][MAX];

//breadth First search
bool reachable(int s,int  t){
    bool found=false;
    head=tail=0;
    int vq;
    memset(parent,255,sizeof(parent));
    queue[tail++]=s;
    parent[s]=s;
    while(head< tail && ! found){
        vq=queue[head++];
        for(int i=0;i<V;i++){
            //Parents also made the function as visit vector
            if(graph[vq][i] && parent[i]==-1)
                queue[tail++]=i;
            parent[i]=vq;
            if(i==t){
                found=true;
                break;
            }
        }
    }
    return found;
}

void maxflow(){
    int vj,min;
    fTotal=0;
    while(reachable(s,t)){
        //Gets the minimum possible capacity in edges of the path s to t
        min=graph[parent[t]][t];
        vj=t;
        while(parent[vj]!=vj){
            if(graph[parent[vj]][vj]<min)
                min=graph[parent[vj]][vj];
            vj=parent[vj];
        }

        vj=t;
        while(parent[vj]!=vj){

            graph[parent[vj]][vj]-=min;
            graph[vj][parent[vj]]+=min;
            F[parent[vj]][vj]+=min;
            vj=parent[vj];
        }
        fTotal+=min;
    }
}

bool read(){
    cin>>V>>E>>s>>t;
    if(!V && !E) return false;
    memset(graph,0,sizeof(graph));
    memset(queue,0,sizeof(queue));
    memset(F,0,sizeof(F));
    int v1,v2,val;
    for(int i=0;i<E;i++){
        cin>>v1>>v2>>val;
        graph[v1][v2]=val;
    }
    return true;
}

int  main(){
    while(read()){
        maxflow();
        cout<<" max flow from s to t is : "<<fTotal<<endl;
    }
    return 0;
}

在输入之后,我输入了 6 个节点和 8 个边,源 1 和汇顶点 6。

 (1,2)        2
   (1,3)        3
   (2,4)        3
   (3,4)        1
   (2,5)        1
   (3,5)        1
   (4,6)        2
   (5,6)        3

【问题讨论】:

  • 如果这纯粹是一个编程问题,它属于堆栈溢出。我不清楚这与统计数据有什么关系。请参阅FAQ 了解本网站上的适当问题。
  • 任何帮助?我已经展示了一切

标签: graph-theory c++


【解决方案1】:

您的reachable() 函数不是广度优先搜索。例如,查看this pseudo-code 并将其与您的进行比较。你一直做得很好,直到“为每个边缘”部分,你改为“为每个节点”做一个,它只是从那里分崩离析。

您还混淆了基于 0 的索引和基于 1 的索引:您输入基于 1 的索引,但在 reachable() 中,循环 for(int i=0;i&lt;V;i++) 是基于 0 的。选择一个系统并保持一致。

此代码还有许多其他潜在问题,一旦您修复reachable(),这些问题将导致更多问题。我建议您访问CodeReview 网站以获得进一步的反馈。

【讨论】:

    猜你喜欢
    • 2015-07-13
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2017-10-30
    相关资源
    最近更新 更多