Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- std::vector<int> getMinPathFromTo(const std::vector<std::map<int, uint64_t>>& adjacencyList, int from, int to) {
- const uint64_t INF = UINT64_MAX;
- std::vector<uint64_t> distance(adjacencyList.size(), INF);
- distance[from] = 0;
- std::set<std::pair<uint64_t, int>> queue;
- queue.emplace(distance[0], 0);
- std::vector<int> ancestor(adjacencyList.size(), -1);
- while (!queue.empty()) {
- auto vertexWithMinDistance = *queue.begin();
- auto current = vertexWithMinDistance.second;
- auto distanceToCurrent = vertexWithMinDistance.first;
- queue.erase(queue.begin());
- for (const auto& neighboor : adjacencyList[current]) {
- if (distance[neighboor.first] > distanceToCurrent + neighboor.second) {
- auto vertex = std::make_pair(distance[neighboor.first], neighboor.first);
- auto it = queue.find(vertex);
- if (it != queue.end()) {
- queue.erase(it);
- }
- distance[neighboor.first] = distanceToCurrent + neighboor.second;
- queue.insert(std::make_pair(distance[neighboor.first], neighboor.first));
- ancestor[neighboor.first] = current;
- }
- }
- }
- if (INF == distance[to]) {
- return {};
- }
- std::vector<int> path;
- for (int current = to; current != from; current = ancestor[current]) {
- path.push_back(current);
- }
- path.push_back(from);
- std::reverse(path.begin(), path.end());
- return path;
- }
Add Comment
Please, Sign In to add comment