跳到正文

题解

参考了xht佬的做法

丿青衣挽红袖约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年7月11日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 4 分钟

版本

  1. v1当前

给定3e5点,3e5边和权重,开始时有k个点被感染,开始后d天中,第i天距离被感染者小于等于di的点被感染,问d天后每个人的被感染情况。

如果直接使用多源dijkstra,维护时为了表达某点to是di天已经经过了dis后到达的,to的距离应该记录为dis+w[i],而加上dis之后和原有的数据产生交叉,到了下一天时无法区分某个人是昨天被感染成dis+w[i]的,还是原来就是w[i]。而前者必须-dis参与计算,否则会产生谬误。

因此使用两个优先队列q和p,q存放所有可以直接接触到感染者的点以及距离w[i],p是必被感染者的处理地,所有的小于di的dis+w[i]都在p中处理。

每一天先看q中有多少可以被感染的,全部变成放入p中处理。每次枚举到p中pre的邻点to时,若当前dis加上w[to]小于等于di,则继续放入p中处理;若当前dis加上w[to]大于di,则不再放入p中,而是将to作为下一天的可直接接触到感染者的点,记录距离w[to]放入q。这样dis+w[i]和原有w[i]不再交叉,第二天只要考虑w[i]进行计算。

C++
#include<bits/stdc++.h>

using namespace std;

#define int long long
#define endl '\n'
#define pii pair<int, int>
#define deb(n) cout << #n << "=" << n << "    "
#define debug(n) cout << #n << "=" << n << endl
#define div() cout << "_______________" << endl

const int N = 3e5 + 10, M = N * 2;

int n, m;
int h[N], e[M], w[M], ne[M], idx;
int ste[N];
priority_queue<pii, vector<pii>, greater<pii> > q, p;

void add(int a, int b, int c) {
	e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

void oper() {
	cin >> n >> m;
	memset(h, -1, sizeof h); idx = 0;
	for (int i = 1; i <= m; i++) {
		int a, b, c; cin >> a >> b >> c;
		add(a, b, c), add(b, a, c);
	}
	memset(ste, -1, sizeof ste);
	int k; cin >> k;
	for (int i = 1; i <= k; i++) {
		int a; cin >> a;
		ste[a] = 0;
		for (int i = h[a]; ~i; i = ne[i]) q.push({ w[i], e[i] });
	}
	int d; cin >> d;
	for (int day = 1; day <= d; day++) {
		int a; cin >> a;
		while (q.size() && q.top().first <= a) {
			int pre = q.top().second, dis = q.top().first; q.pop();
			if (~ste[pre]) continue;
			p.push({ dis, pre });
		}
		while (p.size()) {
			int pre = p.top().second, dis = p.top().first; p.pop();
			if (~ste[pre]) continue;
			ste[pre] = day;
			for (int i = h[pre]; ~i; i = ne[i]) {
				int to = e[i];
				if (dis + w[i] > a) q.push({ w[i], to });
				else p.push({ dis + w[i], to });
			}
		}
	}
	for (int i = 1; i <= n; i++) cout << ste[i] << endl;
}

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int t = 1; //cin >> t;
	while (t--) oper();
	return 0;
}
原文