Guest User

Untitled

a guest
Nov 20th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. std::vector<int> getMinPathFromTo(const std::vector<std::map<int, uint64_t>>& adjacencyList, int from, int to) {
  2. const uint64_t INF = UINT64_MAX;
  3. std::vector<uint64_t> distance(adjacencyList.size(), INF);
  4. distance[from] = 0;
  5.  
  6. std::set<std::pair<uint64_t, int>> queue;
  7. queue.emplace(distance[0], 0);
  8.  
  9. std::vector<int> ancestor(adjacencyList.size(), -1);
  10. while (!queue.empty()) {
  11. auto vertexWithMinDistance = *queue.begin();
  12. auto current = vertexWithMinDistance.second;
  13. auto distanceToCurrent = vertexWithMinDistance.first;
  14. queue.erase(queue.begin());
  15.  
  16. for (const auto& neighboor : adjacencyList[current]) {
  17. if (distance[neighboor.first] > distanceToCurrent + neighboor.second) {
  18. auto vertex = std::make_pair(distance[neighboor.first], neighboor.first);
  19. auto it = queue.find(vertex);
  20. if (it != queue.end()) {
  21. queue.erase(it);
  22. }
  23. distance[neighboor.first] = distanceToCurrent + neighboor.second;
  24. queue.insert(std::make_pair(distance[neighboor.first], neighboor.first));
  25. ancestor[neighboor.first] = current;
  26. }
  27. }
  28. }
  29.  
  30. if (INF == distance[to]) {
  31. return {};
  32. }
  33.  
  34. std::vector<int> path;
  35. for (int current = to; current != from; current = ancestor[current]) {
  36. path.push_back(current);
  37. }
  38. path.push_back(from);
  39. std::reverse(path.begin(), path.end());
  40.  
  41. return path;
  42. }
Add Comment
Please, Sign In to add comment