作者:小肥沙沙2006_759 | 来源:互联网 | 2023-07-30 12:39
Youaregivenaweightedundirectedgraph.Theverticesareenumeratedfrom1ton.Yourtaskistofindthesh
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.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), 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.
Output
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.
Sample 1
Inputcopy | Outputcopy |
---|
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1 | 1 4 3 5 |
Sample 2
Inputcopy | Outputcopy |
---|
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1 | 1 4 3 5 |
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn=100005;
const int maxb=2e5+5;
typedef long long ll;
const long long INF=9e13;
int n,m;
int a,b,c;
int head[maxn],pre[maxn];
bool vis[maxn];
ll dis[maxn];
int cnt;
struct edge
{int next;int to;int cost;
}e[maxb];
struct node
{int dis;int id;node(){}node(int dis,int id):dis(dis),id(id){ }bool operator <(const node &a) const {return dis>a.dis;}
};
void begin()
{memset(vis,0,sizeof(vis));memset(head,-1,sizeof(head));memset(pre,0,sizeof(pre));cnt&#61;0;
}
void build(int u,int v,int w)
{e[cnt].to&#61;v;e[cnt].cost&#61;w;e[cnt].next&#61;head[u];head[u]&#61;cnt&#43;&#43;;
}
void dij(int x,int n)
{priority_queue q;for(int i&#61;0;i<&#61;n;i&#43;&#43;) dis[i]&#61;INF;dis[x]&#61;0;q.push(node(0,x));node p;while(!q.empty()){p&#61;q.top();q.pop();int u&#61;p.id;if(vis[u]) continue;vis[u]&#61;1;for(int i&#61;head[u];i!&#61;-1;i&#61;e[i].next){int j&#61;e[i].to;if(!vis[j]&&dis[j]>dis[u]&#43;e[i].cost){dis[j]&#61;dis[u]&#43;e[i].cost;pre[j]&#61;u;q.push(node(dis[j],j));}}}return ;
}
void find(int x)
{if(x!&#61;1)find(pre[x]);if(x!&#61;1)cout<<" ";cout<}
int main()
{scanf("%d %d",&n,&m);begin();while(m--){scanf("%d %d %d",&a,&b,&c);build(a,b,c);build(b,a,c);}dij(1,n);if(dis[n]!&#61;INF)find(n);else printf("-1");cout<}