Блог пользователя luminarae

Автор luminarae, история, 7 месяцев назад, По-английски

Hello Codeforces Community, I was recently trying to solve this problem on CSES

Following is my approach and code. Approach — Find LCA using Binary Lifting and then compute distance of a to b by doing the following depth[a] + depth[b] — 2 * depth[lca(a, b)].

Link to my code

But I am continuously getting TLE on test 6 and 7(this is not a meme, I am really having difficulty). Can someone help me with what exactly the issue is out here? Is it some large constant factor or smth else. Any help is appreciated.

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
7 месяцев назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

I remember also getting time limit on this problem, which was fixed by switching the indexing of my binary lifting array for better cache efficiency. I can't look up my old solution right now, but maybe swapping your binary lifting indexing from [vertex][height] to [height][vertex] helps.

»
7 месяцев назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

vector<vector<int>> binl(n, vector<int>(LOG));

The above line is the issue. Change the position of the vector, it would faster ur code. While Allocating 2d vector or 2d array, make the 1st array size to be of smaller size than the second. For ur case, LOG is smaller so it should be the first array size and the vector declaration should be like this -> . vector<vector<int>> binl(LOG, vector<int>(n));

»
7 месяцев назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится
»
7 месяцев назад, скрыть # |
Rev. 2  
Проголосовать: нравится +3 Проголосовать: не нравится

Must've been the i3-7100U

...Did you know there's a linear time solution?

A simple, $$$O(n\alpha(n))$$$ solution can be found here: https://cp-algorithms.com/graph/lca_tarjan.html

»
7 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by luminarae (previous revision, new revision, compare).