题目描述
You are given a weighted undirected graph. The vertices are enumerated from 1 to n . Your task is to find the shortest path between the vertex 1 and the vertex n .
输入格式
The first line contains two integers n n n and m m m ( 2<=n<=10^5,0<=m<=10^5 ), where n n n is the number of vertices and m m m is the number of edges. Following m m m lines contain one edge each in form ai bi and wi ( 1<=ai,bi<=n,1<=wi<=10^6 ), where ai,bi are edge endpoints and wi is the length of the edge.
It is possible that the graph has loops and multiple edges between pair of vertices.
输出格式
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
输入 #1
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1
输出 #1
1 4 3 5
输入 #2
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1
输出 #2
1 4 3 5
思路:
模板题,最重要的是学会STL。
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=1e5+10;
const ll INF=1ll<<62;
vector<int>e[N];//定义可变二维数组 只有N行
vector<int>w[N];
bool v[N];
ll d[N];
int p[N];
int n,m,a,b,c;
struct node
{
ll d;
int u;
bool operator<(const node&rhs) const
{
return d>rhs.d;
}
};
void Dijkstra()
{
priority_queue<node>q;//优先队列 初始化定义
for(int i=1;i<=n;i++)
d[i]=INF;
d[1]=0;
memset(v,0,sizeof(v));
node tn;
tn.d =0,tn.u =1;
q.push(tn);//入队
while(!q.empty())
{
node t=q.top();
q.pop();
int u=t.u ;
if(v[u])
continue;
v[u]=true;
for(int i=0;i<e[u].size();i++)//队列元素个数
{
int v=e[u][i];
if(d[v]>d[u]+w[u][i])
{
d[v]=d[u]+w[u][i];
p[v]=u;
tn.d =d[v],tn.u =v;
q.push(tn);
}
}
}
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++)
e[i].clear(),w[i].clear();//清除元素个数
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&a,&b,&c);
e[a].push_back(b);
w[a].push_back(c);
e[b].push_back(a);
w[b].push_back(c);//在尾部加一个数据
}
Dijkstra();
if(d[n]==INF)
printf("-1\n");
else
{
e[1].clear();
e[1].push_back(n);
while(p[n]!=1)
{
n=p[n];
e[1].push_back(n);
}
e[1].push_back(1);
for(int i=e[1].size()-1;i>0;i--)
printf("%d ",e[1][i]);
printf("%d\n",e[1][0]);
}
}
return 0;
}