THIS PROBLEM CAN BE SOLVED IN MAY WAYS
1-> MO
2-> NORMAL DFS AND EACH NODE WILL CONTAIN A MAP
2 ND METHOD IS VERY INTERESTING AND OFTEN I CONFUSED HOW ITS WORKING IN THE TIME LIMIT AND , HOW MUCH MEMORIES IT NEEDED ..
SO FIRST OF DISCUSS THE SECOND APPROACH
The name of this problem is anagram for ''Small to large''. There is a reason for that :-) The author solution for this problem uses the classic technique for computing sets in tree. The simple solution is the following: let's find for each vertex v the ''map<int, int>'' — the number of occurences for each colour, ''set<pair<int, int>>'' — pairs the number of occurences and the colour, and the number sum — the sum of most frequent colours in subtree of v. To find that firstly we should find the same thing for all childs of v and then merge them to one. These solution is correct but too slow (it works in O(n2logn) time). Let's improve that solution: every time when we want to merge two map-s a and b let's merge the smaller one to larger simply by iterating over all elements of the smaller one (this is the ``Small to large''). Let's consider some vertex v: every time when vertex v will be moved from one map to another the size of the new map will be at least two times larger. So each vertex can be moved not over than logn times. Each moving can be done in O(logn)time. If we accumulate that values by all vertices then we get the complexity O(nlog2n).
I saw the solutions that differs from author's but this technique can be used in a lot of other problems.
No comments:
Post a Comment