I am trying to solve this problem by running dfs from every node. I am getting TLE verdict. Please help me speed up my solution
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
7 | adamant | 156 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
I am trying to solve this problem by running dfs from every node. I am getting TLE verdict. Please help me speed up my solution
Name |
---|
Hint: Dont dfs from every node.
If you run dfs from the root, you can save the sequence of accessing nodes and calculate the size of each nodes' subtree. Now if ith node's index is in and ith node's size is k, you can find your answer in your sequence from in to in+k.
Did you try to understand the tutorial? If yes, please, tell what part you didn't understand(even if you didn't understand anything).
I got AC :) thanks
I will describe my approach which i believe is a bit easier than the one described in editorial.
First of all we run dfs from an arbitrary node which we set as the root (eg. node 1) and push each node processed from dfs into a set. We can see that this will generate the set from the sample. Now by definition when we have a query {u, k} we are interested in the k-th element in set counting from the index of u in the set. We are now left with calculating whether the answer is -1. We can do this slightly different than the approach described in editorial. For each node we count the number of nodes in it's subtree and now we node that if
#of nodes in u's subtree < k
then answer is -1.My code: 40438205