Pagini recente » Cod sursa (job #3321759) | Cod sursa (job #1049095) | Cod sursa (job #3312394) | Cod sursa (job #1618702) | Cod sursa (job #1615147)
#include <fstream>
#include <queue>
using namespace std;
const int MAX_N = 50000;
const int MAX_M = 250000;
const int MAX_WEIGHT = 30000;
const int NIL = -1;
struct Arc {
int v, weight;
int next;
};
Arc G[MAX_M];
int head[MAX_N];
int D[MAX_N];
vector <int> Q[MAX_WEIGHT];
void addArc(int u, int v, int weight, int pos) {
G[pos].v = v;
G[pos].weight = weight;
G[pos].next = head[u];
head[u] = pos;
}
int main() {
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
fin.tie(0);
ios_base::sync_with_stdio(false);
int N, M; fin >> N >> M;
for (int i = 0; i < N; ++ i) {
head[i] = NIL;
}
for (int i = 0; i < M; ++ i) {
int u, v, weight; fin >> u >> v >> weight;
addArc(u - 1, v - 1, weight, i);
}
for (int i = 1; i < N; ++ i) {
D[i] = MAX_WEIGHT - 1;
Q[MAX_WEIGHT - 1].emplace_back(i);
}
D[0] = 0;
Q[0].emplace_back(0);
for (int i = 0; i < MAX_WEIGHT; ++ i) {
int st = 0;
while (st != (int) Q[i].size()) {
int u = Q[i][st++];
if (D[u] == i) {
for (int j = head[u]; j != NIL; j = G[j].next) {
int v = G[j].v;
if (D[v] > D[u] + G[j].weight) {
D[v] = D[u] + G[j].weight;
Q[D[v]].emplace_back(v);
}
}
}
}
}
for (int i = 1; i < N; ++ i) {
fout << ((D[i] == MAX_WEIGHT - 1) ? 0 : D[i]) << " \n"[i == N - 1];
}
fout.close();
return 0;
}