Pagini recente » Rating Tudor Florea (tudorflorea) | Cod sursa (job #3296246)
#include <stdio.h>
#include <queue>
#include <vector>
const int MAX_N = 50'000;
const int INF = 2'000'000'000;
struct Edge {
int node;
int cost;
};
struct State {
int node;
int cost;
bool operator<(const State &other) const {
return cost < other.cost;
}
};
int n;
std::vector<Edge> adj[MAX_N];
int min_cost[MAX_N];
void dijkstra(int source) {
for(int i = 0; i < n; i++) {
min_cost[i] = INF;
}
std::priority_queue<State> pq;
min_cost[source] = 0;
pq.push({source, 0});
while(!pq.empty()) {
State nd = pq.top();
pq.pop();
if(nd.cost == min_cost[nd.node]) {
for(Edge &e : adj[nd.node]) {
int c = nd.cost + e.cost;
if(c < min_cost[e.node]) {
min_cost[e.node] = c;
pq.push({e.node, c});
}
}
}
}
}
int main() {
FILE *fin = fopen("dijkstra.in", "r");
FILE *fout = fopen("dijkstra.out", "w");
int m;
fscanf(fin, "%d%d", &n, &m);
for(int i = 0; i < m; i++) {
int u, v, cost;
fscanf(fin, "%d%d%d", &u, &v, &cost);
u--;
v--;
adj[u].push_back({v, cost});
}
dijkstra(0);
for(int i = 1; i < n; i++) {
fprintf(fout, "%d ", min_cost[i]);
}
fputc('\n', fout);
fclose(fin);
fclose(fout);
return 0;
}