为什么只能过一个样例呀,明明已经用堆优化了

P4779 【模板】单源最短路径(标准版)

JINHUUI @ 2024-07-30 22:46:36

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

using namespace std;

const int N = 1e5 + 10;

typedef pair<int, int> PII;

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

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

void dijkstra(){
    memset(dist, 0x3f, sizeof dist);
    dist[s] = 0;
    priority_queue<PII, vector<PII>, greater<PII> > q;
    q.push({0, s});

    while(q.size()){
        auto t = q.top();
        q.pop();

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

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

    return ;
}

int main(){

    cin >> n >> m >> s;
    memset(h, -1, sizeof h);
    int x, y, z;
    for(int i = 0;i < m;i++){
        cin >> x >> y >> z;
        add(x, y, z);
    }

    dijkstra();
    for(int i = 1;i <= n;i++)    cout << dist[i] << ' ';

    return 0;
}

by meifan666 @ 2024-07-30 23:02:13

@JINHUUI 链式前向星里也要判断是否松驰过,不然下一个松弛点仍不变


|