int maxData=10000000;
int graph[arraysize][arraysize];
int d[arraysize];
int pre[arraysize]; //存储节点前驱
bool final[arraysize];
int t,n;
void Dij(int src)
{
int i,j;
int minData;
int v;
memset(final,0,sizeof(final));
for(i=1;i<=n;++i)
{
d[i] = graph[src][i];
if(d[i]<maxData)
pre[i]=src;
else
pre[i]=0;
}
final[src]=true;
d[src]=0;
for(i=1;i<n;++i)
{
minData = maxData;
for(j=1;j<=n;++j)
{
if(!final[j] && d[j]<minData)
{
v = j;
minData=d[j];
}
}
final[v]=true;
for(j=1;j<=n;++j)
{
if(!final[j] && graph[v][j]<maxData && d[j]>d[v]+graph[v][j])
{
d[j]=d[v]+graph[v][j];
pre[j]=v; //前驱节点更新
}
}
}
cout<<d[1]<<endl; //输出所需的最短路
}
int main()
{
freopen("1.txt","r",stdin);
int i,j;
int start,end,cost;
while(cin>>t>>n)
{
for(i=1;i<=n;++i) //此处别忘了进行初始化临界矩阵为无穷大
{
for(j=1;j<=n;++j)
{
graph[i][j]=maxData;
}
}
for(i=1;i<=t;++i)
{
cin>>start>>end>>cost;
if(cost<graph[start][end]) //重边判断
{
graph[start][end]=cost;
graph[end][start]=cost;
}
}
Dij(n);
//输出最短路径(如果需要从源点到终点输出可利用栈实现)
int p = 1; //终点
while(p!=n) //源点
{
cout<<p<<" ";
p = pre[p];
}
cout<<p<<endl;
}
getch();
return 0;
}
来源:https://www.cnblogs.com/north_dragon/archive/2010/06/03/1751010.html