#include <bits/stdc++.h>
using namespace std;
#define inf 999999999
int a[102][102], vis[102], b[102];
void dis(int k,int n)
{
int i,t;
int m = n-1;
while(m--)
{
int Min = inf;
for(i = 1; i<=n; i++)//查找离源节点最近的节点
{
if(b[i]<Min&&vis[i]==0)
{
Min = b[i];
t = i;
}
}
a[k][t] = Min;
vis[t] = 1;
for(i = 1; i<=n; i++)
{
if(b[i]>a[t][i] + b[t] && vis[i] == 0)
b[i] = a[t][i] + b[t];//更新与源节点相邻路径的权值,b[t]为离源节点最近的路径值;
}
}
}
int main()
{
int n, m, x,y,z,i,j;
while(~scanf("%d%d",&n,&m))
{
memset(b,inf,sizeof(b));
memset(vis,0,sizeof(vis));
for(i = 1; i<=n; i++)
{
for(j = 1; j <=n; j++)
{
if(i == j)
{
a[i][j] = 0;
}
else a[i][j] = inf;
}
}
for(i = 1; i<=m; i++)
{
cin>>x>>y>>z;
a[x][y] = a[y][x] = min(a[x][y], z);
}
for(i = 1; i<=n; i++)//第一次更新与源节点相邻的路径权值;
{
b[i] = a[1][i];
}
vis[1] = 1;
dis(1,n);
printf("%d\n",a[1][n]);
}
}
单源最短路径
最新推荐文章于 2022-08-29 20:19:26 发布