Pagini recente » Cod sursa (job #2232136) | Cod sursa (job #1532695) | Cod sursa (job #289618) | Cod sursa (job #2661738) | Cod sursa (job #2238018)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
#define MAXN 50005
#define INF 0x3f3f3f3f
struct Node {
int node;
int cost;
};
class Comp {
public:
bool operator()(Node A, Node B) {
return A.cost > B.cost;
}
};
vector<Node> graf[MAXN];
priority_queue<Node, vector<Node>, Comp> pq;
int costUntil[MAXN];
int main() {
int n, m;
fin >> n >> m;
for(int i = 1; i <= m; i++) {
Node crtNode;
int x;
fin >> x >> crtNode.node >> crtNode.cost;
graf[x].push_back(crtNode);
}
for(int i = 1; i <= n; i++) {
costUntil[i] = INF;
}
Node startingNode;
startingNode.node = 1;
startingNode.cost = 0;
costUntil[1] = 0;
pq.push(startingNode);
while(!pq.empty()) {
Node crtNode = pq.top(); pq.pop();
// Check if cost hasn't already changed
if(crtNode.cost != costUntil[crtNode.node])
continue;
for(int i = 0; i < graf[crtNode.node].size(); i++) {
Node nextNode = graf[crtNode.node][i];
if( costUntil[nextNode.node] > costUntil[crtNode.node] + nextNode.cost ) {
costUntil[nextNode.node] = costUntil[crtNode.node] + nextNode.cost;
nextNode.cost = costUntil[nextNode.node];
pq.push(nextNode);
}
}
}
for(int i = 2; i <= n; i++) {
if(costUntil[i] == INF) {
fout << "0 ";
} else {
fout << costUntil[i] << " ";
}
}
return 0;
}