fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5. const int MAXN = 100000 + 5;
  6.  
  7. int n;
  8. vector<int> g[MAXN];
  9. ll ans = 0;
  10.  
  11. inline ll f(ll x){ return x*(x+1)/2; }
  12.  
  13. void dfs(int u, set<int>& S, ll& avoid, const ll T){
  14. // insert u
  15. auto it = S.insert(u).first;
  16. auto itL = prev(it);
  17. auto itR = next(it);
  18. int L = *itL, R = *itR;
  19. ll big = R - L - 1;
  20. ll left = u - L - 1;
  21. ll right = R - u - 1;
  22.  
  23. avoid = avoid - f(big) + f(left) + f(right);
  24.  
  25. // contribute of node u
  26. ans += T - avoid;
  27. cout<<u<<" "<<T-avoid<<endl;
  28.  
  29. for(int v : g[u]) dfs(v, S, avoid, T);
  30.  
  31. // erase u (revert)
  32. avoid = avoid - f(left) - f(right) + f(big);
  33. S.erase(it);
  34. }
  35.  
  36. int main(){
  37. ios::sync_with_stdio(false);
  38. cin.tie(nullptr);
  39.  
  40. if(!(cin >> n)) return 0;
  41. for(int i=2;i<=n;i++){
  42. int p; cin >> p;
  43. g[p].push_back(i);
  44. }
  45.  
  46. const ll T = 1LL * n * (n + 1) / 2;
  47.  
  48. set<int> S; // giữ các nhãn tổ tiên đang active
  49. S.insert(0); S.insert(n+1); // lính gác để tính khoảng
  50. ll avoid = f(n); // ban đầu một khoảng trống dài n
  51.  
  52. dfs(1, S, avoid, T);
  53.  
  54. cout << ans << "\n";
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.01s 5828KB
stdin
6
5 5 1 1 4
stdout
1 6
4 15
6 17
5 14
2 17
3 18
87