dijkstra优化+路径还原

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 0x3f3f3f3f
using 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值