怎么都是 ?来点 小清新做法。
首先注意到一个显然的 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(); }