【问题标题】:Problems in running the dijkstra algorithm运行dijkstra算法的问题
【发布时间】: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


【解决方案1】:

仔细查看while(m--) {...} 循环中发生的情况。当您从输入中读取a 0 4 8 行时,v 设置为零。然后,在 while 循环中,通过将 v-- 设置为负一来减小 v 的值。在此之后,您尝试在此行中访问g[v] = g[-1]g[v].push_back(make_pair(u , w));,这会导致运行时错误,因为您无法使用负索引访问向量的元素。

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 2014-06-20
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多