优先队列优化的Dijkstra算法

直接贴代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <ctime>
using namespace std;
#define LL long long
const int N = 30005;
const LL INF = 1LL << 60;
struct Node
{
    int v,next,w;
    bool operator < (const Node &a) const
    {
        return w > a.w;
    }
}p[N],t1,t2;

bool vis[N];
int head[N],cnt;
LL dis[N];

void addedge(int u,int v,int w)
{
    p[cnt].v = v;
    p[cnt].next = head[u];
    p[cnt].w = w;
    head[u] = cnt++;
}

void Dijkstra(int s)
{
    priority_queue<Node> q;
    t1.v = s;
    q.push(t1);
    memset(vis,false,sizeof(vis));
    dis[s] = 0;
    while(!q.empty())
    {
        t1 = q.top();
        q.pop();
        int u = t1.v;
        if(vis[u]) continue;
        vis[u] = true;
        for(int i = head[u]; i != -1 ; i = p[i].next)
        {
            int v = p[i].v;
            if(!vis[v] && dis[v] > dis[u] + p[i].w)//松弛操作
            {
                dis[v] = dis[u] + p[i].w;
                t2.v = v;t2.w = dis[v];
                q.push(t2);
            }
        }
    }
}

int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m))
    {
        cnt = 0;
        memset(head,-1,sizeof(head));
        memset(p,0,sizeof(p));
        while(m--)
        {
            int u,v,w;
            scanf("%d %d %d",&u,&v,&w);
            addedge(u,v,w);
            addedge(v,u,w);
        }
        int s,t;
        scanf("%d %d",&s,&t);
        for(int i = 1 ; i <= n ; i ++) dis[i] = INF;
        Dijkstra(s);
        if(dis[t] == INF) puts("-1");
        else printf("%lld\n",dis[t]);
    }
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值