码迷,mamicode.com
首页 > 编程语言 > 详细

DJ 算法的队列优先优化

时间:2018-04-30 14:32:56      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:algo   closed   display   技术分享   优先队列   while   ace   ons   return   

DJ算法就是求单源最短路的算法,但是时间复杂度不太理想,所以在此献上用最小堆来优化的算法。

如果不懂优先队列可以先去看STL分类关于优先队列的介绍;

技术分享图片
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
#define MAX 21000
#define INF 0x3f3f3f3f
using namespace std;
struct nod
{
    int v;
    int net;
}Eg[2*MAX];
struct noo
{
    int x;
    int s;
    bool operator < (const noo & a) const
    {
        return s<a.s;
    }
}t,temp;
int head[MAX],cnt;
bool book[MAX];
int d[MAX];
void build(int form,int to)
{
    Eg[cnt].v=to;Eg[cnt].net=head[form];head[form]=cnt++;
}
void dj(int s)
{
    priority_queue<noo>q;
    d[s]=0;
    t.x=s;
    t.s=0;
    q.push(t);
    while(!q.empty())
    {
        t=q.top();q.pop();
        if(d[t.x]<t.s)
            continue;
        for(int i=head[t.x];i!=-1;i=Eg[i].net)
        {
            if(d[Eg[i].v]>d[t.x]+1)
            {
                 d[Eg[i].v]=d[t.x]+1;
                 temp.x=Eg[i].v;
                 temp.s=d[Eg[i].v];
                 q.push(temp);
            }

        }
    }

}
int main()
{
    int n,m,u,v;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(head,-1,sizeof(head));
        memset(book,0,sizeof(book));
        memset(d,INF,sizeof(d));
        cnt=0;
        int st=0,en=0;
      for(int i=0 ;i<m ;i++)
       {
        scanf("%d%d",&u,&v);
        build(u,v);
        build(v,u);
       }
       dj(1);
   

    }

}
View Code

该算法实现了1到各个点的最短距离;

DJ 算法的队列优先优化

标签:algo   closed   display   技术分享   优先队列   while   ace   ons   return   

原文地址:https://www.cnblogs.com/shuaihui520/p/8973504.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!