Pagini recente » Cod sursa (job #1137476) | Cod sursa (job #429960) | Cod sursa (job #841709) | Cod sursa (job #2091838) | Cod sursa (job #2297548)
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50005
#define INF 1e9
#define pb push_back
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
struct Node{
private:
int y, cost;
public:
Node(const int& y, const int& cost): y{y}, cost{cost} {}
int get_y() const {
return this->y;
}
int get_cost() const {
return this->cost;
}
bool operator<(const Node& other) const {
return this->cost > other.get_cost();
}
};
vector<Node> G[NMAX];
int n, m, dist[NMAX];
priority_queue<Node> pq;
void read_data(){
in >> n >> m;
for(int i = 1; i<=m; i++){
int x, y, c;
in >> x >> y >> c;
G[x].pb({y, c});
}
}
void dijkstra(){
for(int i = 1; i<=n; i++){
dist[i] = static_cast<int>(INF);
}
dist[1] = 0;
pq.push({1, dist[1]});
while(!pq.empty()){
auto top = pq.top();
pq.pop();
if(top.get_cost() != dist[top.get_y()]){
continue;
}
int node = top.get_y();
for(const auto& adj : G[node]){
if(dist[node] + adj.get_cost() < dist[adj.get_y()]){
dist[adj.get_y()] = dist[node] + adj.get_cost();
pq.push({adj.get_y(), dist[adj.get_y()]});
}
}
}
}
int main(){
read_data();
dijkstra();
for(int i = 2; i<=n; i++){
dist[i] != INF ? out << dist[i] << ' ' : out << 0 << ' ';
}
return 0;
}