I just need some very basic hints.
I am thinking of topological sort + BFS to start. What do you say? (No spoilers plz)
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 156 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
I just need some very basic hints.
I am thinking of topological sort + BFS to start. What do you say? (No spoilers plz)
Название |
---|
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 know ans[u] then what happens to ans[v] if v is a child/parent of u. There isn't too much difference between ans[u] and ans[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.
but some judges have insanely tight time limits, maybe it will not be fast enough still
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.
I thought about advancement in this question. What if instead of a tree it is a connected graph with cycles allowed? 1<=N<=200000
Any help would be helpful?
The sum of depth of node is equal to the sum of subtree size of node.
so you maybe just need to use change root DP to solve it in $$$O(n)$$$.