Editorial for UTS Open '24 P6 - Candygrams
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
This question can be modelled as a graph, with classrooms as nodes and hallways (or tunnels) as edges. Since there are hallways and you can travel between any two classrooms via those hallways, the graph is a tree. Keep track of the number of students in each classroom with an array. For every update event, increment or decrement the counts accordingly. For every query event, temporarily add the tunnel to the graph and run a BFS from classroom to determine the shortest distance from it to every classroom in the school. Then, for every classroom, multiply its distance from classroom by the number of students currently in it, and add up all of these values to determine the total cost of delivering candygrams. Then, remove the tunnel from the graph so as to not affect future query events.
Time Complexity:
Subtask 2
Let's analyze how adding an tunnel from classroom to classroom affects the distances more closely. Denote as the distance from to classroom . Without loss of generality, assume . Then it is never optimal to go from to , since we could just go to directly in less than or equal the same amount of distance. Now, let us consider which classrooms have become closer to classroom by taking advantage of going from to . Any classroom in the subtree of will have their distance reduced by . However, it may also be optimal for some classrooms to travel to , then use the tunnel to go to , travel up the tree, and go down a different subtree.
Let the highest ancestor of whose distance is reduced this way be . In other words, is the highest node which satisfies . Consider the path of nodes from node to node , say, . All the students in 's subtree will have their distance reduce by or depending on the parity of , all the students in 's subtree will have their distance reduce by an additional , all the students in 's will have their distance reduce by an additional , and so on until all the students in 's subtree will have their distance reduce by an additional .
To dynamically maintain the number of students in each node's subtree, and to perform sum queries along the path from to , we can use HLD. Finding node may also require an additional query.
Time Complexity:
Comments