这个题目有陷阱!!!
k阶并不是两个的和了,而是k个的和
这就是为什么wa了五次的原因qwq(我好笨)
for(i=0;i<length;i++){
sum+=elem[(front-i+length)%length];
}
除此之外没有什么问题了,移动front就行了
#include <iostream>
using namespace std;
//注意k一定要大于等于2
//初始化时,要把f(1)和f(2)入队
//front 指向下一个需要插入的位置
//只需要把front-1和front-2相加,然后再front++即可
//进行一次循环,即front重新回到0的位置
//终止条件为f(n)<max,max<f(n)+f(n-1)
template <class T>
class SQueue
{
public:
T *elem;
int front;
int rear;
int length;
int MAXSIZE;
SQueue(int n);
void EnterQueue(const T &x);
void DeleteQueue();
bool IsEmpty();
void PrintQueue();
int Size();
void Clear();
void Fibonacci(int max, int k);
};
template <class T>
SQueue<T>::SQueue(int n) : length(0)
{
front = rear = 0;
MAXSIZE = n + 1;
elem = new int[MAXSIZE];
}
template <class T>
void SQueue<T>::EnterQueue(const T &x)
{
elem[rear] = x;
rear = (rear + 1) % MAXSIZE;
length++;
if ((rear + 1) % MAXSIZE == front)
{
return;
}
}
template <class T>
void SQueue<T>::DeleteQueue()
{
if (rear == front)
{
return;
}
front = (front + 1) % MAXSIZE;
length++;
}
template <class T>
bool SQueue<T>::IsEmpty()
{
return rear == length;
}
template <class T>
int SQueue<T>::Size()
{
return length;
}
template <class T>
void SQueue<T>::PrintQueue()
{
int i = 0;
for (i = 0; i < length; i++)
{
cout << elem[(front+i) % length] << " ";
}
cout << endl;
}
template <class T>
void SQueue<T>::Clear()
{
while (length > 0)
{
DeleteQueue();
}
}
template <class T>
void SQueue<T>::Fibonacci(int max, int k)
{
EnterQueue(1);
EnterQueue(1);
// cout<<"length= "<<length<<" MAXSIZE="<<MAXSIZE<<endl;
while (length + 1 < MAXSIZE)
{
EnterQueue(elem[length - 1] + elem[length - 2]);
}
// PrintQueue();
// cout<<"front="<<front<<" rear="<<rear<<endl;
while(1){
int i=0;
int sum=0;
for(i=0;i<length;i++){
sum+=elem[(front-i+length)%length];
}
int k=(front-1+length)%length;
// int k_1=(front-2+length)%length;
// cout<<"f(n)="<<elem[k]<<" f(n+1)="<<elem[k]+elem[k_1]<<endl;
if(elem[k]<=max&&sum>max)
break;
elem[front]=sum;
front=(front+1)%length;
// PrintQueue();
}
PrintQueue();
}
int main()
{
int max,k;
// freopen("in010.txt", "r", stdin);
cin>>max>>k;
SQueue<int> L(k);
// cout<<"maxsize=="<<L.MAXSIZE<<endl;
L.Fibonacci(max,k);
system("pause");
return 0;
}