dijkstra优化+路径还原

来源:互联网 发布:火箭队实力 知乎 编辑:程序博客网 时间:2024/06/15 12:35

dijkstra优化+路径还原

较dijkstra而言,可以优化数值的更新和取出最小值的操作。可以用有限队列+邻接表来实现来实现。每次更新往队列中加入当前最短距离和顶点的值。如果取出的最小值,不是最短距离的话,就丢弃这个值。
路径还原,特简单,就是用一个pre[v]的数组,d[j] = d[i] +cost[i][j] 时更新pre[j] = i,则可。
代码:

//// Created by luozujian on 17-10-17.//#include<cstdio>#include<algorithm>#include<cstring>#include<iostream>#include<queue>#include<vector>#define INF 0x3f3f3f3fusing namespace std;const int maxv =1e2+5;const int maxe = 1e2+5;struct edge{    int to,cost;};typedef pair<int,int>P;vector<edge>G[maxv];int d[maxv];int pre[maxv];int E,V;void dijstra(int v){    priority_queue< P,vector<P>,greater<P> > que;    fill(d,d+maxv,INF);    fill(pre,pre+maxv,-1);    d[v] = 0;    que.push(P(0,v));    while(que.size())    {        P p = que.top();que.pop();        int v = p.second;        if(d[v] < p.first) continue;        for(int i=0;i<G[v].size();i++)        {            edge e = G[v][i];            if(d[e.to] > d[v] + e.cost)            {                d[e.to] = d[v] + e.cost;                pre[e.to] = v;                que.push(P(d[e.to],e.to));            }        }    }}vector<int> get_path(int t){    vector<int>path;    for(;t!=-1;t=pre[t])    {        path.push_back(t);    }    reverse(path.begin(),path.end());    return path;}void solve(){    dijstra(1);    for(int i=1;i<=V;i++)    {        printf("%d\n",d[i]);    }    vector<int> path = get_path(3);    cout<<endl;    for(int i=0;i<path.size();i++)    {        printf("%d\n",path[i]);    }}int main(){    scanf("%d%d",&V,&E);    for(int i=0;i<E;i++)    {        edge e;        int s,t,cost1;        scanf("%d%d%d",&s,&t,&cost1);        e.to = t;        e.cost = cost1;        G[s].push_back(e);        e.to = s;        G[t].push_back(e);    }    solve();    return 0;}