首页 > 其他 > 详细

队列初步

时间:2015-11-21 13:09:31      阅读:239      评论:0      收藏:0      [点我收藏+]

题目描述:定义集合M

1属于M

若x属于M,则2x+1属于M,3x+1属于M

没有其他数字属于M

由小到大输出M中前30项,并且输入一个数字,判断它是否属于M

代码如下:

 1 #include <stdio.h>
 2 int a[1000],b[1000];
 3 int t=0;//t point at first empty element
 4 int count=0;
 5 void push_queue(int num)//
 6 {
 7     a[t]=num;
 8     int i,temp;
 9     for(i=t-1;(i>=0)&&(a[i]>num);i--)
10     {
11         temp=a[i];
12         a[i]=a[i+1];
13         a[i+1]=temp;
14     }
15     
16     t++;
17     
18 }//
19 void pop_queue()//
20 {
21     int flag=1;
22     for (int i=0; i<count; i++) {
23         if (a[0]==b[i]) {
24             flag=0;
25         }
26     }
27     if (flag) {
28         if (count < 30) {
29             printf("%d \n",a[0]);
30         }
31         b[count]=a[0];
32         count++;
33     }
34     for(int k=1;k<=t;k++)
35     {
36         a[k-1]=a[k];
37     }
38     a[t]=0;
39     t--;
40 }//
41 int check(int n)
42 {
43     for (int i = 0; i < 30; i++) {
44         if (n == b[i]) {
45             return 1;
46         }
47     }
48     while (n >= b[count-1]) {
49         push_queue(2*a[0]+1);
50         push_queue(3*a[0]+1);
51         pop_queue();
52         if (n == a[0]) {
53             return 1;
54         }
55     }
56     return 0;
57 }
58 int main(int argc, const char * argv[])
59 {
60     for(int m=0;m<100;m++)
61         a[m]=0;
62     for (int n=0; n<30; n++) {
63         b[n]=0;
64     }
65     push_queue(1);
66     for(int n=0;count<30;n++)
67     {
68         push_queue(2*a[0]+1);
69         push_queue(3*a[0]+1);
70         pop_queue();
71     }
72     int number;
73     scanf("%d",&number);
74     if(check(number)){
75         printf("yes\n");
76     }else{
77         printf("no\n");
78     }
79     return 0;
80 }

一 “生孩子”的方式输出:

出队口设为a[0],入队口是a[t],如果有元素要出队列,则必须留下它的两个孩子(即2x+1和3x+1)送入队列,并通过插入排序使两个孩子插入到合适位置,方便输出

二 判断数字是否属于M:

继续进行出队入队操作,并把所有出队的元素记录到另一个记录数组中,检索记录数组,来判断数字是否属于M

队列初步

原文:http://www.cnblogs.com/liuhao-1997/p/4983282.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!