Dijkstra算法实现的性能

zoo*_*zoo 6 c++ performance implementation dijkstra

下面是我从维基百科文章中的伪代码编写的Dijkstra算法的实现.对于具有大约40 000个节点和80 000个边缘的图形,运行需要3或4分钟.那是不是正确的数量级?如果没有,我的实施有什么问题?

struct DijkstraVertex {
  int index;
  vector<int> adj;
  vector<double> weights;
  double dist;
  int prev;
  bool opt;
  DijkstraVertex(int vertexIndex, vector<int> adjacentVertices, vector<double> edgeWeights) {
    index = vertexIndex;
    adj = adjacentVertices;
    weights = edgeWeights;
    dist = numeric_limits<double>::infinity();
    prev = -1; // "undefined" node
    opt = false; // unoptimized node
   }
};

void dijsktra(vector<DijkstraVertex*> graph, int source, vector<double> &dist, vector<int> &prev) {
  vector<DijkstraVertex*> Q(G); // set of unoptimized nodes
  G[source]->dist = 0;
  while (!Q.empty()) {
    sort(Q.begin(), Q.end(), dijkstraDistComp); // sort nodes in Q by dist from source
    DijkstraVertex* u = Q.front(); // u = node in Q with lowest dist
    u->opt = true;
    Q.erase(Q.begin());
    if (u->dist == numeric_limits<double>::infinity()) {
      break; // all remaining vertices are inaccessible from the source
    }
    for (int i = 0; i < (signed)u->adj.size(); i++) { // for each neighbour of u not in Q
    DijkstraVertex* v = G[u->adj[i]];
    if (!v->opt) {
      double alt = u->dist + u->weights[i];
      if (alt < v->dist) {
        v->dist = alt;
        v->prev = u->index;
      }
    }
    }
  }
  for (int i = 0; i < (signed)G.size(); i++) {
    assert(G[i] != NULL);
    dist.push_back(G[i]->dist); // transfer data to dist for output
    prev.push_back(G[i]->prev); // transfer data to prev for output
  }  
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以通过以下方式改进:

  • 使用sort和erase实现优先级队列会增加| E |的因子 到运行时 - 使用STL 的堆函数来获取日志(N)插入和删除队列.
  • 不要把所有的节点在队列中一次,但只有那些你已经发现了一个路径(这可能是也可能不是最优的,因为你可以找到在队列中通过节点的间接路径).
  • 为每个节点创建对象会产生不必要的内存碎片.如果你关心挤出最后的5-10%,你可以考虑一个解决方案,直接表示关联矩阵和其他信息作为数组.