Pagini recente » Cod sursa (job #236250) | Cod sursa (job #1307840) | Arhiva de probleme | Motroi Valeriu | Cod sursa (job #144768)
Cod sursa(job #144768)
#include <cstdio>
const int maxn = 50001;
const int inf = 1 << 30;
FILE *in = fopen("dijkstra.in","r"), *out = fopen("dijkstra.out","w");
struct graf
{
int nod, cost;
graf *next;
};
int n, m;
graf *a[maxn];
int p, u;
int c1[maxn], c2[maxn], v[maxn];
int d[maxn];
void add(int where, int what, int cost)
{
graf *q = new graf;
q->nod = what;
q->cost = cost;
q->next = a[where];
a[where] = q;
}
void read()
{
fscanf(in, "%d %d", &n, &m);
int x, y, z;
for ( int i = 1; i <= m; ++i )
{
fscanf(in, "%d %d %d", &x, &y, &z);
add(x, y, z);
}
}
void bford()
{
for ( int i = 2; i <= n; ++i )
d[i] = inf;
c1[++p] = 1;
v[1] = 1;
while ( p )
{
for ( int i = 1; i <= p; ++i )
{
graf *q = a[ c1[i] ];
v[ c1[i] ] = 0;
while ( q )
{
if ( d[ q->nod ] > d[ c1[i] ] + q->cost )
{
d[ q->nod ] = d[ c1[i] ] + q->cost;
if ( !v[ q->nod ] )
c2[++u] = q->nod, v[ q->nod ] = 1;
}
q = q->next;
}
}
p = u;
for ( int i = 1; i <= u; ++i )
c1[i] = c2[i];
u = 0;
}
}
int main()
{
read();
bford();
for ( int i = 2; i <= n; ++i )
fprintf(out, "%d ", d[i] == inf ? 0 : d[i]);
fprintf(out, "\n");
return 0;
}