Pagini recente » Cod sursa (job #77586) | Monitorul de evaluare | Cod sursa (job #768095) | Cod sursa (job #458413) | Cod sursa (job #3333295)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
int INF = INT_MAX / 2;
int main()
{
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m;
fin >> n >> m;
vector<vector<pair<int,int>>> adj(n+1);
// .first = nodul vecin
// .second = cost
for (int i = 0; i < m; i++) {
int a, b, c;
fin >> a >> b >> c;
adj[a].push_back({b, c});
}
vector<int> dist(n+1, INF);
dist[1] = 0;
priority_queue<
pair<int,int>, // .first==dist
vector<pair<int,int>>,
greater<pair<int,int>>> q;
q.push({dist[1], 1});
while (!q.empty()) {
int nod = q.top().second;
int d = q.top().first;
q.pop();
if (d != dist[nod])
continue;
for (auto p : adj[nod]) {
int v = p.first;
int c = p.second;
if (dist[nod] + c < dist[v]) {
// actualizare
dist[v] = dist[nod] + c;
q.push({dist[v], v});
}
}
}
for (int i = 2; i <= n; i++) {
if (dist[i] == INF)
fout << 0 << " ";
else
fout << dist[i] << " ";
}
fout << "\n";
return 0;
}