Pagini recente » Cod sursa (job #635395) | Borderou de evaluare (job #641567) | Cod sursa (job #2577793) | Cod sursa (job #2094907) | Cod sursa (job #2462902)
#include<bits/stdc++.h>
#define pb push_back
#define INF 1e9
#define NMAX 50005
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
class Node{
public:
int y, cost;
Node(const int& y, const int& cost): y{y}, cost{cost} {}
bool operator<(const Node& other) const {
return this->cost > other.cost;
}
};
vector<Node> Graph[NMAX];
int n, m, dist[NMAX];
priority_queue<Node> pq;
void read_data(){
in >> n >> m;
for(int i = 0; i<m; i++){
int x, y, c;
in >> x >> y >> c;
Graph[x].pb({y, c});
}
}
void dijkstra(){
for(int i = 1; i<= n; i++){
dist[i] = INF;
}
dist[1] = 0;
pq.push({1, dist[1]});
while(!pq.empty()){
auto top = pq.top();
auto cost = top.cost;
pq.pop();
if(cost != dist[top.y]){
continue;
}
for(const auto& neigh : Graph[top.y]){
if(dist[neigh.y] > dist[top.y] + neigh.cost){
dist[neigh.y] = dist[top.y] + neigh.cost;
pq.push({neigh.y, dist[neigh.y]});
}
}
}
}
int main(){
read_data();
dijkstra();
for(int i = 2; i<=n; i++){
dist[i] == INF ? out << '0' << ' ' : out << dist[i] << ' ';
}
return 0;
}