AcWing 1128. 信使


题目传送门

单源最短路径,一般采用堆优化版本的\(Dijkstra\)算法

一、PII写法

#include 
using namespace std;
typedef pair PII;

const int N = 110;
const int M = 2 * 210; //无向边,开两倍

int n, m;
int h[N], e[M], w[M], ne[M], idx;
void add(int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dist[N];
bool st[N];

int dijkstra() {
    int res = 0, cnt = 0;

    //初始化为无法到达
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0; // 1号点为出发点,距离为0
    //小顶堆
    priority_queue, greater<>> heap;
    heap.push({0, 1});
    while (heap.size()) {
        PII u = heap.top();
        heap.pop();

        if (st[u.second]) continue;
        st[u.second] = true;
        res = max(res, u.first);
        cnt++;

        for (int i = h[u.second]; ~i; i = ne[i]) {
            int j = e[i];
            if (dist[j] > dist[u.second] + w[i]) {
                dist[j] = dist[u.second] + w[i];
                heap.push({dist[j], j});
            }
        }
    }
    return cnt == n ? res : -1;
}
int main() {
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m--) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c), add(b, a, c);
    }
    cout << dijkstra() << endl;
    return 0;
}

二、结构体写法

#include 
using namespace std;

const int N = 110;
const int M = 2 * 210; //无向边,开两倍

int n, m;
int h[N], e[M], w[M], ne[M], idx;
void add(int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dist[N];
bool st[N];

//定义结构体
struct Node {
    int dist;   //和起点的距离
    int nodeId; //结点ID
};
//重载小于号,变成小顶堆
bool operator<(const Node &a, const Node &b) {
    return a.dist > b.dist;
}

int dijkstra() {
    int res = 0, cnt = 0;

    //初始化为无法到达
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0; // 1号点为出发点,距离为0

    //小顶堆
    priority_queue heap;
    heap.push({0, 1});

    while (heap.size()) {
        Node u = heap.top();
        heap.pop();

        if (st[u.nodeId]) continue;
        st[u.nodeId] = true;
        res = max(res, u.dist);
        //出队列时统计个数
        cnt++;
        //枚举每个出边
        for (int i = h[u.nodeId]; ~i; i = ne[i]) {
            int j = e[i];
            if (dist[j] > dist[u.nodeId] + w[i]) {
                dist[j] = dist[u.nodeId] + w[i];
                heap.push({dist[j], j});
            }
        }
    }
    return cnt == n ? res : -1;
}
int main() {
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m--) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c), add(b, a, c);
    }
    cout << dijkstra() << endl;
    return 0;
}