【问题标题】:Error in finding shortest path of a graph查找图的最短路径时出错
【发布时间】:2016-05-08 03:57:21
【问题描述】:

我已经编写了代码来输出两个节点之间的最短路径
输入格式-第一行包含两个数字,表示节点 ,
第二行包含 2 个数字,其中必须计算最短路径,然后沿线数跟随


我的代码输入的边数多于边数
例如-

7 9
0 6
0 1 1
0 2 1
0 3 2
0 4 3
1 5 2
2 6 4
3 6 2
4 6 4
5 6 1
代码需要 13 个输入,我找不到错误

代码

#include<iostream>
#include<cstring>
#include<vector> 
#include<queue>
typedef pair <long long int ,long long int> p;
vector<p> adj[100000];
vector<int> ver[100000];
void dijkstra(long long int x,long long int b);
int main()
  {
  long long nodes,t,edges,x,y,weight,a,b;
    cin>>nodes>>edges;
    cin>>a>>b;
    for(long long int i=1;i<=edges;i++)
      {
      cin>>x>>y>>weight;    
      adj[x].push_back(make_pair(weight,y));
      } 
    dijkstra(a,b);
  return 0;
}

void dijkstra(long long int a,long long int b)
  {
  priority_queue< p,vector<p>,greater <p> > q;
  long long int cost[100000];
  memset(cost,1000000,sizeof(cost));
  q.push(make_pair(0,a));
  cost[a]=0;
  while(!q.empty())
   {
      p pi=q.top();  
      q.pop();
     long long int u=pi.second;   //vertex
      long long int v=pi.first;    //weight
      if(cost[u]<v)  
      continue;      
      for(long long int i=0;i<adj[u].size();i++)
      {
       long long int w=adj[u][i].first;   //edge weight
       long long int x=adj[u][i].second; //vertex

        if(cost[x]>cost[u]+w)
          {
              ver[u].clear();
              ver[u].push_back(x);//prevcost[x]=cost[x];    
              cost[x]=cost[u]+w;
              q.push(p(cost[x],x)); 

          }
          if(cost[x]=cost[u]+w)
          ver[u].push_back(x);
      }
    }

  for(long long int i=0;i<ver[b].size();i++)
  cout<<ver[b][i]<<"->";
  cout<<"\n";
 }  

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。

标签: c++ algorithm dijkstra


【解决方案1】:

这是您的代码的精简版本,仅接受来自终端的输入。不要将值存储在向量中或调用 dijkstra 函数。 它只根据需要输入 9 个边......

#include<iostream>
#include<cstring>
#include<vector>
#include<queue>
//typedef pair <long long int ,long long int> p;
///vector<p> adj[100000];
//vector<int> ver[100000];
//void dijkstra(long long int x,long long int b);
using namespace std;
int main()
  {
    long long nodes,t,edges,x,y,weight,a,b;
    cin>>nodes>>edges;
    cin>>a>>b;
    cout<<"nodes "<<nodes<<"edges "<<edges<<endl;
    for(long long int i=1;i<=edges;i++)
      {
      cin>>x>>y>>weight;

      //adj[x].push_back(make_pair(weight,y));
      }
    //dijkstra(a,b);
  return 0;
}

请检查您通过终端输入数据的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多