The first N elements of a set.
The first N elements of the set: compile a program to generate the smallest N number of the Set M in ascending order. The definition of M is as follows: (1) Number 1 belongs to M; (2) if X belongs to M, Y = 2 * x + 1 and Z = 3 * x + 1 also belong to M. (3) No other numbers belong to M. [Analysis] two queues a and B can be used to store the new number, and then the output is determined by comparing the size. The specific method is as follows: (1) make fa and fb the header pointers of queue a and queue B respectively, and their tail pointers are ra and rb respectively. Initially, X = 1, fa = fb = ra = rb = 1; (2) put 2 * x + 1 and 3 * x + 1 at the end of queue a and queue B respectively, and Add 1 to the tail pointer. That is, a [r] records 2 * x + 1, B [r] records 3 * x + 1, r records r + 1; (3) compare the header nodes of queue a and queue B in three possible cases: (A) a [ha]> B [hb] (B) a [ha] = B [hb] (C) a [ha] <B [hb] transfers the smaller ones to X, and Adds 1 to the header pointer of the number of queues. (4) Repeat (2) and (3) until the nth item is retrieved. Non-stl
1 #include<iostream> 2 using namespace std; 3 int a[10001]; 4 int b[10001]; 5 int ha=1,ta; 6 int hb=1,tb; 7 int n; 8 int tot=1; 9 int x=1;10 int main()11 {12 int n;13 cin>>n;14 while(tot<=n)15 {16 cout<<x<<" ";17 ta++;18 tb++;19 a[ta]=2*x+1;20 b[tb]=3*x+1;21 if(a[ha]>b[hb])22 {23 x=b[hb];24 hb++;25 }26 else if(a[ha]<b[hb])27 {28 x=a[ha];29 ha++;30 }31 else32 {33 x=a[ha];34 ha++;35 hb++;36 }37 tot++; 38 }39 //cout<<tot;40 return 0;41 }
Stl:
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 int tot=1; 5 int x=1; 6 int main() 7 { 8 queue<int>a; 9 queue<int>b;10 int n;11 cin>>n;12 while(tot<=n)13 {14 cout<<x<<" ";15 a.push(2*x+1);16 b.push(3*x+1);17 if(a.front()>b.front())18 {19 x=b.front();20 b.pop();21 }22 else if(a.front()<b.front())23 {24 x=a.front();25 a.pop();26 }27 else 28 {29 x=a.front();30 a.pop();31 b.pop();32 }33 tot++;34 }35 return 0;36 }