Dijkstra(带路径追踪)

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define pii pair<int,int>
const int maxn=1e5+5,inf=0x3f3f3f3f;
int n,m,s,t;
int dist[maxn];
int pre[maxn]; // 前驱数组,用于记录路径
vector<pii>G[maxn];
int tt[maxn];
int vis[maxn];
vector<int> path; // 用于存储最终的路径

void Dijkstra(){
    priority_queue<pii,vector<pii>,greater<pii>>q;
    for (int i = 1; i <=n ; ++i)dist[i]=inf,vis[i]=0,pre[i]=-1; // 初始化前驱数组
    dist[s]=0;
    q.push({0,s});
    while(!q.empty()){
        int u=q.top().second;
        q.pop();
        if(vis[u])continue;
        vis[u]=1;
        for(auto xx:G[u]){
            int cost=xx.second,v=xx.first;
            if(dist[v]>dist[u]+cost){
                dist[v]=dist[u]+cost;
                pre[v] = u; // 更新前驱节点
                q.emplace(dist[v],v);
            }
        }
    }
}

// 回溯路径
void getPath(int t){
    if(pre[t]!=-1) getPath(pre[t]);
    path.push_back(t);
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin>>n>>m>>s>>t;
    
    for (int i = 1; i <=n; ++i)cin>>tt[i];
    
    for (int i = 0; i < m; ++i) {
        int u,v,c;
        cin>>u>>v>>c;
        G[u].push_back({v,c});
        G[v].push_back({u,c});
    }
    
    Dijkstra();
    if(dist[t]==inf){
        cout<<"Impossible";
    }else{
        cout<<dist[t]<<endl;
        getPath(t);
        for(int i=0;i<path.size();i++){
            cout<<path[i];
            if(i!=path.size()-1) cout<<"->";
        }
        cout<<endl;
    }
    
    return 0;
}

posted @ 2025-03-24 17:06  冬天的睡袋  阅读(7)  评论(0)    收藏  举报