循环队列实现舞伴配对
时间: 2023-10-29 19:05:40 浏览: 238
循环队列可以用来实现舞伴配对问题。我们可以将男女分别存储在两个循环队列中,每次从男队和女队的队头各出一个人配成舞伴,如果两队初始人数不等,则较长的那一队中未配对者等待下一轮舞曲。具体实现步骤如下:
1. 初始化两个循环队列,分别存储男女。
2. 输入舞会轮数,每轮循环队列中出队两个人,分别为男女舞伴。
3. 判断两个队列是否为空,如果为空则输出未配对者姓名。
4. 输出每一轮舞伴配对名单。
代码实现如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char name[20];
int gender; // 0表示女性,1表示男性
} Person;
typedef struct {
Person data[MAXSIZE];
int front, rear;
} Queue;
void InitQueue(Queue *Q) {
Q->front = Q->rear = 0;
}
int QueueEmpty(Queue Q) {
return Q.front == Q.rear;
}
int QueueFull(Queue Q) {
return (Q.rear + 1) % MAXSIZE == Q.front;
}
void EnQueue(Queue *Q, Person x) {
if (QueueFull(*Q)) {
printf("Queue is full!\n");
exit(1);
}
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAXSIZE;}
Person DeQueue(Queue *Q) {
if (QueueEmpty(*Q)) {
printf("Queue is empty!\n");
exit(1);
}
Person x = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return x;
}
void Match(Queue *male, Queue *female, int rounds) {
int i;
for (i = 1; i <= rounds; i++) {
printf("Round %d:\n", i);
if (QueueEmpty(*male) || QueueEmpty(*female)) {
printf("No enough people!\n");
break;
}
Person m = DeQueue(male);
Person f = DeQueue(female);
printf("%s and %s are matched!\n", m.name, f.name);
if (male->rear > male->front) {
EnQueue(male, m);
}
if (female->rear > female->front) {
EnQueue(female, f);
}
}
if (!QueueEmpty(*male)) {
printf("The following males are not matched:\n");
while (!QueueEmpty(*male)) {
Person m = DeQueue(male);
printf("%s\n", m.name);
}
}
if (!QueueEmpty(*female)) {
printf("The following females are not matched:\n");
while (!QueueEmpty(*female)) {
Person f = DeQueue(female);
printf("%s\n", f.name);
}
}
}
int main() {
Queue male, female;
InitQueue(&male);
InitQueue(&female);
// 初始化男女队列
Person m1 = {"Tom", 1};
Person m2 = {"Jack", 1};
Person m3 = {"Mike", 1};
EnQueue(&male, m1);
EnQueue(&male, m2);
EnQueue(&male, m3);
Person f1 = {"Lucy", 0};
Person f2 = {"Lily", 0};
Person f3 = {"Mary", 0};
EnQueue(&female, f1);
EnQueue(&female, f2);
EnQueue(&female, f3);
Match(&male, &female, 3);
return 0;
}
```
阅读全文