Pagini recente » Cod sursa (job #2302792) | Cod sursa (job #594246) | Cod sursa (job #2932237) | Cod sursa (job #36112) | Cod sursa (job #2801977)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
void dijkstra(vector<vector<pair<int, int>>> &ad, int n, int s){
/// method to find Dijkstra's shortest path using
/// in the priority queue we store elements of pair
/// first -> cost from the start node to the current node
/// second -> node
const int INF = 0x3f3f3f3f;
priority_queue< pair<int, int>, vector <pair<int, int> > , greater<pair<int, int> > > pq;
vector<int> dist(n + 1, INF);
pq.push(make_pair(0, s)); /// the cost to reach start node is always 0
dist[s] = 0;
while (!pq.empty()){
int node = pq.top().second; /// node is the current node
pq.pop();
for(pair<int,int> v : ad[node]) /// iterate through all vertexes reachable from node
if (dist[v.first] > dist[node] + v.second){ /// if there is shorted path to v through node
dist[v.first] = dist[node] + v.second; /// update distance
pq.push(make_pair(dist[v.first], v.first));
}
}
for(int i = 2; i <= n; i++)
if(dist[i] == INF) fout << 0 << " ";
else fout << dist[i] << " ";
fout.close();
}
int main() {
int n, m, x, y, cost;
fin >> n >> m;
vector<vector<pair<int, int>>> ad(n + 1);
for (int i = 1; i <= m; ++i) {
fin >> x >> y >> cost;
ad[x].push_back({y, cost});
}
dijkstra(ad, n, 1);
return 0;
}