算法思想:哈哈哈,这道题,buff叠满了,循环+队列+操作受限(对头和队尾都能入队,只有队尾出队),具体知识讲解和图解在王道p79页。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max_size 100
typedef int ElemType;
typedef struct SqQueue {
ElemType data[max_size];
int front, rear;
}SqQueue;
void initial(SqQueue& Q) {
Q.front = Q.rear = 0;
}
bool isEmpty(SqQueue Q) {
if (Q.front == Q.rear) {//队空的条件
return true;
}
else {
return false;
}
}
//入队列,从队尾入队
bool EnQueue1(SqQueue& Q, ElemType e) {
if ((Q.rear + 1) % max_size == Q.front) {//队满的条件(牺牲了一个存储单元)
return false;
}
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % max_size;//循环队列队尾入队
return true;
}
//入队列,从对头入队
bool EnQueue2(SqQueue& Q, ElemType e) {
if ((Q.front+max_size - 1) % max_size == Q.rear) {//队满的条件(牺牲了一个存储单元)
return false;
}
Q.front = (Q.front - 1+max_size) % max_size;//循环队列对头入队
Q.data[Q.front] = e;
return true;
}
//出队,队头元素出队
bool DeQueue(SqQueue& Q, ElemType& e) {
if (Q.rear == Q.front) {
return false;
}
e = Q.data[Q.front];
Q.front = (Q.front + 1) % max_size;//循环队列队头出队
return true;
}
int main() {
SqQueue Q;
initial(Q);
int len;
scanf("%d", &len);
int arr[max_size];
scanf("%d", &arr[0]);
EnQueue1(Q, arr[0]);//队列存入一个元素,方便比较
for (int i = 1; i < len; i++) {
scanf("%d", &arr[i]);
int num1 = Q.data[Q.front];
int num2 = Q.data[Q.rear - 1];
float ave = (num1 + num2) / 2;//求队头队尾元素平均值
if (arr[i] < ave) {
EnQueue2(Q, arr[i]);//插入队头
}
else {
EnQueue1(Q, arr[i]);//插入队尾
}
}
int num;
while (!isEmpty(Q)) {
DeQueue(Q, num);
printf("%d ", num);
}
return 0;
}