跳到正文

个人记录

AT_abc362_d [ABC362D] Shortest Path 3

bananamilktea约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月22日
篇幅
约 2 分钟

版本

  1. v1当前

思路

bfs 板子题。

用 ansians_i 表示从 11 到 ii 的最短距离。

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

代码

C++
#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;
}
原文