Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <functional>
- using namespace std;
- const int maxn = 1e5 + 5;
- const int INF = 2e9;
- int n, m;
- vector<pair<int, int>> graph[maxn];
- void dijkstra(int start_node, int end_node) {
- vector<bool> visited(n, false);
- vector<int> shortest_distance(n, INF);
- shortest_distance[start_node] = 0;
- priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
- pq.push({start_node ,0});
- while(!pq.empty()) {
- pair<int, int> p = pq.top();
- pq.pop();
- int current_node = p.first;
- int current_node_path = p.second;
- if(visited[current_node]) {
- continue;
- }
- if(current_node == end_node) {
- cout << current_node_path << endl;
- return;
- }
- visited[current_node] = true;
- for(pair<int, int> neighbour : graph[current_node]) {
- int neighbour_node = neighbour.first;
- int neighbour_weight = neighbour.second;
- if(!visited[neighbour_node] and current_node_path + neighbour_weight < shortest_distance[neighbour_node]) {
- pq.push({neighbour_node, current_node_path + neighbour_weight});
- shortest_distance[neighbour_node] = current_node_path + neighbour_weight;
- }
- }
- }
- }
- int main() {
- cin >> n >> m;
- for(int i = 0; i < m; i++) {
- int a, b, c;
- cin >> a >> b >> c;
- graph[a].push_back({b, c});
- graph[b].push_back({a, c});
- }
- dijkstra(0, 4);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment