算法—Dijkstra

Dijkstra算法介绍
#include <bits/stdc++.h>

#define MAXNODENUMBER 100

using namespace std;

typedef pair<int, int> PII; // 第一个int保存顶点编号 第二个int保存距离

struct edge {
    int destination;
    int weight;

    edge(int destination_, int weight_) {
        destination = destination_;
        weight = weight_;
    }
};

struct compare {
    bool operator()(PII lhs, PII rhs) {
        return lhs.second > rhs.second;
    }
};

vector<edge> graph[MAXNODENUMBER];
vector<int> Dist(MAXNODENUMBER, -1);
vector<int> State(MAXNODENUMBER, 0);

void djikstra(int s) {

    priority_queue<PII, vector<PII>, compare> pq;
    pq.push({s, 0});
    Dist[s] = 0;

    while (!pq.empty()) {
        PII cur = pq.top();
        pq.pop();

        if (State[cur.first] == 1) continue;
        else State[cur.first] = 1;

        for (edge nextEdge: graph[cur.first]) {
            if (Dist[nextEdge.destination] > Dist[cur.first] + nextEdge.weight || Dist[nextEdge.destination] == -1) {
                Dist[nextEdge.destination] = Dist[cur.first] + nextEdge.weight;
                pq.push({nextEdge.destination, Dist[nextEdge.destination]});
            }
        }
    }
}


int main() {

    int n, m, s;
    cin >> n >> m >> s;
    // 建图
    for (int i = 0; i < m; ++i) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].push_back(edge(v, w));
        graph[v].push_back(edge(u, w));
    }
    djikstra(s);
    for (int i = 0; i < n; ++i) {
        cout << Dist[i];
        if (i != n - 1) cout << " ";
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值