zoukankan      html  css  js  c++  java
  • 课内上机实验3——M集合问题(队列)

    题目描述:定义集合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 
    ",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
    ");
    76     }else{
    77         printf("no
    ");
    78     }
    79     return 0;
    80 }

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

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

    二 判断数字是否属于M:

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

  • 相关阅读:
    UDP通信网络编程
    多线程:购票小案例
    多线程:线程池异步计算,2个线程,1个计算10的阶乘,一个计算20的阶乘并返回
    Kong入门指南
    5分钟完成App后端API开发
    Docker安装Kong
    React Native如何用调用RestFul API
    Flutter如何用调用RestFul API
    如何用Flutter调用生成的RestFul API
    自动化API之一 生成开源ERP Odoo App 的RestFul API
  • 原文地址:https://www.cnblogs.com/liuhao-1997/p/4983282.html
Copyright © 2011-2022 走看看