Pagini recente » Cod sursa (job #666294) | Cod sursa (job #3254408) | Cod sursa (job #3121223) | Cod sursa (job #636077) | Cod sursa (job #2944793)
//
// Created by Radu Buzas on 22.11.2022.
//
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
//ifstream in("dijkstra.in");
//ofstream out("dijkstra.out");
struct cost{
int c, x;
bool operator<(const cost & o) const{
return (this->c > o.c);
}
};
int n, m;
vector<vector<cost>> graph;
int d[50001];
void dijkstra(int x){
d[x] = 0;
priority_queue<cost> q;
struct cost S;
S.c = 0; S.x = x;
q.push(S);
while (!q.empty()){
int cost = q.top().c;
int nod = q.top().x;
q.pop();
int size = graph[nod].size();
for (int i = 0; i < size; ++i) {
if(cost + graph[nod][i].c < d[graph[nod][i].x]){
d[graph[nod][i].x] = cost + graph[nod][i].c;
S.c = cost + graph[nod][i].c;
S.x = graph[nod][i].x;
q.push(S);
}
}
}
}
int main(){
FILE * in = fopen("dijkstra.in", "r");
fscanf(in, "%d %d", &n, &m);
const int inf = ((unsigned)1 << 31) -1;
graph.resize(n+1);
for(int i = 1; i <=n; ++i)
d[i] = inf;
for(int i = 1; i <= m; ++i){
int x;
struct cost S;
fscanf(in, "%d %d %d", &x, &S.x, &S.c);
graph[x].push_back(S);
// graph[y].push_back({x, c});
}
fclose(in);
FILE * out = fopen("dijkstra.out", "w");
dijkstra(1);
for (int i = 2; i <= n; ++i) {
if(d[i] == ((unsigned)1 << 31) -1)
fprintf(out, "0 ");
else
fprintf(out, "%d ", d[i]);
}
fclose(out);
return 0;
}