cf208E. Blood Cousins
题意:
给你一个森林,m次询问,每次询问(v,p),问v的p-cousin有多少?p-cousin指的是与v在同一层且他们到lca的距离都是p
题解:
对于每次询问(v,p),我们都可以通过其找到v的p距离的父亲节点fa,然后去找以fa为根节点,到fa的距离为p的节点的数量,然后更新答案。用树上启发式合并来实现
答案就是fa的子树中,深度为dep[fa]+p-1(减1是将v本身减去)
代码:
// Problem: E. Blood Cousins
// Contest: Codeforces - Codeforces Round #130 (Div. 2)
// URL: https://codeforces.com/contest/208/problem/E
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// Data:2021-09-02 16:39:57
// By Jozky#include <bits/stdc++.h>
#include <unordered_map>
#define debug(a, b) printf("%s = %d\n", a, b);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
clock_t startTime, endTime;
//Fe~Jozky
const ll INF_ll= 1e18;
const int INF_int= 0x3f3f3f3f;
void read(){};
template <typename _Tp, typename... _Tps> void read(_Tp& x, _Tps&... Ar)
{x= 0;char c= getchar();bool flag= 0;while (c < '0' || c > '9')flag|= (c == '-'), c= getchar();while (c >= '0' && c <= '9')x= (x << 3) + (x << 1) + (c ^ 48), c= getchar();if (flag)x= -x;read(Ar...);
}
template <typename T> inline void write(T x)
{if (x < 0) {x= ~(x - 1);putchar('-');}if (x > 9)write(x / 10);putchar(x % 10 + '0');
}
void rd_test()
{
#ifdef LOCALstartTime= clock();freopen("in.txt", "r", stdin);
#endif
}
void Time_test()
{
#ifdef LOCALendTime= clock();printf("\nRun Time:%lfs\n", (double)(endTime - startTime) / CLOCKS_PER_SEC);
#endif
}
int n;
const int maxn= 3e5 + 9;
int a[maxn];
vector<int> vec[maxn];
vector<PII> q[maxn];
int siz[maxn], son[maxn];
int Son;
int dep[maxn];
int f[maxn][30];
void dfs1(int u, int fa)
{siz[u]= 1;dep[u]= dep[fa] + 1;f[u][0]= fa;for (int i= 1; i <= 18; i++)f[u][i]= f[f[u][i - 1]][i - 1];for (auto v : vec[u]) {if (v == fa)continue;dfs1(v, u);siz[u]+= siz[v];if (siz[v] > siz[son[u]])son[u]= v;}
}
ll sum[maxn];
int num[maxn];
void add(int u, int fa, int val)
{num[dep[u]]+= val;for (auto v : vec[u]) {if (v == fa || v == Son)continue;add(v, u, val);}
}
void dfs2(int u, int fa, int keep)
{for (auto v : vec[u]) {if (v == fa || v == son[u])continue;dfs2(v, u, 0);}if (son[u]) {dfs2(son[u], u, 1);Son= son[u];}add(u, fa, 1);for (auto it : q[u]) { //更新答案int v= it.first;int id= it.second;sum[id]= max(0, num[v + dep[u]] - 1);}Son= 0;if (!keep) {add(u, fa, -1);}
}
int k_th(int u, int k)
{for (int i= 0; i <= 18; i++) {if ((1 << i) & k)u= f[u][i];}return u;
}
int main()
{//rd_test();read(n);for (int i= 1; i <= n; i++) {int x;read(x);vec[x].push_back(i);vec[i].push_back(x);}int m;read(m);dfs1(0, 0);for (int i= 1; i <= m; i++) {int v, p;read(v, p);int fa= k_th(v, p);// printf("fa=%d\n",fa);// cout << "fa=" << fa << endl;if (fa == 0)continue;q[fa].push_back({p, i});}dfs2(0, 0, 0);for (int i= 1; i <= m; i++)printf("%d ", sum[i]);//Time_test();
}