Editorial for COCI '10 Contest 3 #5 Diferencija
Submitting an official solution before solving the problem yourself is a bannable offence.
The key observation follows: instead of calculating the sum of difference values of all contiguous subsequences, we can separately calculate the sum of all maximum values and all minimum values of the subsequences, subtracting the second from the first number to obtain the solution. It is not difficult to show that this approach is correct, since the difference value of a given subsequence is defined as the difference between its maximum and minimum value, thus the observation follows from addition associativity and commutativity. Here we will only describe a method to find the sum of maximum values; the sum of minimum values is obtained with a completely analogous algorithm.
Our approach is as follows: for each element of the provided sequence, we shall compute the number of contiguous subsequences that contain that element as their maximum. In order to resolve ambiguity, we shall define the first out of multiple equal maximal elements as the maximum of a subsequence.
If the position of the current element is
Now we only need an algorithm to find the first element to the left of the current one that is greater than or equal to it (the algorithms to find the first one to the right that is greater, as well as the other combinations for finding minimum values, are completely analogous). We shall traverse the sequence from left to right, keeping a stack of pairs (value, position) containing some previous elements of the sequence. The stack will be kept in decreasing order of the values. Processing of an element with value
Comments