#include <stdio.h>
#include <stdlib.h>
#define MaxVNum 500
#define INFINITY 100000
typedef int Vertex;
typedef struct MGraph {
int Distance[MaxVNum][MaxVNum];
int Cost[MaxVNum][MaxVNum];
int VertexNum;
}MGraph,*PMGraph;
void Dijkstra(PMGraph PGraph, int dist[], int cost[], int path[], Vertex S);
Vertex MinDist(PMGraph PGraph,int collected[], int dist[]);
void PrintPath(int path[], Vertex D);
int main()
{
PMGraph PGraph=(PMGraph)malloc(sizeof(MGraph));
int M, i,j,distance,c;
Vertex S, D, c1, c2;
scanf("%d %d %d %d", &PGraph->VertexNum, &M, &S, &D);
int *dist = (int*)malloc(sizeof(int)*PGraph->VertexNum);
int *cost = (int*)malloc(sizeof(int)*PGraph->VertexNum);
int *path = (int*)malloc(sizeof(int)*PGraph->VertexNum);
for (i = 0; i < PGraph->VertexNum; i++)
for (j = 0; j < PGraph->VertexNum; j++) {
PGraph->Distance[i][j] = INFINITY;
PGraph->Cost[i][j] = INFINITY;
}
for (i = 0; i < M; i++) {
scanf("%d %d %d %d", &c1, &c2, &distance, &c);
PGraph->Distance[c1][c2] = distance;
PGraph->Distance[c2][c1] = distance;
PGraph->Cost[c1][c2] = c;
PGraph->Cost[c2][c1] = c;
}
Dijkstra(PGraph, dist, cost, path, S);
printf("%d ", S);
PrintPath(path, D);
printf("%d %d",dist[D],cost[D]);
return 0;
}
void Dijkstra(PMGraph PGraph, int dist[],int cost[], int path[], Vertex S)
{
Vertex v,w;
int *collected = (int*)malloc(sizeof(int)*PGraph->VertexNum);
for (v = 0; v < PGraph->VertexNum; v++) {
collected[v] = 0;
dist[v] = PGraph->Distance[S][v];
cost[v] = PGraph->Cost[S][v];
path[v] = -1;
}
dist[S] = 0;
collected[S] = 1;
cost[S] = 0;
while (1) {
v = MinDist(PGraph,collected, dist);
if (v == -1)
break;
collected[v] = 1;
for (w = 0; w < PGraph->VertexNum; w++)
if ((!collected[w]) && (PGraph->Distance[v][w] < INFINITY))
if (dist[v] + PGraph->Distance[v][w] < dist[w]) {
dist[w] = dist[v] + PGraph->Distance[v][w];
cost[w] = cost[v] + PGraph->Cost[v][w];
path[w] = v;
}
else if (dist[v] + PGraph->Distance[v][w] == dist[w] && cost[v] + PGraph->Cost[v][w] < cost[w]) {
cost[w] = cost[v] + PGraph->Cost[v][w];
path[w] = v;
}
}
}
Vertex MinDist(PMGraph PGraph, int collected[], int dist[])
{
Vertex MinV, V;
int MinDist = INFINITY;
for (V = 0; V<PGraph->VertexNum; V++) {
if (!collected[V] && dist[V]<MinDist) {
MinDist = dist[V];
MinV = V;
}
}
if (MinDist < INFINITY)
return MinV;
else return -1;
}
void PrintPath(int path[], Vertex D)
{
Vertex v=D;
if(path[v] != -1)
PrintPath(path, path[v]);
printf("%d ",v);
}
两个权值的Dijkstra问题。