Pagini recente » Cod sursa (job #1841076) | Cod sursa (job #1837185) | Cod sursa (job #3325374)
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <utility>
#include <fstream>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct vecinCost {
int y;
int cost;
};
typedef pair<long long, int> distantaNod;
int distanta[51000];
int vis[51000];
vector<vecinCost> lista[51000]; // salvez vecinii si costul lor
priority_queue<distantaNod> PQ;
int main() {
int n, m;
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int xC, yC, costC;
fin >> xC >> yC >> costC;
vecinCost curent;
curent.y = yC;
curent.cost = costC;
lista[xC].push_back(curent);
}
distanta[1] = 0;
for (int i = 2; i <= n; i++)
distanta[i] = INFINITY;
distantaNod prima = { -distanta[1], 1 }; // hey se pune minus pentru ca priority queue face un MAXHEAP in loc de MINHEAP
PQ.push(prima);
while (!PQ.empty()) {
int nod = PQ.top().second;
if (vis[nod] == 1) {
continue;
}
PQ.pop();
vis[nod] = 1;
for (auto nodIterator : lista[nod]) {
int vecin = nodIterator.y;
int cost = nodIterator.cost;
if (distanta[vecin] > distanta[nod] + cost) {
distanta[vecin] = distanta[nod] + cost;
PQ.push({ -distanta[vecin], vecin });
}
}
}
for (int i = 2; i <= n; i++)
if (distanta[i] == INFINITY) {
fout << 0 << " ";
}
else {
fout << distanta[i] << " ";
}
return 0;
}