题解:P5292 [HNOI2019] 校园旅行
怎么都是
首先注意到一个显然的 dp:
注意到以上的复杂度是
发现每次我们需要枚举
再维护一个
上面的复杂度被我们优化到了
然后发现上面的运算非常简单,使用 bitset 优化,就可以了。
#include <bits/stdc++.h>
using namespace std;
namespace {
constexpr int N = 5010;
int n, m, q, co[N];
bitset<N> f[N], g[N], a[N][3], res;
vector<int> e[N];
void entry() {
freopen("tour.in", "r", stdin);
freopen("tour.out", "w", stdout);
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i++) {
scanf("%1d", &co[i]);
f[i].set(), g[i].set();
}
for (int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
a[u][2].set(v), a[v][2].set(u);
a[u][co[v]].set(v), a[v][co[u]].set(u);
e[u].push_back(v);
e[v].push_back(u);
}
queue<pair<pair<int, int>, int>> que;
for (int i = 1; i <= n; i++) {
f[i].reset(i);
que.push({{i, i}, 0});
for (int j : e[i]) if (j > i && co[i] == co[j]) {
f[i].reset(j), f[j].reset(i);
que.push({{i, j}, 0});
}
}
while (!que.empty()) {
int u = que.front().first.first, v = que.front().first.second, t = que.front().second;
que.pop();
if (t == 0) {
// a[u][x] = 1 && g[v][x] = 1 的需要揪出来
res = a[u][2] & g[v];
for (int x = res._Find_first(); x <= n; x = res._Find_next(x)) {
g[v].reset(x);
que.push({{x, v}, 1});
}
} else {
// a[v][x] = 1 && f[u][x] = 1 && co[x] == co[u] 的需要揪出来
res = a[v][co[u]] & f[u];
for (int x = res._Find_first(); x <= n; x = res._Find_next(x)) {
f[u].reset(x), f[x].reset(u);
que.push({{u, x}, 0});
}
}
}
for (int i = 1; i <= q; i++) {
int u, v;
scanf("%d%d", &u, &v);
if (!f[u][v]) printf("YES\n");
else printf("NO\n");
}
}
}
int main() { entry(); }