Pagini recente » Cod sursa (job #1413618) | Cod sursa (job #2220026) | Cod sursa (job #2337068) | Cod sursa (job #754545) | Cod sursa (job #2801982)
#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;
typedef pair<int, int> my_pair;
priority_queue<my_pair, vector <my_pair> , greater<my_pair> > 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;
}