标签:
3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
#include<iostream>
#include<cstdio>
#include<cstring>
#define inf 0x7fffffff
using namespace std;
int n,m,a,b,c;
int s,e;
int mapp[205][205];
int dist[205];
bool book[205];
void ini()
{
memset(book,0,sizeof(book));
for(int i=0;i<n;i++) //初始化用了点小技巧用了无向图的对称性质。
for(int j=i;j<n;j++){
if(i==j) mapp[i][j]=0;
else mapp[i][j]=mapp[j][i] =inf;
}
while(m--)
{
cin>>a>>b>>c;
if(c<mapp[a][b]) mapp[a][b]=mapp[b][a]=c; //if极易丢去。。
}
cin>>s>>e;
for(int i=0;i<n;i++) //dist[]初始化成与源点s直连的一系列点之间的距离。
dist[i]=mapp[s][i];
}
void Dijkstra()
{
for(int j=0;j<n;j++){
int cur=-1;
for(int i=0;i<n;i++){
if(!book[i]){
if(cur==-1||dist[cur]>dist[i]) cur=i;
}
}
book[cur]=1;
for(int i=0;i<n;i++){
if(mapp[cur][i]!=inf&&dist[i]>dist[cur]+mapp[cur][i]) dist[i]=dist[cur]+mapp[cur][i];
}
}
}
int main()
{
while(cin>>n>>m)
{
ini();
Dijkstra();
if(dist[e]==inf) cout<<"-1"<<endl;
else cout<<dist[e]<<endl;
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/kalilili/article/details/42686917