We have a tree with n(n < 1e5) nodes and we have a constant k(k < 1e5) can we store the k'th ancestor of all nodes in an array or there is no way to do that??? Thank you for helping :)

Before contest

Codeforces Round #512 (Div. 1, based on Technocup 2019 Elimination Round 1)

13:14:22

Register now »

Codeforces Round #512 (Div. 1, based on Technocup 2019 Elimination Round 1)

13:14:22

Register now »

*has extra registration

Before contest

Codeforces Round #512 (Div. 2, based on Technocup 2019 Elimination Round 1)

13:14:22

Register now »

Codeforces Round #512 (Div. 2, based on Technocup 2019 Elimination Round 1)

13:14:22

Register now »

*has extra registration

# | User | Rating |
---|---|---|

1 | tourist | 3509 |

2 | OO0OOO00O0OOO0O0…O | 3327 |

3 | Syloviaely | 3274 |

4 | Um_nik | 3237 |

5 | Petr | 3161 |

6 | ko_osaga | 3154 |

7 | LHiC | 3135 |

8 | Benq | 3130 |

9 | Swistakk | 3089 |

10 | dotorya | 3060 |

# | User | Contrib. |
---|---|---|

1 | Radewoosh | 185 |

2 | rng_58 | 161 |

3 | tourist | 158 |

4 | Petr | 152 |

5 | Vovuh | 150 |

5 | Swistakk | 150 |

7 | PikMike | 147 |

8 | csacademy | 146 |

9 | Errichto | 145 |

9 | Um_nik | 145 |

We have a tree with n(n < 1e5) nodes and we have a constant k(k < 1e5) can we store the k'th ancestor of all nodes in an array or there is no way to do that??? Thank you for helping :)

↑

↓

Codeforces (c) Copyright 2010-2018 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Sep/23/2018 02:50:38 (f1).

Desktop version, switch to mobile version.

User lists

Name |
---|

easiest way is binary lifting to kth parent using sparse table (similar to lca).

space complexity:O(nlogn)

Complexity:O(nlogn)

Hi teja349 how can I do the binary search in O(logn)? I already know it in O(logn*logn) because I know the kth parent in O(logn) plus the binary search

let's say that

khas the following binary representation: 0011010This means that you need to climb up (2

^{1}= 2 nodes) + (2^{3}= 8 nodes) + (2^{4}= 16 nodes), the order doesn't matterTo do this you can loop over the bits of

kand if thei^{th}bit set, go up 2^{i}nodesSince we have

O(log_{2}(n)) bits, we go up by a power of two and we doO(1) work on the sparse table, the overall complexity isO(log_{2}(n))You can solve in O(N) by maintaining an explicit dfs stack in a vector as you dfs from the root. From each node you then look at the kth last thing in the vector if it exists.

I think this is actually much easier than using a sparse stable (although sparse tables can be easily extended to non constant k-th ancestor queries)