解题代码
#include <stdio.h>
#include <stdlib.h>
#define MAXN 500
#define Infinite 65534
#define error -1
typedef struct Data Weight;
struct Data {
int dist;
int cost;
} ;
typedef struct GNode * PtrToGNode;
struct GNode {
int Nv, Ne;
Weight W[ MAXN] [ MAXN] ;
} ;
typedef PtrToGNode MGraph;
int collection[ MAXN] , dist[ MAXN] , cost[ MAXN] ;
MGraph BuildMGraph ( int N, int M) ;
void Dijkstra ( int S, MGraph G) ;
int FindMinDist ( MGraph G) ;
int main ( )
{
int N, M, S, D;
scanf ( "%d %d %d %d" , & N, & M, & S, & D) ;
MGraph G = BuildMGraph ( N, M) ;
Dijkstra ( S, G) ;
printf ( "%d %d" , dist[ D] , cost[ D] ) ;
return 0 ;
}
MGraph BuildMGraph ( int N, int M) {
MGraph G = ( MGraph) malloc ( sizeof ( struct GNode) ) ;
G-> Nv = N;
G-> Ne = M;
for ( int i= 0 ; i< N; i++ )
for ( int j = 0 ; j < N; j++ )
G-> W[ i] [ j] . dist = G-> W[ i] [ j] . cost = Infinite;
int temp_dist, temp_cost, temp_s, temp_d;
for ( int i = 0 ; i < M; i++ ) {
scanf ( "%d %d %d %d" , & temp_s, & temp_d, & temp_dist, & temp_cost) ;
G-> W[ temp_s] [ temp_d] . cost = G-> W[ temp_d] [ temp_s] . cost = temp_cost;
G-> W[ temp_s] [ temp_d] . dist = G-> W[ temp_d] [ temp_s] . dist = temp_dist;
}
for ( int i = 0 ; i < G-> Nv; i++ ) {
dist[ i] = cost[ i] = Infinite;
G-> W[ i] [ i] . cost = G-> W[ i] [ i] . dist = 0 ;
}
return G;
}
void Dijkstra ( int S, MGraph G) {
int v;
for ( int i = 0 ; i < G-> Nv; i++ ) {
dist[ i] = G-> W[ S] [ i] . dist;
cost[ i] = G-> W[ S] [ i] . cost;
}
collection[ S] = 1 ;
while ( 1 ) {
v = FindMinDist ( G) ;
if ( v == error) break ;
collection[ v] = 1 ;
for ( int i = 0 ; i < G-> Nv; i++ ) {
if ( ! collection[ i] && dist[ v] + G-> W[ v] [ i] . dist < dist[ i] ) {
dist[ i] = dist[ v] + G-> W[ v] [ i] . dist;
cost[ i] = cost[ v] + G-> W[ v] [ i] . cost;
}
else if ( ! collection[ i] && dist[ v] + G-> W[ v] [ i] . dist == dist[ i] && cost[ v] + G-> W[ v] [ i] . cost < cost[ i] )
cost[ i] = cost[ v] + G-> W[ v] [ i] . cost;
}
}
}
int FindMinDist ( MGraph G) {
int mindist= Infinite, minv= 0 ;
for ( int i = 0 ; i < G-> Nv; i++ ) {
if ( ! collection[ i] && dist[ i] < mindist) {
mindist = dist[ i] ;
minv = i;
}
}
if ( mindist < Infinite) return minv;
return error;
}
测试结果
问题整理
1.Dijkstra算法对我不友好,需要多加练习。