天天爱跑步
题目链接:luogu P1600
题目大意
有一棵树,给你若干条路径,对于每个点,有一个数 x,求出有多少条路径的第 x 个点是当前点。
思路
考虑把路径拆成两个部分,向上和向下。
考虑对于每个点建一个权值线段树,用深度为下标,记录这样的路径有多少个。(因为向上和向下每个点需要的深度其实是固定的)
(向下的话它可能是先上来在下去的所以我们可以翻折一下把它折到上面的深度即可)
然后至于怎么维护线段树我们可以差分一下,然后就可以用线段树合并来维护这 \(n\) 个线段树了。
(你可以可以直接在每个点记录着修改,然后 dfs 下去用两个桶记录,都可以)
代码
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 3e5 + 1000;
struct node {
int to, nxt;
}e[N << 1];
int n, m, w[N], le[N], KK, ans[N];
int deg[N], fa[N][21];
void add(int x, int y) {
e[++KK] = (node){y, le[x]}; le[x] = KK;
}
void dfs(int now, int father) {
deg[now] = deg[father] + 1;
fa[now][0] = father;
for (int i = 1; i <= 20; i++) fa[now][i] = fa[fa[now][i - 1]][i - 1];
for (int i = le[now]; i; i = e[i].nxt)
if (e[i].to != father) dfs(e[i].to, now);
}
int LCA(int x, int y) {
if (deg[x] < deg[y]) swap(x, y);
for (int i = 20; i >= 0; i--)
if (deg[fa[x][i]] >= deg[y]) x = fa[x][i];
if (x == y) return x;
for (int i = 20; i >= 0; i--)
if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
struct XD_tree {
int rt[N];
int f[N << 6], ls[N << 6], rs[N << 6], tot;
void insert(int &now, int l, int r, int pl, int x) {
if (!now) now = ++tot;
f[now] += x;
if (l == r) return ;
int mid = (l + r) >> 1;
if (pl <= mid) insert(ls[now], l, mid, pl, x);
else insert(rs[now], mid + 1, r, pl, x);
}
int merge(int a, int b, int l, int r) {
if (!a || !b) return a + b;
if (l == r) {f[a] += f[b]; return a;}
int mid = (l + r) >> 1;
ls[a] = merge(ls[a], ls[b], l, mid);
rs[a] = merge(rs[a], rs[b], mid + 1, r);
return a;
}
int query(int now, int l, int r, int pl) {
if (!now) return 0;
if (l == r) return f[now];
int mid = (l + r) >> 1;
if (pl <= mid) return query(ls[now], l, mid, pl);
else return query(rs[now], mid + 1, r, pl);
}
}T1, T2;
void dfs1(int now, int father) {
if (now == 80) {
now++; now--;
}
for (int i = le[now]; i; i = e[i].nxt)
if (e[i].to != father) {
dfs1(e[i].to, now);
T1.rt[now] = T1.merge(T1.rt[now], T1.rt[e[i].to], -n, n);
T2.rt[now] = T2.merge(T2.rt[now], T2.rt[e[i].to], -n, n);
}
if (deg[now] + w[now] <= n) ans[now] += T1.query(T1.rt[now], -n, n, deg[now] + w[now]);
if (deg[now] - w[now] >= -n) ans[now] += T2.query(T2.rt[now], -n, n, deg[now] - w[now]);
}
int main() {
// freopen("P1600.in", "r", stdin);
// freopen("P1600.ans", "w", stdout);
scanf("%d %d", &n, &m);
for (int i = 1; i < n; i++) {
int x, y; scanf("%d %d", &x, &y);
add(x, y); add(y, x);
}
for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
dfs(1, 0);
for (int i = 1; i <= m; i++) {
int x, y; scanf("%d %d", &x, &y); int lca = LCA(x, y);
T1.insert(T1.rt[x], -n, n, deg[x], 1);
T1.insert(T1.rt[lca], -n, n, deg[x], -1);
T2.insert(T2.rt[y], -n, n, deg[lca] * 2 - deg[x], 1);
T2.insert(T2.rt[fa[lca][0]], -n, n, deg[lca] * 2 - deg[x], -1);
}
dfs1(1, 0);
for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
return 0;
}
标签:return,int,luogu,线段,fa,LCA,P1600,now
From: https://www.cnblogs.com/Sakura-TJH/p/luogu_P1600.html