Pagini recente » Cod sursa (job #391844) | Cod sursa (job #1393338) | Cod sursa (job #1961073) | Cod sursa (job #1675732) | Cod sursa (job #2959754)
#include <fstream>
#include <vector>
#include <queue>
#include <tuple>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int Inf = 0x3f3f3f3f;
using VI = vector<int>;
using PI = pair<int, int>;
using VP = vector<PI>;
using VVP = vector<VP>;
int n, m;
VVP G; // graful
VI D; //dist
void ReadData();
void Dijkstra(int x, VI& D);
void WriteDistances();
int main(){
ReadData();
Dijkstra(1, D);
WriteDistances();
return 0;
}
void Dijkstra(int x, VI& D){
priority_queue<PI, vector<PI>, greater<PI>> Q; // min-heap
D[x] = 0;
Q.emplace(0, x);
int dx, y, w;
while (!Q.empty()){
tie(dx, x) = Q.top();
Q.pop();
if (dx > D[x]) continue;
for (auto pair : G[x]){
tie(y, w) = pair;
if (D[y] > D[x] + w){
D[y] = D[x] + w;
Q.emplace(D[y], y);
}
}
}
}
void WriteDistances(){
for (int i = 2; i <= n; ++i)
fout << D[i] << ' ';
}
void ReadData(){
fin >> n >> m;
G = VVP(n + 1);
D = VI(n + 1, Inf);
int x, y, w;
while (m--){
fin >> x >> y >> w;
G[x].emplace_back(y, w);
}
}