Dijkstra? - 洛谷
思路:dij模板题,没啥好说的
代码:#includeusing namespace std; #define ll long long const int N = 200005; int n, m, st, en; ll dist[N]; //距离数组 int pre[N]; //前驱 int head[N], tot; //结构体数组edge存边,edge[i]表示第i条边, //head[i]存以i为起点的第一条边(在edge中的下标) struct e{ int next, to; ll w; } edge[N*4]; void add(int u, int v, ll w){ edge[tot].to = v; edge[tot].w = w; edge[tot].next = head[u]; head[u] = tot++; } void init(){ tot = 0; memset(head, -1 ,sizeof(head)); memset(pre, -1, sizeof(pre)); } struct node{ int id; ll dis; bool operator< (const node& tmp)const{ return dis > tmp.dis; } }; priority_queue q; void dij(){ for(int i=0; i<=n; i++) dist[i] = 1e18; dist[st] = 0; node n1; n1.id = st, n1.dis = 0; q.push(n1); while(q.size()){ int u = q.top().id; q.pop(); for(int i=head[u]; i!=-1; i=edge[i].next){ int v = edge[i].to; ll w = edge[i].w; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; node n2; n2.id = v, n2.dis = dist[v]; q.push(n2); pre[v] = u; //注意别忘了记录最优路径前驱 } } } } vector path; void getPath(){ for(int i=en; i!=-1; i=pre[i]){ path.push_back(i); } } int main(){ cin >> n >> m; st = 1, en = n; int u, v; ll w; init(); for(int i=1; i<=m; i++){ cin >> u >> v >> w; add(u, v, w); add(v, u, w); } dij(); if(dist[en] == 1e18){ cout << -1 << 'n'; return 0; } getPath(); for(int i=path.size()-1; i>=0; i--){ cout << path[i] << ' '; } }



