AT_abc362_d [ABC362D] Shortest Path 3

· · 个人记录

思路

bfs 板子题。

用 ans_i 表示从 1 到 i 的最短距离。

利用一个队列 q 存储所有状态,每次取出队列顶部的状态进行处理,枚举当前状态所有转移,如果转移到这个新状态时比之前记录的状态更优,则更新并记录该状态,并将新的状态存入队列。

代码

#include<bits/stdc++.h>

using namespace std;

const int MAXN = 1e6 + 1;

long long n, m, a[MAXN], ans[MAXN], p[MAXN];
vector<pair<long long, long long>> c[MAXN];
bool b[MAXN];
queue<long long> q; 

int main() {
    cin >> n >> m;
    for(int i = 1; i <= n; i++) {
        cin >> p[i];
    }
    fill(ans + 1, ans + n + 1, 1e18);
    for(int i = 1, x, y, z; i <= m; i++) {
        cin >> x >> y >> z;
        c[x].push_back({y, z});
        c[y].push_back({x, z});
    }
    q.push(1), ans[1] = p[1];
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        for(int i = 0; i < c[x].size(); i++) {
            int y = c[x][i].first;
            if(ans[y] > ans[x] + c[x][i].second + p[y]) {
                ans[y] = ans[x] + c[x][i].second + p[y];
                q.push(y);
            }
        }
    }
    for(int i = 2; i <= n; i++) {
        cout << ans[i] << " ";
    }
    return 0;
}