题解:P17195 [KOI 2026 #2] 游戏
题目大意
给定一个
思路
正难则反。
考虑从所有有出口的点出发进行搜索,用数组记录每个点是否一定能够到达出口。
可以注意到如下性质:若一个点的所有能一定到达出口的邻点与该点相连的边的边权之和不小于
证明:若 Alice 当前位于该点,她可以选择这些邻边(边权之和不小于
这一过程可以用 BFS 实现。用
while (head <= tail) {
int tot = 0;
for (int l = head; l <= tail; l++) {
int u = q[l];
for (auto [v, w] : edge[u]) {
cnt[v] += w;
if (cnt[v] >= k && !vis[v]) {
vis[v] = 1;
tot++;
q[tail + tot] = v;
}
}
}
head = tail + 1;
tail += tot;
}
其中
每次询问都需要重新计算
分析上述代码可以发现,单次 BFS 的时间复杂度
由于每次询问的 pair 和优先队列来维护点和
给出核心代码:
while (!pq.empty()) {
auto [g, u] = pq.top();
pq.pop();
if (vis[u]) continue;
vis[u] = 1;
for (auto [v, w] : e[u]) {
if (vis[v]) continue;
sum[v] += w;
int nd = min(g, sum[v]);
if (nd > d[v]) {
d[v] = nd;
pq.push({nd, v});
}
}
}
最后对于每个询问,只需判断
此算法中每个点至多入队、出队一次。由于是离线预处理,这部分时间复杂度与
完整代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define N 200005
#define INF 1000000000000000001LL
int n, m, q;
int a[N], d[N], sum[N];
bool vis[N];
vector<pair<int, int>> e[N];
priority_queue<pair<int, int>> pq;
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m >> q;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) {
int x, y, z;
cin >> x >> y >> z;
e[x].push_back({y, z});
e[y].push_back({x, z});
}
for (int i = 1; i <= n; i++) d[i] = -1;
for (int i = 1; i <= n; i++) {
if (a[i]) {
d[i] = INF;
pq.push({INF, i});
}
}
while (!pq.empty()) {
auto [g, u] = pq.top();
pq.pop();
if (vis[u]) continue;
vis[u] = 1;
for (auto [v, w] : e[u]) {
if (vis[v]) continue;
sum[v] += w;
int nd = min(g, sum[v]);
if (nd > d[v]) {
d[v] = nd;
pq.push({nd, v});
}
}
}
while (q--) {
int s, k;
cin >> s >> k;
cout << (d[s] >= k ? "YES\n" : "NO\n");
}
return 0;
}
后记 & 注意事项
- 本题的
k 可能非常大,建议使用long long类型存储,详见题目限制条件。 - 作者在机房写这篇题解时电脑突然死机,草稿未保存,故在此提醒大家写题解时记得及时保存。
AI 使用说明:本文在写作完成后使用 DeepSeek 进行了文字润色与格式校对。