Data structure--monotone stack--Beacon

Jingdong written test programming questions: Parllay, dynamic programming solution | Hexo

https://www.nowcoder.com/discuss/8704?type=0&order=0&pos=5&page=0

The crucial part of the war game is coming. This time the outcome will decide the life and death of the kingdom. Little B is responsible for the defense of the capital. The capital is located in a basin surrounded by mountains, and the surrounding n hills form a ring. As an early warning measure, Little B plans to set up an observation post on each hill to keep an eye on the surrounding situation day and night.
In the event of an invasion by foreign enemies, the sentry on the top of the mountain will light the beacon. If the peaks where the two sentries are located are not blocked by a higher peak and there is a connecting path between the two, the sentry can observe whether the beacon smoke on the other mountain is lit. Since the hill is on the ring, there are two different connecting paths between any two hills. Under the above conditions of not being blocked, the beacon smoke lit by the sentry post on a mountain can be observed at the other end through at least one passage. For any adjacent sentry, the sentry at one end must be able to find the beacon smoke lit at one end.
An important feature of this defense scheme designed by Xiao B is the ability to observe the number of sentry pairs of the opponent's beacon smoke. She hopes that you can help her solve this problem. Input
There are multiple sets of test data in the input.
The first line of each set of test data is an integer n (3<=n <=10^6), which is the number of hills around the capital, and the second line is n integers, which in turn represent the height h of the hills, (1<=h< =10^9).
Output
For each set of test data, output the logarithm of the observed sentinels in a separate line.
Sample Input
5
1 2 4 5 3
Sample Output
7
 
 
Using a monotonic stack, use the bottom of the stack to the top of the stack from large to small, record the height of the peak and the number of occurrences, start the stack from a maximum value of the ring, and then start recording
In the stack structure shown in the figure, there are k 5s, m 4s, and n 3s. When the next 5 is encountered,
3 pops the stack, the logarithm of the peaks is C n 2   + n * 2
4 out of the stack, the logarithm of the peak is C m +m * 2
The number of occurrences of 5 is given by k -> k + 1
When m=1, that is, it occurs only once, it is 2 pairs
 
After the loop is traversed, there are still k 5s, m 4s, and n 3s in the stack.
Then the settlement rule for the penultimate 3, 4, 5..... is still C n 2   + n * 2
How many pairs are there in the penultimate record, first consider how many (k) there are in the penultimate record,
  When k>1, C n 2   + n * 2,
  When k=1, it is C n 2   + n * 1,
 Penultimate record: C n 2

 

 
 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325220244&siteId=291194637