Description-Problem description
The definition of set M is as follows:
- 1 is the element in M
- If x is an element in M, then both 2x+1 and 4x+5 are elements in M
So, what is the minimum number of n in the set m?
Input-Enter data
An integer n (1<=n<=100 000)
Output-outputs data
n a small to large integer, separated by a space.
A careful analysis can infer that the last number of outputs required must be monotonically increasing. At the time to do this problem, next to the Gxy classmate directly from 1 to start the violent enumeration of all the odd (2x+1 and 4x+5 must be an odd number), and then determine whether the preceding numbers constitute a 2x+1 or 4x+5 relationship, yes, the output, otherwise continue, In this way, the complexity of the algorithm reached O (n^2), and finally there is a point can not pass. So, is there a better way?
In fact, the monotone increment from the front can be known: if we use an array to hold the number of the output, then this array must be the number that the 2x+1 produces and 4x+5. So it's clear. As long as we define a queue to hold the number generated by 2x+1, a B queue is used to save the number of 4x+5. Each time you compare the head of a with the opponent of B, there are 3 cases: (a) A to >b (B) A to head to =b (C) A to the head of the head at this point only need to send the smaller person X to perform the next 2x+1 and 4x+5, but also do not forget the X output. After a multi-party verification, I was able to know that this is the idea of using a monotonous queue, the following gives the definition of Baidu to help everyone understand: monotonous queue, that is, monotonous queue. The usage frequency is not high, but in some programs will have the unusual function. (It's probably something like this sort of topic.)
ExampleUse a question to illustrate the function and operation of the monotone queue: constantly reading elements into the cache array, and occasionally removing the oldest elements, and periodically asking the smallest elements in the current cache array. The most straightforward method: The normal queue implements the cache array. Incoming teams are all O (1), one query needs to traverse all the elements of the current queue, so O (n). Well, here's the code, for reference only:
1#include <iostream>2 using namespacestd;3 Const intmaxn=1000000+Ten;4 intA[MAXN],B[MAXN];5 intx=1, n,total=1;6 intfront1=1, front2=1, tail1=0, tail2=0;7 intMain ()8 {9Cin>>N;Ten while(total<=N) One { A if(total==N) -cout<<x; - Else thecout<<x<<' '; - -tail1++; -a[tail1]=2*x+1; + -tail2++; +b[tail2]=4*x+5; A at if(a[front1]>B[front2]) - { -x=B[front2]; -front2++; - - } in Else - { to if(a[front2]<B[front2]) + { -x=A[front1]; thefront1++; * } $ ElsePanax Notoginseng { -x=A[front1]; thefront1++; +front2++; A } the } +total++; - } $ return 0; $}
Finally, we welcome your advice.
The detailed solution of yzoi2223 set construction