跳到正文

题解

AT_abc307_f

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

文章信息

发布
2023年6月27日
收录
2025年12月12日
更新
2026年11月7日
篇幅
约 2 分钟
获赞
17

版本

  1. v1当前

每次实际上是做一个多源最短路。

唯一的问题是,如果我们维护源点,最坏情况是每次扫描 O(n)\mathcal O(n) 个点,时间复杂度为 O(nd)\mathcal O(nd)。

考虑维护所有已被传染的点和未被传染的点之间的边,每次只需要从 ≤xi\le x_i 的边对应的未被传染的点开始做多源最短路即可。由于所有边至多被扫描一次,这部分时间复杂度为 O(m)\mathcal O(m)。

C++
int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<pi>> e(n + 1);
    for (int i = 1; i <= m; i++) {
        int x, y, z;
        cin >> x >> y >> z;
        e[x].pb(mp(y, z));
        e[y].pb(mp(x, z));
    }
    int k;
    cin >> k;
    vi d(n + 1, -1);
    pq<pi> q;
    for (int i = 1; i <= k; i++) {
        int x;
        cin >> x;
        d[x] = 0;
        for (auto o : e[x])
            q.push(mp(-o.se, o.fi));
    }
    cin >> k;
    for (int t = 1; t <= k; t++) {
        int w;
        cin >> w;
		pq<pi> p;
        while (q.size() && -q.top().fi <= w) {
            int x = q.top().se, r = w + q.top().fi;
            q.pop();
            if (~d[x]) continue;
			p.push(mp(r, x));
        }
		while (p.size()) {
			int x = p.top().se, r = p.top().fi;
			p.pop();
			if (~d[x]) continue;
			d[x] = t;
			for (auto o : e[x]) {
				int y = o.fi, z = o.se;
				if (z > r) q.push(mp(-z, y));
				else p.push(mp(r - z, y));
			}
		}
    }
	for (int i = 1; i <= n; i++) cout << d[i] << endl;
	return 0;
}
原文
存档评论6 条抓取于