【发布时间】:2019-05-12 00:41:21
【问题描述】:
我一直在为要解决的特定问题实施 dijkstra 算法。
我的问题是当我减小v--; u--; 的值时,程序会自动结束。不知道有没有溢出或者什么特别的。
当我删除值 v--; or--; 的行时,程序运行良好但没有给我正确答案,因为我需要减少这两个值。
如果您能帮我找到问题,我将不胜感激
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define forn(i , a , b) for(int i=(a);i<(b);i++)
int const N = 1001;
int const M = numeric_limits<int>::max();
bool visited[N];
vector<int> cost(N);
vector<vector<pair<int, int>>> g;
priority_queue<pair<int, int>> q;
void dijkstra(int src) {
cost[src] = 0;
q.push(make_pair(0, src));
while(!q.empty()){
int v = q.top().second;
int c = -q.top().first;
q.pop();
if(visited[v]) continue;
visited[v] = true;
forn(i , 0 , (int)g[v].size()){
if(g[v][i].second + c < cost[g[v][i].first]) {
cost[g[v][i].first] = g[v][i].second + c;
q.push(make_pair(-(g[v][i].second + c), g[v][i].first));
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cout << fixed;
#ifdef LOCAL_DEFINE
freopen("input.txt" , "rt" , stdin);
#endif
int n; cin >> n;
int m; cin >> m;
g.resize(n);
while(!q.empty()) q.pop();
forn(i , 0 , n) cost[i] = M;
memset(visited , false , sizeof visited);
while(m--){
string s; cin >> s;
int v; cin >> v;
int u; cin >> u;
int w; cin >> w;
v--; u--;
g[v].push_back(make_pair(u , w));
}
int t; cin >> t;
while(t--){
int v; cin >> v;
int u; cin >> u;
v--; u--;
dijkstra(v);
if(cost[u] == M) cout << "Unreachable" << endl;
else cout << cost[u] << endl;
}
#ifdef LOCAL_DEFINE
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
return 0;
}
测试用例
5 3
a 0 4 8
b 0 4 8
c 2 3 1
4
0 1
0 4
2 4
1 4
这是我的结果,当我删除 v--; 的行时u--;
Unreacheble
8
8
8
预期输出
Unreachable
8
13
Unreachable
【问题讨论】:
-
你调试了吗?
-
不是真的,但是当我删除值 v-- 和 u-- 时程序运行良好;但我不能消除它们,因为这是必要的。
-
在向我们寻求免费帮助解决您的问题之前,您应该已经完成了调试。带着你从那个过程中得到的结果回来
-
当我从代码中删除 v-- 和 u-- 时,我刚刚添加了我的输出。
-
我注意到您昨天在关闭的其他问题中也被告知了这一点,但没有听从这个建议
标签: c++ algorithm graph dijkstra discrete-mathematics