Ruler method is actually a very simple algorithm, thought has been used, but has not known. These two days happened to do two questions about the ruler, just to summarize.
First, what is a ruler? The ruler method usually refers to the array to save a pair of subscript (starting point, focus), and then according to the actual situation of alternating two end points to arrive at the answer, because this method like the crawling way of the worm is named. In fact, it is to ask for an interval problem on a linear array. Because only the two endpoints of the interval are changed, the middle part does not need maintenance updates, as long as the two ends can be maintained. Can greatly reduce the complexity.
Example one: poj3061 given an integer sequence of length n and an integer s, the minimum value of the length of a continuous subsequence with a sum not less than S is obtained, if the solution does not exist, the output is 0.
Solution One: (1) s=t=sum=0 initialization
(2) As long as the sum<s, will continue to increase the sum of a (t), and add T 1
(3) If the sum>=s is not met in (2), then the ANS is updated to min (ans,t-s).
(4) The sum is subtracted by a (s), and S is increased by 1 to return to (2)
This is actually a typical ruler, when we get sum>=s and then subtract a (s) it will be less than S is equivalent to re-determine the starting point, the same, but also to determine the end point, and because the new area and the original interval has a large part overlap, so directly to sum to add and subtract on it, No recalculation is required.
Example two: Give a string of beads, there are 2n, of which there are black and white beads each N, black counter-clockwise number, white clockwise numbering, white black random arrangement, to find a length of the interval of n, requires the number of beads within the range of 1-n (not necessarily from small to large or from large to small appearance, as long as 1-n can be) (Thank God for the quiz!) ) data range 10 million.
Solution Two: Because the data range is very large, it must be solved by O (n) method. We first put the beads into a number, and then find a starting point, looking backwards for n beads, record each number of beads each have a few and a total number of beads appeared. Then we take the beads out of the head, add the n+1 beads, repeat the process until we have n numbered beads and we find a legal interval. This is also a ruler method, the middle n-2 a bead we do not need to tube, just take out and add the head and tail beads on the line. This interval can be easily identified by enumerating N starting points.
Summary: Overall ruler method of the idea is very good understanding, code difficulty is not high, in the NOIP exam is suitable, some problems can be convenient to solve, personal feeling should master.
Application of the ruler extraction