我的Dijkstra算法实现中的无限循环

时间:2014-08-31 03:00:02

标签: c++ dijkstra

我正在为在线评审编程竞赛编写一个程序。这是一个简单的dijkstra最短路径问题,但我在这里面临一个非常奇怪的问题。

在我读取输入(注释为#PROBLEM)之后,CPU使用get为100%并且程序没有做任何其他事情:既不接受新输入也不显示任何输出。有点奇怪的是,如果我在我的dijkstra()旁边注释掉cin函数调用,则问题无法再次重现。

我正在考虑UB,但实际上找不到问题所在的位置。

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define INF 100001
#define vi vector<int>
#define ii pair<int, int>
#define vii vector<ii>

struct orderByCost {
 bool operator() (ii a, ii b) { return a.second > b.second; }
};

int dijkstra(const vector<vii> &adj, int start, int target) {
    vector<bool> visited(adj.size());
    priority_queue<ii, vector<ii>, orderByCost> pq;
    pq.push(ii(start, 0));
    vi costsTable(adj.size(), INF);
    while (!pq.empty()) {
        ii node = pq.top(); pq.pop();
        if (visited[node.first]) {
            continue;
        }
        visited[start] = true;
        for (int i = 0; i < adj[node.first].size(); i++)
        {
            ii neighbor = adj[node.first][i];
            if (!visited[neighbor.first]) {
                pq.push(neighbor);
            }
            if (costsTable[neighbor.first] == INF) {
                costsTable[neighbor.first] = neighbor.second;
            } else if (neighbor.second + costsTable[node.first] < costsTable[neighbor.first]) {
                costsTable[neighbor.first] += costsTable[node.first];
            }
        }
    }

    return costsTable[target];
}

int main(int argc, char *argv[]) {
    int n, e;
    while (true) {
        cin >> n >> e;
        if (n == e && e == 0) break;
        vector<vii> adj(n);
        for(int i = 0; i < e; i++)    {
            int a, b, w;
            cin >> a >> b >> w;
            a--; b--;
            adj[a].push_back(ii(b, w));
        }
        int cases;
        cin >> cases;
        for(int i = 0; i < cases; i++) {
            int a, b;
            cin >> a >> b; // #PROBLEM: this is the input that causes weird behavior
            a--; b--;
            int result = dijkstra(adj, a, b); // #PROBLEM: if I comment this line out, the following line WILL get printed. If not, CPU use get's 100% and just hangs
            cout << "This line isn't being printed\n";
            result > 0 ? cout << result << '\n' : cout << "Not possible\n";
        }
    }
}

示例输入(注意:#开头的行是我为您的理解所做的评论,它们不是输入的一部分):

4 5 # 4 nodes with 5 edges
1 2 5 # edge from node 1 to node 2 with cost of 5
2 1 10
3 4 8
4 3 7
2 3 6
5 # test cases
1 2 # cost from path 1 to 2. Here is where the input hangs
1 3
1 4
4 3
4 1
3 3

读取输入后我的CPU使用情况: enter image description here

1 个答案:

答案 0 :(得分:4)

您可能想要更改

visited[start] = true;

visited[node.first] = true;

否则只有start节点被标记为已访问。