迪傑斯特拉路徑輸出模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 1e5+5;
typedef long long LL;
const LL INF = 0x3f3f3f3f3f3f3f3f;
 
struct Edge
{
    int from, to; LL dist;       //起點,終點,距離
    Edge(int from, int to, LL dist):from(from), to(to), dist(dist) {}
};
int n,m; 
struct Dijkstra
{
    int n, m;                 //結點數,邊數(包括反向弧)
    vector<Edge> edges;       //邊表。edges[e]和edges[e^1]互爲反向弧
    vector<int> G[MAXN];      //鄰接表,G[i][j]表示結點i的第j條邊在edges數組中的序號
    int vis[MAXN];            //標記數組
    LL d[MAXN];              //s到各個點的最短路
    int p[MAXN];              //上一條弧
 
    void init(int n)
    {
        this->n = n;
        edges.clear();
        for (int i = 0; i <= n; i++) G[i].clear();
    }
 
    void AddEdge(int from, int to, int dist)
    {
        edges.push_back(Edge(from, to, dist));
        m = edges.size();
        G[from].push_back(m - 1);
    }
 
    struct HeapNode
    {
        int from; LL dist;
        bool operator < (const HeapNode& rhs) const
        {
            return rhs.dist < dist;
        }
        HeapNode(int u, LL w): from(u), dist(w) {}
    };
 
    void dijkstra(int s)
    {
        priority_queue<HeapNode> Q;
        for (int i = 0; i <= n; i++) d[i] = INF;
        memset(vis, 0, sizeof(vis));
        d[s] = 0;
        Q.push(HeapNode(s, 0));
        while (!Q.empty())
        {
            HeapNode x = Q.top(); Q.pop();
            int u = x.from;
            if (vis[u]) continue;
            vis[u] = true;
            for (int i = 0; i < G[u].size(); i++)
            {
                Edge& e = edges[G[u][i]];
                if (d[e.to] > d[u] + e.dist)
                {
                    d[e.to] = d[u] + e.dist;
                    p[e.to] = G[u][i];
                    Q.push(HeapNode(e.to, d[e.to]));
                }
            }
        }
    }
    void output(int x)
    {
        if (x == 1)
        {
            printf("%d", x);
            return ; 
        }
        output(edges[p[x]].from);
        printf(" %d", x);
        putchar('\n');
    }
}gao;
int main()
{
	while(1)
	{
		scanf("%d%d",&n,&m);
		if(n == 0 && m == 0)
		{
			return 0;
		}
		gao.init(n) ;
		for(int i = 0 ; i < m ; i++)
		{
			int x , y , z ;
			cin >> x >> y >> z ;
			gao.AddEdge(x , y , z) ;
			gao.AddEdge(y , x , z) ; 	
		}
		gao.dijkstra(1) ;
		cout << gao.d[n] << endl ;
		gao.output(n);//從開始點1到n的路徑
	}
	
	
}
/*
5 7
1 2 10
1 4 25
1 5 80
2 3 40
3 5 10
4 3 20
4 5 50
0 0
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章