water

11  •  1个月前


#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

struct Edge {
    int to, weight;
};

int main() {
    int n, m, s;
    cin >> n >> m >> s;
    
    // 使用邻接表存储图
    vector<vector<Edge>> graph(n + 1);
    
    for (int i = 0; i < m; ++i) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].push_back({v, w});
    }
    
    // 距离数组,初始化为无穷大
    vector<int> dist(n + 1, INT_MAX);
    dist[s] = 0;
    
    // 最小堆,存储{距离, 节点}
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, s});
    
    while (!pq.empty()) {
        int d = pq.top().first;
        int u = pq.top().second;
        pq.pop();
        
        // 如果当前距离大于已经计算出的最短距离,跳过
        if (d > dist[u]) continue;
        
        // 遍历所有邻接边
        for (const auto& edge : graph[u]) {
            int v = edge.to;
            int weight = edge.weight;
            
            // 如果找到更短路径,更新并加入优先队列
            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }
    
    // 输出结果
    for (int i = 1; i <= n; ++i) {
        if (dist[i] == INT_MAX) {
            cout << -1 << " ";
        } else {
            cout << dist[i] << " ";
        }
    }
    cout << endl;
    
    return 0;
}

评论:

请先登录,才能进行评论