Dijkstra模板(堆优化)

复杂度:O(m+n)logn

const int maxn=2505;
const int inf=0x3f3f3f3f;
struct Edge
{
    int from,to,dist;
    Edge(int u,int v,int d):from(u),to(v),dist(d)
    {

    }
};
struct heapnode
{
    int d,u;
    bool operator <(const heapnode &r)const
    {
        return d>r.d;
    }
};
struct Dijkstra
{
    int n;
    vector <Edge> edges;//保存所有边
    vector <int> G[maxn];//只保存边的编号
    bool done[maxn];//访问标记
    int d[maxn];//到每个点的距离
    int p[maxn];//保存路径 可以递归打印
    void init(int n)//传参为顶点数
    {
        this->n=n;
        for(int i=0; i<=n; i++)
        {
            G[i].clear();
        }
        edges.clear();
    }
    void addedge(int from,int to,int dist)
    {
        edges.push_back(Edge(from,to,dist));
      int  m=edges.size();
        G[from].push_back(m-1);
    }
    void dijkstra (int s)
    {
        priority_queue<heapnode> q;
        memset(d,inf,sizeof(d));
        d[s]=0;
        memset(done,0,sizeof(done));
        q.push((heapnode)
        {
            0,s
        });
        while(!q.empty())
        {
            heapnode x=q.top();
            q.pop();
            int u=x.u;
            if(done[u])
                continue;
            done[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]=e.from;
                    q.push(heapnode{d[e.to],e.to});
                }
            }
        }
    }
    void print(int u,int s)//打印路径 起点 终点
    {
        if(s==u)
        {
            printf("%d",u);
            return;
        }
        print(u,p[s]);
        printf(" %d",s);
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值