循环队列的运用---求K阶斐波那契序列

问题描述:

  试利用循环队列编写k阶斐波那契序列中前n+1项的算法,要求满足:f(n)<=max而f(n+1)>max,其中max为某个约定的常数。(注意:本题所用循环队列的容量仅为K,则在算法执行结束时,留在循环队列中的元素应是所求K阶斐波那契序列中的最后k项)。

问题分析:

 这道题可以这样想,循环队列满时,可继续将元素入队列,覆盖以前的值即可。

代码:

View Code
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define k 8
 4 typedef struct{
 5     int *base;
 6     int front;
 7     int rear;
 8 }queue;
 9 void InitQueue(queue &q){
10     q.base=(int *)malloc(k*sizeof(int));
11     if(!q.base)
12         printf("存储分配失败");//存储分配失败
13     q.front=q.rear=0;
14 }
15 void EnQueue(queue &q,int i)
16 {
17     q.base[q.rear]=i;
18     q.rear=(q.rear+1)%k;
19 }
20 void DeQueue(queue &q,int &i)
21 {
22     i=q.base[q.front];
23     q.front=(q.front+1)%k;
24 }
25 int QueueLength(queue &q)
26 {
27     return (q.rear-q.front+k)%k;
28 }
29 int fun(int m)
30 {
31     if(m==0)
32         return 0;
33     if(m==1)
34         return 1;
35     else
36         return fun(m-1)+fun(m-2);
37 }
38 int main()
39 {
40   queue q;
41   int e;
42   InitQueue(q);
43   int s,j=0,count=0,max;
44   printf("请输入约定的最大数:");
45   scanf("%d",&max);
46   for(int i=0;;i++)
47   {
48       s=fun(i);
49       if(s<=max)
50       {
51           EnQueue(q,s);
52           j=i;
53           ++j;
54           s=fun(j);
55       }
56     if(s>max)
57         break;
58       
59   }
60   int len=QueueLength(q);
61   while(count<len)
62   {
63       DeQueue(q,e);
64      printf("%d\n",e);
65      count++;
66   }
67   return 0;
68 }

总结:
  还好,自己最后发现问题所在解决了。

更正:

#include<stdio.h>
#include<stdlib.h>
#define k 8
typedef struct{
    int *base;
    int front;
    int rear;
}queue;
void InitQueue(queue &q){
    q.base=(int *)malloc(k*sizeof(int));
    if(!q.base)
        printf("存储分配失败");//存储分配失败
    q.front=q.rear=0;
}
void EnQueue(queue &q,int i)
{
    q.base[q.rear]=i;
    q.rear=(q.rear+1)%k;
}
void DeQueue(queue &q,int &i)
{
    i=q.base[q.front];
    q.front=(q.front+1)%k;
}
int QueueLength(queue &q)
{
    return (q.rear-q.front+k)%k;
}
int fun(int m)
{
    if(m==0)
        return 0;
    if(m==1)
        return 1;
    else
        return fun(m-1)+fun(m-2);
}
int main()
{
  queue q;
  int e;
  InitQueue(q);
  int s,j=0,count=0,max;
  printf("请输入约定的最大数:");
  scanf("%d",&max);
  for(int i=0;;i++)
  {
      s=fun(i);
      if(s<=max)
      {
          if(i>=k)
            DeQueue(q,e);
          EnQueue(q,s);
          j=i;
          ++j;
          s=fun(j);
      }
    if(s>max)
        break;
      
  }
  int len=k;
  if(i<k-1)
     len=QueueLength(q);
  while(count<len)
  {
      DeQueue(q,e);
     printf("%d\n",e);
     count++;
  }
  return 0;
}

 

posted @ 2013-04-29 15:36  wj704  阅读(1100)  评论(3编辑  收藏  举报