1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #include<bits/stdc++.h> #define int long long using namespace std; const int N = 1e6+10; typedef pair<int, int> PII; int n, l, r, sum[N], ans; vector<PII> e[N]; int siz[N], dep[N], top[N], fa[N], son[N]; void dfs1(int u ,int father){ siz[u] = 1; dep[u] = dep[father] + 1; fa[u] = father; for(int i = 0; i < e[u].size(); i++){ int s = e[u][i].first; if(s == fa[u]) continue; dfs1(s, u); siz[u] += siz[s]; if(siz[son[u]] < siz[s]){ son[u] = s; } } } void dfs2(int u ,int t){ top[u] = t; if(son[u] == 0) return; dfs2(son[u], t); for(int i = 0; i < e[u].size(); i++){ int s = e[u][i].first; if(s == fa[u] || s == son[u]) continue; dfs2(s, s); } } int lca(int x, int y){ while(top[x] != top[y]){ if(dep[top[x]] < dep[top[y]]){ swap(x, y); } x = fa[top[x]]; } return dep[x] < dep[y]? x : y; } void cal_sum(int u){ for(int i = 0; i < e[u].size(); i++){ int x = e[u][i].first; if(x == fa[u]) continue; int y = e[u][i].second; sum[x] = sum[u] + y; cal_sum(x); } } signed main() { cin>>n>>l>>r; for(int i = 1,x; i < n; i++){ cin>>x; e[x].push_back({i + 1,1}); e[i+1].push_back({x, 1}); } dfs1(1, 0); dfs2(1, 1); cal_sum(1); for(int i = 1; i <= n; i++){ for(int j = i + 1; j <=n; j++){ int dis = sum[i]+sum[j]-2*sum[lca(i,j)]; if(dis>=l&&dis<=r){ ans+=dis; } } } cout<<ans<<endl; return 0; }
|