Pagini recente » Cod sursa (job #29402) | Cod sursa (job #387561) | Cod sursa (job #519158) | Cod sursa (job #2744321) | Cod sursa (job #2202555)
#include <fstream>
#include <vector>
#include <queue>
#define pb push_back
#define INF 1e9
#define NMAX 50005
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
class Node{
public:
int y, cost;
Node(int y, int cost){
this->y = y;
this->cost = cost;
}
bool operator<(const Node& ot) const{
return this->cost > ot.cost;
}
};
vector<Node>G[NMAX];
priority_queue<Node> pq;
int dist[NMAX];
int n, m;
void read_data(int &n, int &m){
f >> n >> m;
for(int i = 1; i<=m; i++){
int x, y, cost;
f >> x >> y >> cost;
G[x].pb(Node{y, cost});
}
}
void dijkstra(int start){
for(int i = 1; i<=n; i++){
dist[i] = INF;
}
dist[start] = 0;
pq.push(Node(start, dist[start]));
vector<Node>::iterator it;
while(!pq.empty()){
auto node = pq.top();
pq.pop();
int y = node.y;
int cost = node.cost;
if(cost != dist[y]){
continue;
}
for(it = G[y].begin(); it != G[y].end(); it++){
Node vec = *it;
if(dist[y] + vec.cost < dist[vec.y]){
dist[vec.y] = dist[y] + vec.cost;
pq.push({vec.y, dist[vec.y]});
}
}
}
}
int main(){
read_data(n, m);
dijkstra(1);
for(int i = 2; i<=n; i++){
dist[i] != INF ? g << dist[i] << ' ' : g << 0 << ' ';
}
return 0;
}