CSES Solutions
#1674Tree Algorithms

Subordinates

View on CSES

Solution

1674-Subordinates.cpp
1#include<bits/stdc++.h>
2using namespace std;
3#define int long long
4
5const int N = 2e5+5;
6vector<int> adj[N];
7int sz[N];
8
9void dfs(int i) {
10  sz[i] = 0;
11  for (auto &x : adj[i]) {
12    dfs(x);
13    sz[i] += sz[x] + 1;
14  }
15}
16
17signed main(){
18  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
19
20  int N;
21  cin >> N;
22
23  for (int i = 2; i <= N; ++i) {
24    int e; cin >> e;
25    adj[e].emplace_back(i);
26  }
27   
28  dfs(1);
29  for(int i = 1; i <= N; ++i)
30    cout << sz[i] << " ";
31  cout << '\n';
32  return 0;
33}

Editorial not yet generated for this problem. Run the editorial generation script to add hints and detailed explanations.