多学习。

【图论】Acwing1488.最短距离(超级源点+Dijkstra堆优化)


题解

加入一个超级源点,到各个商店之间的距离为0,对商店求单源最短路,那么各个村庄到源点的最短距离就是到其最短商店的距离

vector成邻接表

#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
#define x first
#define y second
//建立一个超级源点,各商店到超级源点的距离为0,则可以求出超级源点到其他点的最短距离,就是其他点到商店的最小距离
using namespace std;

typedef pair<int,int> PII;

const int N = 100010;

int dist[N],n;
vector<PII> h[N];
bool vis[N];

void dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    priority_queue<PII,vector<PII>,greater<PII>> q;
    q.push({0,0});
    while(q.size())
    {
        auto e = q.top();
        q.pop();
        int distinct = e.x, head = e.y;
        
        if(vis[head]) continue;
        vis[head] = true;
        
        for(auto t : h[head]){
            if(dist[t.y] > distinct + t.x){
                dist[t.y] = distinct + t.x;
                q.push({dist[t.y],t.y});
            }
        }
    }
}

int main()
{
    int m,a,b,v;
    cin >> n >> m;
    while(m--){
        cin >> a >> b >> v;
        h[a].push_back({v,b});
        h[b].push_back({v,a});
    }
    cin >> m;
    while(m--){
        cin >> a;
        h[0].push_back({0,a});
    }
    dijkstra();
    cin >> m;
    while(m--)
    {
        cin >> a;
        cout << dist[a] << endl;
    }
    return 0;
}

数组成邻接表

#include <iostream>
#include <queue>
#include <cstring>
#include <vector>
#define x first
#define y second

using namespace std;

typedef pair<int,int> PII;

const int N = 300010; //注意:不止无向边开两倍还要多出一倍给超级源点

int cnt = 0;
int e[N],h[N],ne[N],v[N];
bool st[N];
void add(int a,int b,int c)
{
    ne[cnt] = h[a];
    h[a] = cnt;
    v[cnt] = c;
    e[cnt++] = b;
}

int dist[N];
void dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    priority_queue<PII,vector<PII>,greater<PII>> q;
    q.push({0,0});
    
    while(q.size())
    {
        auto t = q.top();
        q.pop();
        
        int d = t.x, point = t.y;
        
        if(st[point]) continue;
        st[point] = true;
        
        for(int i = h[point]; i != -1; i = ne[i]){
            if(dist[e[i]] > d + v[i]){
                dist[e[i]] = d + v[i];
                q.push({dist[e[i]],e[i]});
            }
        }
    }
}

int main()
{
    memset(h,-1,sizeof h);
    
    int n,m,a,b,c;
    cin >> n >> m;
    for(int i = 0; i < m; ++i){
        cin >> a >> b >> c;
        add(a,b,c);
        add(b,a,c);
    }
    cin >> m;
    while(m--)
    {
        cin >> a;
        add(0,a,0);
    }
    
    dijkstra();
    
    cin >> m;
    while(m--)
    {
        cin >> a;
        cout << dist[a] << endl;
    }
    return 0;
}
posted @   czyaaa  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示