The single source shortest path problem is a typical problem.And I give a solution based on Dijkstra,which is as follow.
First of all,I am not so good at coding.So my code could be much simpler.
Second,this code does work,and you can use it if you can understand.
Finally,when I am coding,I find many problem,such as the "i" in for can not be changed.Or the int i will work,and it is dangerous.
Ok,have fun coding,i_human.Have fun coding,everyone!
THE CODE:
<strong>/</strong>/ 最短路径.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#define a 100
#define b 1000
using namespace std;
int main()
{
int take[a+1];
int point,line;
int min=b;
int k,l,l1;
int count =1;
int first,second,length;
int c[a+1][a+1],dist[a+1],pre[a+1];
for(int i=1;i<=100;i++)
for(int j=1;j<=100;j++)
c[i][j]=b;
cin>>point>>line;
for(int i=0;i<line;i++)
{
cin>>first>>second>>length;
c[first][second]=length;
}
for(int i=2;i<=point;i++)
{
dist[i]=c[1][i];
pre[i]=1;
}
while(count<=point-1)
{
for(int i=2;i<=point;i++)
if(dist[i]<=min && take[i]!=-1)
{
min=dist[i];
k=i;
}
take[k]=-1;
min=b;
for(int j=2;j<=point;j++)
{
if(dist[k]+c[k][j]<=dist[j])
{
pre[j]=k;
dist[j]=dist[k]+c[k][j];
}
}<strong>
</strong>count++;
}
for(int i=2;i<=point;i++)
cout<<dist[i]<<endl;
for(int i=2;i<=point;i++)
{
l1=i;
if(pre[l1]==1)
cout<<l1<<"<--"<<1<<endl;
else
{
while(pre[l1]!=1)
{
cout<<l1<<"<--";
l1=pre[l1];
}
cout<<l1<<"<--"<<1<<endl;
}
}
system("pause");
return 0;
}