繁体   English   中英

Bellman-Ford算法中的堆栈溢出和分段错误11

[英]Stack Overflow and Segmentation Fault 11 in Bellman-Ford's Algorithm

我正在用C ++实现Bellman-Ford算法,以发现货币兑换问题中的负权重周期,当我放置一个测试用例时,它给出了

Segmentation Fault: 11

这是代码:

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
struct edge
{
    int vertex;
    double weight;
};
int mindist(int A[],bool B[],int n)
{
    int v=0;
    while(B[v]==true)
        v++;
    for(int i=v;i<n;i++)
    {
        if(B[i]==false)
            if(A[i]<A[v])
                v=i;
    }
    return v;
}
class Graph
{
public:
    vector<edge> adj;

    void add(int a,int b)
    {
        edge e;
        e.vertex=a;
        e.weight=b;
        adj.push_back(e);
    }
};
int main()
{
    int n,m,u,v,j,isCycle=0;
    double w;
    edge temp;
    cin>>n>>m;
    Graph* G=new Graph[n];
    for(int i=0;i<m;i++)
    {
        cin>>u>>v>>w;
        w=-log(w);
        G[u-1].add(v-1,w);
    }
    int* dist=new int[n];
    bool* done = new bool[n];
    for(int i=0;i<n;i++)
    {
        dist[i]= 10000;
        done[i]=false;
    }
    dist[0]=0;
    for(int i=0;i<n;i++)
    {
        j=mindist(dist,done,n);
        done[j]=true;
        for(int i=0;i<G[j].adj.size();i++)
        {
            temp=G[j].adj[i];
            if(dist[temp.vertex]>temp.weight+dist[j])
                dist[temp.vertex]=temp.weight+dist[j];
        }
    }
    for(int i=0;i<n;i++)
    {
            temp=G[i].adj[i];
            if(dist[temp.vertex]>temp.weight+dist[i])
            {
                isCycle=1;
                break;
            }
    }
    cout<<isCycle;
}

测试用例:(格式:-FirstVertex SecondVertex权重)

//注意下面是有向图

10 9
1 2 1
6 7 1
8 9 1
9 10 1
3 4 1
7 8 1
4 5 1
5 6 1
2 3 1

我已经使用动态分配初始化了堆上的所有静态数组,但是仍然遇到相同的错误。 谁能告诉我我哪里出问题了?

考虑当B全部为真时会发生什么。

然后这个循环:

while(B[v]==true)
    v++;

具有不确定的行为,您很可能以“在那儿”的v结尾。
然后,将v返回到以下代码:

j=mindist(dist,done,n);
done[j]=true;
for(int i=0;i<G[j].adj.size();i++)

这将写在外层空间和外观的某处Graph不存在。

检查界限。

另外,在该部分的两个嵌套循环中使用i看起来很麻烦。
即使您要使用它,也可以重命名其中之一,这样看起来就不会错。

分段错误位于第70行,因此在G [i] .adj [i]中,adj [i]不存在。 每个adj [i]的大小均为1。第57行的循环也是错误的,因为您也在嵌套循环中使用了i。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM