题目链接
题意:
一棵
n
n
个节点的数,每个节点有一个权值,回答次询问,每次询问给你一对
(u,v)
(
u
,
v
)
,问
u
u
到的简单路径上不同点权的数目。
思路:
树上无修改莫队, 跑出
dfs
d
f
s
序列后直接分块, 类似普通序列处理, 确定询问区间, 然后离线处理一下就行了。
#include<bits/stdc++.h>
typedef long long ll;
const int maxn = 1e5 + 10;
const int block_size = 400;
using namespace std;
struct opr {
int id, l, r, lca;
opr() {}
opr(int id, int l, int r, int lca) : id(id), l(l), r(r), lca(lca) {}
bool operator < (opr p) const {
if(l / block_size != p.l / block_size) return l / block_size < p.l / block_size;
return r < p.r;
}
} rec[maxn];
int n, m, T, kase = 1;
vector<int> G[maxn];
int vis[maxn], tot[maxn], number;
int val[maxn], ans[maxn], now_ans;
int l[maxn], r[maxn], dfn[maxn], cnt;
int deep[maxn], anc[maxn][18], cal[maxn];
void init() {
cnt = 1; number = 0; now_ans = 0;
for(int i = 0; i < maxn; i++) {
vis[i] = cal[i] = 0;
G[i].clear();
for(int j = 0; j < 18; j++) anc[i][j] = -1;
}
}
void dfs(int x, int fa, int d) {
anc[x][0] = fa; deep[x] = d;
dfn[cnt] = x; l[x] = cnt++;
for(int i = 1; i < 18; i++) {
int t = anc[x][i - 1];
if(~t) anc[x][i] = anc[t][i - 1];
}
for(int i = 0; i < G[x].size(); i++) {
int to = G[x][i];
if(to != fa) dfs(to, x, d + 1);
}
dfn[cnt] = x; r[x] = cnt++;
}
int lca(int x, int y) {
if(deep[x] < deep[y]) swap(x, y);
for(int i = 17; i >= 0; i--) {
if(deep[x] - (1 << i) < deep[y]) continue;
x = anc[x][i];
}
if(x == y) return x;
for(int i = 17; i >= 0; i--) {
if(anc[x][i] == anc[y][i]) continue;
x = anc[x][i]; y = anc[y][i];
}
return anc[y][0];
}
void solve_node(int x) {
vis[x] ^= 1;
if(vis[x]) {
cal[val[x]]++;
if(val[x] && cal[val[x]] == 1) now_ans++;
} else {
cal[val[x]]--;
if(val[x] && !cal[val[x]]) now_ans--;
}
}
void solve(int id, int las_l, int las_r, int now_l, int now_r) {
while(las_l < now_l) { solve_node(dfn[las_l]); las_l++; }
while(las_r > now_r) { solve_node(dfn[las_r]); las_r--; }
while(las_l > now_l) { las_l--; solve_node(dfn[las_l]); }
while(las_r < now_r) { las_r++; solve_node(dfn[las_r]); }
ans[id] = now_ans;
}
int main() {
while(scanf("%d %d", &n, &m) != EOF) {
int num = 0; init();
for(int i = 1; i <= n; i++) {
scanf("%d", &val[i]);
tot[number++] = val[i];
}
sort(tot, tot + number);
number = unique(tot, tot + number) - tot;
for(int i = 1; i <= n; i++) val[i] = upper_bound(tot, tot + number, val[i]) - tot;
for(int i = 1; i < n; i++) {
int u, v; scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
cnt = 1; dfs(1, -1, 1);
for(int i = 0; i < m; i++) {
int u, v; scanf("%d %d", &u, &v);
int LCA = lca(u, v);
if(l[u] > l[v]) swap(u, v);
if(LCA == u || LCA == v) rec[num++] = opr(i, l[u], l[v], LCA);
else rec[num++] = opr(i, r[u], l[v], LCA);
}
sort(rec, rec + num);
int las_l = 0, las_r = 0;
for(int i = 0; i < num; i++) {
solve(rec[i].id, las_l, las_r, rec[i].l, rec[i].r);
if(rec[i].lca != dfn[rec[i].l] && rec[i].lca != dfn[rec[i].r]) {
if(!cal[val[rec[i].lca]]) ans[rec[i].id]++;
}
las_l = rec[i].l; las_r = rec[i].r;
}
for(int i = 0; i < m; i++) printf("%d\n", ans[i]);
}
return 0;
}