算法详解:Dijkstra算法(二)之 C++详解
http://www.cnblogs.com/skywang12345/p/3711514.html
实例代码:
//
// 6 9
// 1 2 1
// 1 3 12
// 2 3 9
// 2 4 3
// 3 5 5
// 4 3 4
// 4 5 13
// 4 6 15
// 5 6 4
#include<iostream>
#include<cstring>
#define inf 999999
using namespace std;
bool mark[inf];
int store[100][100];
int rst[inf];
int main()
{
int n,m;
while(cin>>n>>m)
{
if(!n&&!m)
break;
memset(mark,0,sizeof(mark));
memset(store,inf,sizeof(store));
memset(rst,0,sizeof(rst));
for(int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
store[a][b]=c;
store[b][a]=c;
}
for(int i=1;i<=n;i++)
{
store[i][i]=0;
rst[i]=store[1][i];
}
mark[1]=true;
int j=n-1;
while(j--)
{
int minl=inf;
int k;
for(int i=1;i<=n;i++)
{
if(!mark[i]&&rst[i]<minl)
{
minl=rst[i];
k=i;
}
}
mark[k]=true;
for(int i=1;i<=n;i++)
{
if(store[k][i]<inf)
if(!mark[i]&&rst[i]>rst[k]+store[k][i])
rst[i]=rst[k]+store[k][i];
}
}
for(int i=1;i<=n;i++)
{
cout<<1<<"->"<<i<<" "<<rst[i]<<endl;
}
}
}
17万+

被折叠的 条评论
为什么被折叠?



