recursice vs iterative

Revision en1, by K0DEL, 2023-01-13 12:43:36

I was trying to solve this problem: 1559D1 - Mocha and Diana (Easy Version)

I used the editorial solution for this and just made a small change instead of recursively finding the parent of the node I used an iterative way and it took a lot of time and I want to know why this is happening. The recursive way took 15ms while the iterative way took 764ms.

The editorial submission with recursive method: 189082733 The same submission with iterative method: 189082883

The only difference between the 2 submissions is "getf()" function.

for the recursive approach: int getf(int id, int x){return x == f[id][x] ? x : f[id][x] = getf(id, f[id][x]);}

for the iterative approach: int getf(int id, int x) { while (x != f[id][x]) x = f[id][x]; return x; }

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English K0DEL 2023-01-13 12:43:36 816 Initial revision (published)