I just need some very basic hints.

I am thinking of topological sort + BFS to start. What do you say? (No spoilers plz)

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

1 | tourist | 3372 |

2 | mnbvmar | 3345 |

3 | OO0OOO00O0OOO0O0…O | 3264 |

4 | Radewoosh | 3230 |

5 | scott_wu | 3189 |

6 | Benq | 3187 |

7 | LHiC | 3171 |

8 | Um_nik | 3155 |

9 | V--o_o--V | 3152 |

10 | Petr | 3139 |

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

1 | Radewoosh | 192 |

2 | Errichto | 172 |

3 | rng_58 | 159 |

4 | neal | 156 |

5 | Um_nik | 155 |

6 | tourist | 154 |

7 | PikMike | 151 |

7 | Ashishgup | 151 |

9 | 300iq | 150 |

9 | Petr | 150 |

I just need some very basic hints.

I am thinking of topological sort + BFS to start. What do you say? (No spoilers plz)

↑

↓

Codeforces (c) Copyright 2010-2018 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Nov/13/2018 02:39:56 (d3).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|

Lets say you know the sum of distances from a node. Think about what happens to the sum if you go to a child or to the parent.

Hi, I am not sure I understand your hint.

If I know the sum of distances node X to node Y I am not sure how this helps? Thanks!

He meant that, if for some node

u, you knowans[u] then what happens toans[v] ifvis a child/parent ofu. There isn't too much difference betweenans[u] andans[v], can you figure that out?Just use LCA.

Simple dfs would be much easier and probably faster.

Hmm. That works if he is looking for distance from a single node to the rest of the nodes. What if i is arbitrary?

Just do dfs for all vertices, n^2 should pass for given constraints.

Oh yeah. You are right. I didn't note the small constraints.

but some judges have insanely tight time limits, maybe it will not be fast enough still

Can you help me with DFS approach in O(N)? I am very confused how to do it. Thank you so much

yes, topological sort + bfs can be done, but it's easier and faster to just use a DFS traversal. You can remember, in the recursive function, the depth that you are currently at, and just add that to the answer. When you go to your children, increase the depth argument. This is O(n), so when you do a new traversal for every node, it will be O(n^2).

Can you help me out with this DFS approach? I am trying to understand it properly. Say I do a DFS from Node X to all of its children, then if denote:

DP[x][some child] = DP[some child][x] = distance from X to some Child, which ever child we are looking at.

Are you saying I should then use DP[x][some child] for parents of node X?

Thanks!

I'm saying you don't have to store it in memory.

So, when you do dfs(x, 0); the variable sum will hold the solution for that node, calculated in O(n). Cheers.