代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int maxn=1005;
const int INF=0x3f3f3f3f;
int n,m;
//存储末边和长度
struct edge
{
int e;
int len;
};
vector <edge> ve[maxn];
//到源点的最小距离
int d[maxn];
//初始化
void init (int x)
{
for (int i=1;i<=n;i++)
d[i]=INF;
d[x]=0;
}
//spfa
void spfa (int x)
{
//循环直到对列为空为止,只要有节点的值更新,就直接将其压入队列
queue<int> q;
q.push(x);
while (!q.empty())
{
int u=q.front(); q.pop();
for (int i=0;i<ve[u].size();i++)
{
int v=ve[u][i].e;
if(d[v]>d[u]+ve[u][i].len)
{
d[v]=d[u]+ve[u][i].len;
q.push(v);
}
}
}
printf("%d\n",d[n]);
}
int main()
{
scanf("%d%d",&m,&n);
init(1);
for (int i=0;i<m;i++)
{
int x,y,len;
scanf("%d%d%d",&x,&y,&len);
edge temp1,temp2;
temp1.e=y; temp1.len=len;
temp2.e=x; temp2.len=len;
ve[x].push_back(temp1);
ve[y].push_back(temp2);
}
spfa(1);
return 0;
}