Pagini recente » Cod sursa (job #848808) | Cod sursa (job #773384) | Cod sursa (job #1737187) | Cod sursa (job #2719844) | Cod sursa (job #579825)
Cod sursa(job #579825)
#include <fstream>
#include <vector>
using namespace std;
#define NMAX 50050
#define INF 0x3f3f3f3f
int H[NMAX], C[NMAX], poz[NMAX], N, n, m;
vector < pair <unsigned short int, int> > G[NMAX];
void up_heap (int), down_heap (int), dijkstra (), citire (), afisare ();
int main () {
citire ();
dijkstra ();
afisare ();
return 0;
}
void up_heap (int k) {
int c = k, t = c >> 1;
while (t > 0 && C[ H[c] ] < C[ H[t] ]) {
swap (H[c], H[t]);
poz[ H[c] ] = c, poz[ H[t] ] = t;
c = t, t = c >> 1;
}
}
void down_heap (int k) {
int t = k, c = t << 1;
if (c < N && C[ H[c+1] ] < C[ H[c] ]) c++;
while (c <= N && C[ H[c] ] < C[ H[t] ]) {
swap (H[c], H[t]);
poz[ H[c] ] = c, poz[ H[t] ] = t;
t = c, c = t << 1;
if (c < N && C[ H[c+1] ] < C[ H[c] ]) c++;
}
}
void dijkstra () {
int nod, fiu, cst;
vector < pair <unsigned short int, int> >::iterator it;
memset (C, INF, sizeof (C));
N = 1, C[1] = 0, H[1] = 1, poz[1] = 1;
while (N) {
nod = H[1]; poz[nod] = -1;
H[1] = H[N], poz[ H[1] ] = 1; N--;
down_heap (1);
for (it = G[nod].begin (); it != G[nod].end (); it++) {
fiu = it -> first, cst = it -> second;
if (C[nod] + cst < C[fiu]) {
C[fiu] = C[nod] + cst;
if (!poz[fiu]) {
N++, H[N] = fiu, poz[fiu] = N;
up_heap (N);
}
else
up_heap (poz[fiu]);
}
}
}
}
void citire () {
ifstream f ("dijkstra.in");
int i, x, y, c;
f >> n >> m;
for (i = 1; i <= m; i++) {
f >> x >> y >> c;
G[x].push_back (make_pair ((unsigned short int) y, c));
}
f.close ();
}
void afisare () {
ofstream g ("dijkstra.out");
for (int i = 2; i <= n; i++)
g << (C[i] != INF ? C[i] : 0) << " ";
g.close ();
}