gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:03:23 25 4
gpt4 key购买 nike

<分区>

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

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

我正在考虑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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com