此算法为<算法导论>中第24章第2小节关于single-source shortest paths in directed graphs原理的实现.
原著P592
#include<iostream>
using namespace std;
#define MAX 32767
int N,M;
int u,v,l,pos;
int w[1000][1000],d[1000];
int order[1000],parent[1000],visited[1000];
int cnt=0;
void DFS_Visited(int pos)
{
visited[pos]=1;
for(int i=0;i<N;++i)
{
{
if(w[pos][i]<MAX)
{
if(visited[i]==0)
{
DFS_Visited(i);
}
}
}
}
order[cnt++]=pos;
}
void DFS()
{
for(int i=0;i<N;++i)
{
if(visited[i]==0)
{
DFS_Visited(i);
}
}
}
void Dag_Shortest_Path(int pos)
{
DFS();
for(int i=0;i<cnt;++i)
{
if(order[i]==pos)
d[i]=0;
else
d[i]=MAX;
}
for(int i=0;i<cnt;++i)
{
for(int j=0;j<N;++j)
{
if(w[j][order[i]]<MAX)
{
if(d[j]>d[i]+w[j][order[i]])
{
d[j]=d[i]+w[j][order[i]];
parent[j]=order[i];
}
}
}
}
for(int i=0;i<cnt;++i)
{
cout<<"(pos:"<<order[i]<<"\tdis:"<<d[i]<<"\tparent:"<<parent[i]<<")\n";
}
}
int main()
{
cin>>N>>M;
for(int i=0;i<N;++i)
{
for(int j=0;j<N;++j)
{
w[i][j]=MAX;
}
w[i][i]=0;
visited[i]=0;
}
for(int i=0;i<M;++i)
{
cin>>u>>v>>l;
w[u][v]=l;
}
cin>>pos;
Dag_Shortest_Path(pos);
return 0;
}
测试数据:
测试数据(书上讲解的内容)
6 10
1 0 5
2 0 3
2 1 2
3 1 6
3 2 7
4 2 4
5 2 2
4 3 -1
5 3 1
5 4 -2