【问题标题】:Got runtime error while using BFS algorithm使用 BFS 算法时出现运行时错误
【发布时间】:2020-06-24 14:51:11
【问题描述】:

m 个航班连接了 n 个城市。每个航班从城市 u 出发,到达 v,价格为 w。

现在给定所有城市和航班,连同起始城市 src 和目的地 dst,您的任务是找到从 src 到 dst 最多 k 个停靠点的最便宜的价格。如果没有这样的路由,输出-1。

例如:

示例 1:

输入:

n = 3, 

edges = [[0,1,100],[1,2,100],[0,2,500]]


src = 0, dst = 2, k = 1

输出:200 解释: 图表如下所示:

这是我的代码:

class Solution {
public:
    int ans=INT_MAX;
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
        vector<vector<vector<int>>>g;
        for(auto f:flights)
        {
            int from=f[0];
            int to=f[1];
            int cost=f[2];
            g[from].push_back({to,cost});
        }
        queue<vector<int>>q;
        q.push({src,0,-1});
        while(!q.empty())
        {
             vector<int>curr=q.front();
            q.pop();
            int currCity=curr[0];
            int currCost=curr[1];
            int currK=curr[2];
            
            if(currCity == dst)
            {
                ans=min(currCost,ans);
                continue;
            }
            for(auto x:g[currCity])
            {
                if(currK+1<=K && currCost+x[1]<ans)
                {
                    q.push({x[0],currCost+x[1],currK+1});
                }
            }
            
        }
        if(ans == INT_MAX)
        {
            return -1;
        }
        return ans;
    }
};

我曾经使用过 BFS 算法。

但是我得到了以下错误:

第 924 行:字符 9:运行时错误:引用绑定到类型为 'std::vector<:vector std::allocator>, std::allocator<:vector> > >' (stl_vector.h) 摘要:UndefinedBehaviorSanitizer:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h :933:9

我无法找出哪里出错了。

谢谢。

【问题讨论】:

  • g[from].push_back({to,cost}); 是 UB,因为 gempty()。可能还有更多问题。

标签: c++ data-structures graph breadth-first-search


【解决方案1】:

查看这段代码:

        vector<vector<vector<int>>>g;
        for(auto f:flights)
        {
            int from=f[0];
            int to=f[1];
            int cost=f[2];
            g[from].push_back({to,cost});
        }

最初g 是一个空向量。您使用它做的第一件事是访问不存在的元素:g[from]

你的意思可能是:

vector<vector<vector<int>>>g(n);

在这里,您创建一个第一个维度正确初始化的 3D 矢量。

其他注意事项:在不需要的地方使用向量。您在不检查实际大小的情况下使用已知固定数量的元素这一事实意味着该向量被滥用:

            int from=f[0];
            int to=f[1];
            int cost=f[2];

尽量使用结构体、元组等来避免这种情况。结构体更合适,因为你甚至知道每个元素的作用:fromtocost

这段代码效率很低:

for(auto x:g[currCity])
    ...

只要 g 是 3D 向量,auto x 就会成为每个 2D 元素的完整副本。试试看:for(const auto &amp;x:g[currCity])

【讨论】:

    【解决方案2】:
    vector<vector<vector<int>>>g; should be `vector<vector<vector<int>>>g(n);` 
    

    其中 n 可以是任意数字。因为您试图获取特定的索引。你必须初始化你的向量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      相关资源
      最近更新 更多