Monotonous queue, as the name implies is the team elements are monotonous queue, they can be monotonically increment, can also be monotonically decreasing, monotone queue has important application.
Familiarize yourself with the monotonous queue with several classic topics:
1. Collection
If a number x is in the collection, then 2x+1,3x+1 is also in the collection, known as Start 1, in the collection, to find the number of the nth largest.
Analysis: If the simple way to deal with large data, you can maintain three monotone increment queue, a queue to save the set of number A, the other two queues are saved by 2x+1 and 3x+1 generated number, named P,q, each time by a squadron first generated two number, respectively into the P,q, p, Q Team first element comparison, small elements into a team at the same time corresponding to the queue team first pointer back, know a in the number of N, time efficiency O (n).
2. Merging fruits
n heap of fruit, each time 22 merges, the combined cost is the sum of the combined two piles of fruit, all combined into a pile of the minimum cost.
Analysis: Sort all the heaps by the number of fruits from small to large, and then maintain two monotonically increasing queues, a, a, representing the pre-save values and the merged new values, respectively. Each merger compares the sum of the first two elements of Team A, the sum of the first two elements of Team B, the sum of the first elements of the two teams, select the minimum value in B and move with a A, a, and finally when there is only one value in B end, time efficiency O (n), but also with the sorting time, the total efficiency is O (Nlog (n) +n).
3. Sliding window
The number of n is ranked in a column, and the minimum and maximum values in each interval of k are obtained.
Analysis: For the minimum value, maintain a monotone increment sequence, at the same time to record each element of the team into the team time, according to the Order of reading to select the number to be added, each time the team tail elements and the elements to be added, if the team tail element is larger then the team tail pointer minus the team tail, until the tail element is less than the number Elements into the team, if the first element of the team from join to the present time exceeds the K, the team first pointer plus one, because each time a number into the queue, can guarantee that the next number in the current time not more than K, so out of time the team first pointer as long as a can, due to monotonicity, each team first element for the interval minimum, Just maintenance is a monotonically decreasing sequence. Each number of teams out of the team once, time efficiency is O (n) level.
Application of monotone queue