Last active
July 14, 2024 15:03
-
-
Save ajx42/e48d7f652325f92c198b980935e472e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector < vector <int> > adj; | |
int attending[N]; | |
void dfs(int i, int par){ | |
int sm = 0; | |
for(auto j: adj[i]){ | |
if(j == par) | |
continue; | |
dfs(j, i); // call dfs on child node to compute its answer | |
sm += attending[j]; // add to the sum | |
} | |
attending[i] = sm + 1; | |
} | |
int main(){ | |
int n; // # nodes, hopefully n <= N | |
cin >> n; | |
// get the tree input and build the adj list representation | |
for(int i = 0, x, y; i < n; ++i){ | |
cin >> x >> y; | |
adj[x].pb(y); | |
adj[y].pb(x); | |
} | |
// run DFS once to compute all answers O(n) | |
dfs(1, -1); | |
int q; // # queries | |
cin >> q; | |
while(q--){ | |
cin >> m; // member node id | |
cout << attending[m] << endl; // O(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment