Write a program to not only find the weighted shortest distances, but also count the number of different minimum paths from any vertex to a given source vertex in a digraph. It is guaranteed that all the weights are positive.(编写一个程序,不仅可以找到加权的最短距离,还可以计算有向图中从任何顶点到给定源顶点的不同最小路径的数量。保证所有权重都是正的。)
函数接口定义:
void ShortestDist( MGraph Graph, int dist[], int count[], Vertex S );
where MGraph is defined as the following:
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
The shortest distance from V to the source S is supposed to be stored in dist[V]. If V cannot be reached from S, store -1 instead. The number of different minimum paths from V to the source S is supposed to be stored in count[V] and count[S]=1.(从V到源S的最短距离应该存储在dist[V]中。如果无法从S到达V,则存储-1。从V到源S的不同最小路径的数量被假定存储在count[V]和count[S]=1中。)
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef enum {false, true} bool;
#define INFINITY 1000000
#define MaxVertexNum 10 /* maximum number of vertices */
typedef int Vertex; /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef int WeightType;
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
WeightType G[MaxVertexNum][MaxVertexNum];
};
typedef PtrToGNode MGraph;
MGraph ReadG(); /* details omitted */
void ShortestDist( MGraph Graph, int dist[], int count[], Vertex S );
int main()
{
int dist[MaxVertexNum], count[MaxVertexNum];
Vertex S, V;
MGraph G = ReadG();
scanf("%d", &S);
ShortestDist( G, dist, count, S );
for ( V=0; V<G->Nv; V++ )
printf("%d ", dist[V]);
printf("\n");
for ( V=0; V<G->Nv; V++ )
printf("%d ", count[V]);
printf("\n");
return 0;
}
/* Your function will be put here */
输入样例:
8 11
0 4 5
0 7 10
1 7 30
3 0 40
3 1 20
3 2 100
3 7 70
4 7 5
6 2 1
7 5 3
7 2 50
3
输出样例:
40 20 100 0 45 53 -1 50
1 1 4 1 1 3 0 3
代码:
int vis[MaxVertexNum];
void ShortestDist( MGraph Graph, int dist[], int count[], Vertex S )
{
for(int i=0;i<Graph->Nv;i++)//初始化
{
vis[i]=0;
dist[i]=Graph->G[S][i];
if(dist[i]<INFINITY) count[i]=1;//是S的邻接点
else count[i]=0;//不是
}
//初始化S点
dist[S]=0;
vis[S]=1;
count[S]=1;
while(1)
{
int v=-1;
int min=INFINITY;
for(int j=0;j<Graph->Nv;j++)//找v点
{
if(vis[j]==0&&dist[j]<min)
{
min=dist[j];
v=j;
}
}
if(v==-1) break;
vis[v]=1;
for(int w=0;w<Graph->Nv;w++)//访问v点的邻接点
{
//路径权值一致,说明w点原有的几条路径权值等同于经过v点到w点的几条路径权值
if(dist[v]+Graph->G[v][w]==dist[w])
count[w]+=count[v];//w点的路径要在原有基础上再加上v点的路径条数
//没被访问过且路径权值比原来的小
if((dist[v]+Graph->G[v][w]<dist[w])&&vis[w]==0)
{
dist[w]=dist[v]+Graph->G[v][w];
count[w]=count[v];//有几条路径可以到达v点就有几条路径可以到达w点
}
}
}
for(int i=0;i<Graph->Nv;i++)//不能到达S点
{
if(dist[i]==INFINITY) dist[i]=-1;
}
}