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 | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 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