Pagini recente » Cod sursa (job #1481635) | Cod sursa (job #1213471) | Cod sursa (job #833305) | Cod sursa (job #425028) | Cod sursa (job #3243725)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMax = 50005;
const int inf = 0x3f3f3f3f;
int n, m;
int D[NMax];
bool inQueue[NMax];
vector<pair<int, int>> G[NMax];
struct compareDist {
bool operator() (int x, int y) {
return D[x] > D[y];
}
};
priority_queue< int, vector<int>, compareDist> q;
void read() {
fin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y, cost;
fin >> x >> y >> cost;
G[x].push_back(make_pair(y, cost));
}
}
void Dijkstra(int startNode) {
for (int i = 1; i <= n; ++i) {
D[i] = inf;
}
D[startNode] = 0;
q.push(startNode);
inQueue[startNode] = true;
while (!q.empty()) {
int currNode = q.top();
q.pop();
inQueue[currNode] = false;
for (int i = 0; i < G[currNode].size(); ++i) {
int neighbor = G[currNode][i].first;
int cost = G[currNode][i].second;
if (D[currNode] + cost < D[neighbor]) {
D[neighbor] = D[currNode] + cost;
if (!inQueue[neighbor]) {
q.push(neighbor);
inQueue[neighbor] = true;
}
}
}
}
}
void print() {
for (int i = 2; i <= n; ++i) {
if (D[i] != inf) {
fout << D[i] << ' ';
} else {
fout << "0 ";
}
}
}
int main() {
read();
Dijkstra(1);
print();
return 0;
}