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

Автор K0DEL, история, 4 года назад, По-английски

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; }

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

»
4 года назад, скрыть # |
 
Проголосовать: нравится -6 Проголосовать: не нравится

Dude, u not deserve yellow color with such obvious questions.

»
4 года назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

You use path compression like in DSU in the recursive approach, where as in the second approach you don't compress paths at all. I.e. if you want to get equavilent solution you should have written the following:

return x == f[id][x] ? x : getf(id, f[id][x]);

The result: 189085171

»
4 года назад, скрыть # |
 
Проголосовать: нравится -25 Проголосовать: не нравится

Hello I am a very beautiful girl

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

Here's one (probably bad) way to replicate what the recursive code is doing iteratively: https://codeforces.me/contest/1559/submission/189085433

In your submissions, iterative isn't updating the f[id][x] at all. So if you make another query with the same arguments, it will run the same loop again. In recursive one, the loop will run only the first time.