【题目描述】
罗老师被邀请参加一个舞会,是在城市n,而罗老师当前所处的城市为1,附近还有很多城市2~n-1,有些城市之间没有直接相连的路,有些城市之间有直接相连的路,这些路都是双向的,当然也可能有多条。
现在给出直接相邻城市的路长度,罗老师想知道从城市1到城市n,最短多少距离。
【输入】
输入n, m,表示n个城市和m条路;
接下来m行,每行a b c, 表示城市a与城市b有长度为c的路。
【输出】
输出1到n的最短路。如果1到达不了n,就输出-1。
【输入样例】
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
【输出样例】
90
【提示】
【数据规模和约定】
1≤n≤2000
1≤m≤10000
0≤c≤10000
要求Dijkstra 但写的是spfa
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include <cstdio>
using namespace std;
const int N=200010,M=400010;
int h[N],w[M],e[M],ne[M],idx;
bool vis[N];
void add(int a,int b,int c)
{
e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;
}
int spfa(int st,int ed)
{
int dist[M];
memset(dist,0x3f,sizeof dist);
queue<int> q;
q.push(st);
dist[st]=0;
vis[st]=true;
while(q.size())
{
int t=q.front();
q.pop();
vis[t]=false;
for(int i=h[t];~i;i=ne[i])
{
int j=e[i];
if(dist[j]>dist[t]+w[i])
{
dist[j]=dist[t]+w[i];
if(!vis[j])
{
vis[j]=true;
q.push(j);
}
}
}
}
return dist[ed];
}
int main()
{
int n,m;
cin>>n>>m;
memset(h,-1,sizeof h);
for(int i=0;i<m;i++)
{
int a,b,w;
scanf("%d%d%d",&a,&b,&w);
add(a,b,w),add(b,a,w);
}
int t=spfa(1,n);
cout<< t <<endl;
return 0;
}