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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 160 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 151 |
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