【图论之单源最短路】单源最短路专题(Dijkstra,SPFA)

超级(虚拟)源点类型

1488. 最短距离(超级源点)

建立超级源点,从超级源点向某些点连一条权值为0的单向边

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

typedef pair<int, int> PII;

const int N = 1e5 + 10, M = 1e5 * 2 + 1e5 + 10; //无向边*2,再加1e5个超级源点连向其他点的边

int n, m;
int dist[N], id[N];
int h[N], w[M], e[M], ne[M], idx;
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

int dijkstra()
{
    //如果是多次调用dijkstra(),则要每次清空st数组,本题只调用一次,可以不写
    //memset(st, 0, sizeof st); 
    memset(dist, 0x3f, sizeof dist);
    dist[0] = 0;

    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, 0});

    while (heap.size())
    {
        PII t = heap.top();
        heap.pop();

        int ver = t.second, distance = t.first;
        if (st[ver]) continue;
        st[ver] = true;

        for (int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > distance + w[i])
            {
                dist[j] = distance + w[i];
                heap.push({dist[j], j});
            }
        }
    }
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
        add(b, a, c);
    }
    int k;
    scanf("%d", &k);
    while (k -- )
    {
        int id;
        scanf("%d", &id);
        add(0, id, 0); // 超级源点向这些点连一条权值为0的边
    }
    dijkstra();

    int Q;
    scanf("%d", &Q);
    while (Q -- )
    {
        int ver;
        scanf("%d", &ver);
        printf("%d\n", dist[ver]);
    }
    return 0;
}

作者:NFYD
链接:https://www.acwing.com/activity/content/code/content/6289271/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @   Tshaxz  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
历史上的今天:
2022-04-12 【数据结构】单调栈专题
Language: HTML
点击右上角即可分享
微信分享提示