舞伴配对问题(顺序队列)

先入队的男士或者女士先出队配成舞伴,因此设置两个队列分别存放男士和女士入队者。假设男士和女士的记录存放在一个数组中作为输出,然后依次查找该数组的各元素,并根据性别来决定是进男队还是进女队。当这两个队列构造完成之后,依次使两队当前的队头元素出队来配成舞伴,直至某队列变空为止。此时,若某队仍有等待配对者,则输出此队列中排在队头的等待着的姓名,此人将是下一轮舞曲开始时第一个可获得舞伴的人。

算法步骤:

1.初始化Mdancers和Fdancers队列;

2.反复循环,依次将跳舞者姓名根据性别插入Mdancers或Fdancers队列中;

3.当两个队列均不为空时,反复循环,依次输出男女舞伴的姓名;

4.如果Mdancers队列为空,而Fdancers队列非空,则输出Fdancers队列的队头女士的名字;

5.如果Fdancers队列为空,而Mdancers队列非空,则输出Mdancers队列的队头男士的名字;

实验代码:

#include 
#include 

struct Person {//舞伴的姓名和性别
	char name[20];
	char sex;
};

struct SqQueue {//队列结构
	struct Person *base;
	int front;
	int rear;
	int size;
	int MaxSize;
};

struct SqQueue *InitQueue(int MaxSize) {//初始化顺序队列
	struct SqQueue *S;
	S = (struct SqQueue *)malloc(sizeof(struct SqQueue));
	if (S) {
		S->base = (struct Person *)malloc(sizeof(struct SqQueue) * MaxSize);
		S->front = 0;
		S->rear = 0;
		S->size = 0;
		S->MaxSize = MaxSize;
	}
	return S;
}

void EnQueue(struct SqQueue *&S, struct Person p) { //入队列
	if (S->size == S->MaxSize) { /* 如果队列已满,则不能入队 */
		printf("Queue is full.\n");
		return;
	}
	S->base[S->rear++] = p;
	if (S->rear == S->MaxSize)
		S->rear = 0;
	S->size++;
}

int QueueEmpty(struct SqQueue *S) {//判断队列是否为空
	if (S->size == 0)
		return 1;
	else
		return 0;
}

struct Person DeQueue(struct SqQueue *&S ) { //出队列
	struct Person p;
	if (S->size == 0) { /* 如果队列为空,则不能出队 */
		printf("Queue is Empty.\n");
	}
	p = S->base[S->front++];
	if (S->front == S->MaxSize)
		S->front = 0;
	S->size--;
	return p;
}

struct Person GetHead(struct SqQueue *S) {//获取队列头的元素
	if (S->size != 0)
		return S->base[S->front];
}

void DancePartner(struct Person dancer[], int num) {
	struct SqQueue *Mdancers;
	struct SqQueue *Fdancers;
	Mdancers = InitQueue(100);
	Fdancers = InitQueue(100);

	for (int i = 0; i < num; i++) {
		if (dancer[i].sex == 'F')
			EnQueue(Fdancers, dancer[i]);
		else
			EnQueue(Mdancers, dancer[i]);
	}
	printf("舞伴如下: \n");
	while (!QueueEmpty(Fdancers) && !QueueEmpty(Mdancers)) {
		printf("%s ", DeQueue(Fdancers).name);
		printf("%s ", DeQueue(Mdancers).name);
	}
	if (!QueueEmpty(Fdancers)) {
		printf("下一轮第一个找到舞伴的女性是: %s\n", GetHead(Fdancers).name);
	} else if (!QueueEmpty(Mdancers)) {
		printf("下一轮第一个找到舞伴的男性是: %s\n", GetHead(Mdancers).name);
	}
}

int main() {
	struct Person dancer[10];
	int num;
	printf("请输入跳舞总人数:");
	scanf("%d", &num);
	printf("请输入各个跳舞人的姓名和性别('F'表示女性,'M'表示男性):\n");
	for (int i = 0; i < num; i++) {
		printf("请输入第%d个跳舞人的姓名和性别(用空格隔开):", i + 1);
		scanf("%s %c", &dancer[i].name, &dancer[i].sex);
	}
	DancePartner(dancer, num);
	return 0;
}

实验结果:

舞伴配对问题(顺序队列)_第1张图片

 (刚刚接触队列问题算法,请大家多多指教哦)

你可能感兴趣的:(算法,c语言)