luminarae's blog

By luminarae, history, 7 months ago, In English

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.

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
7 months ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

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 months ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

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 months ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Thank you, just a quick question

    • »
      »
      »
      7 months ago, hide # ^ |
       
      Vote: I like it +3 Vote: I do not like it

      As far as I know and understood from attending computer architecture classes, it is due to 2 fact mainly ->1) More Memory Overhead and 2) More Cache Miss.

      In ur case, u r creating a lot of vectors(worst case 200000 or so) but of minimum size(LOG), all of the vectors are scattered around in your computer RAM in different locations so accessing them randomly causes a lot of Cache Miss. But, while creating vector -> if u declare LOG at first, u r creating vectors only LOG times which reduces a lot of cache miss while accessing them randomly.

»
7 months ago, hide # |
 
Vote: I like it +3 Vote: I do not like it
»
7 months ago, hide # |
Rev. 2  
Vote: I like it +3 Vote: I do not like it

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 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

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