堆优化dijkstra 用memset初始化第三个测试点过不了
查看原帖
堆优化dijkstra 用memset初始化第三个测试点过不了
657610
Yoga5801楼主2022/7/23 17:53
#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> PII;
const int N = 5e5 + 7;

int n, m, s;
int dis[N];
bool vis[N];
int h[N], e[N], w[N], ne[N], idx;

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

void dijkstra() {
    //为什么用memset初始化第三个测试点过不了
    memset(dis, 0X7f, sizeof dis); 
    //fill(dis, dis + N, INT_MAX);
    dis[s] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.emplace(0, s); //distance - sno
    while(!heap.empty()) {
        auto t = heap.top();
        heap.pop();
        int ver = t.second, distance = t.first;
        if(vis[ver]) continue;
        vis[ver] = true;
        for(int i = h[ver]; ~i; i = ne[i]) {
            int j = e[i];
            if(!vis[j] && dis[j] > distance + w[i]) {
                dis[j] = distance + w[i];
                heap.emplace(dis[j], j);
            }
        }
    }
}

int main() {
    cin.tie(nullptr)->ios::sync_with_stdio(false);

    cin >> n >> m >> s;

    memset(h, -1, sizeof h);

    while(m--) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    dijkstra();

    for (int i = 1; i <= n; ++i) {
        cout << dis[i] << ' ';
    }
}
2022/7/23 17:53
加载中...