#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAXN (10001)
#define INF (1<<16) typedef struct _Vertex
{
int w[MAXN];
int cw;
int know;
int dis;
int path;
int ew[MAXN]; /*The edge weight of curent vertex to w[i] */ }Graph; Graph G[MAXN]; int read_graph ( void )
{
int i, k;
int n, m, ew; scanf ("%d", &n );
for ( i = ; i < n; i++ ) {
scanf ("%d", &m ); G[i].cw = m; G[i].know = ; G[i].dis = INF; G[i].path = -;
for ( k = ; k < m; k++ ) scanf ("%d%d", &G[i].w[k], &G[i].ew[k] );
} return n;
} int find ( int n )
{
int i;
int m; for ( m = -, i = ; i < n; i++ ) if ( !G[i].know ) { m = i; break; }
if ( m < ) return -; for ( i = m + ; i < n; i++ ) {
if ( !G[i].know ) {
if ( G[i].dis < G[m].dis ) m = i;
}
}
return m;
} void dijst ( int v , int n)
{
int i, k;
int min;
int *w = NULL;
int cw; G[v].dis = ; while () {
min = find ( n );
if ( min < ) { /*Have no vertex to continue*/
break;
} G[min].know = ;
w = G[min].w; cw = G[min].cw;
for ( i = ; i < cw; i++ ) {
if ( !G[ w[i] ].know ) {
if ( G[min].dis + G[min].ew[i] < G[ w[i] ].dis ) {
G[ w[i] ].dis = G[min].dis + G[min].ew[i];
G[ w[i] ].path = min;
}
}
}
}
} void print_path ( int v )
{
if ( G[v].dis > ) {
print_path ( G[v].path );
printf ("->v%d", v + );
} else
printf ("v%d", v + );
} int main(int argc, char *argv[])
{
int n;
int i; freopen ( "data.txt" , "r" , stdin );
n = read_graph ();
dijst ( , n ); for ( i = ; i < n; i++ ) {
print_path ( i );
printf("\n");
}
return ;
}
输入数据:
7
2 1 2 3 1
2 3 3 4 10
2 5 5 0 4
4 2 2 4 2 5 8 6 4
1 6 6
0
1 5 1
参考书籍:数据结构与算法分析(C语言描述第二版)