许多大学生报名参与大运会志愿者工作。其中运动场引导员需要男女生组队,每组一名男生加一名女生,男生和女生各自排成一队,依次从男队和女队队头各出一人配成小组,若两队初始人数不同,则较长那一队未配对者调到其他志愿者队。现要求写一算法模拟上述配对问题,你需要用队列操作实现上述算法。
函数接口定义:
Status EnQueue(SqQueue &Q,QElemType e);//入队
Status DeQueue(SqQueue &Q,QElemType &e);//出队
void Partner( int num);//男女配对
其中 Q
代表队列, e
代表出队或入队的元素; num
为志愿者总人数。
裁判测试程序样例:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iostream>
#include<string>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
#define MAX_QSIZE 5
typedef struct {
char name[20];
char sex;
} QElemType;
typedef int Status;
typedef struct
{ QElemType *base;
int front;
int rear;
}SqQueue;
SqQueue Mdancers, Fdancers; //分别存放男士和女士入队者队列
Status InitQueue(SqQueue &Q)
{ /* 构造一个空队列Q */
Q.base=(QElemType *)malloc(MAX_QSIZE*sizeof(QElemType));
if(Q.base==NULL) return OVERFLOW;
Q.front=Q.rear=0;
return OK;
}
Status EnQueue(SqQueue &Q,QElemType e)//入队
{ /* 插入元素e为Q的新的队尾元素 */
//请补充完整
return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e)//出队
{ /* 若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;否则返回ERROR */
//请补充完整
return OK;
}
Status QueueEmpty(SqQueue Q)//判断队空
{ /* 若队列Q为空队列,则返回TRUE;否则返回FALSE */
if(Q.front==Q.rear) /* 队列空的标志 */
return TRUE;
else
return FALSE;
}
void Partner( int num) {//num是志愿者总人数
InitQueue(Mdancers); //男生队列初始化
InitQueue(Fdancers); //女生队列初始化
QElemType p;
for (int i = 0; i < num; i++) //依次将志愿者根据其性别入队
{
cin>>p.name >>p.sex;
if (p.sex == 'F')
______________________; //插入女队
else
EnQueue(Mdancers, p); //插入男队
}
if(QueueEmpty(Fdancers)||QueueEmpty(Mdancers))
cout << "配对失败!" << endl;
else
{ cout << "配对成功小组:" << endl;
while (!QueueEmpty(Fdancers) && !QueueEmpty(Mdancers)) {//依次输出男女志愿者的姓名
_____________________________; //女生出队
cout << p.name << " "; //输出出队女生姓名
____________________________; //男生出队
cout << p.name << endl; //输出出队男生姓名
}
}
}
int main()
{
int num;
cin>> num;
Partner(num);
return 0;
}
输入样例:
6
张三 M
李四 F
王五 F
李欣 M
钟中 M
萝莉 M
输出样例:
配对成功小组:
李四 张三
王五 李欣
答案:
#include <cstring>
Status EnQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MAX_QSIZE == Q.front)
return ERROR; // 队列满
strcpy(Q.base[Q.rear].name,e.name);
(Q.base[Q.rear]).sex=e.sex;
Q.rear = (Q.rear + 1) % MAX_QSIZE;
return OK;
}
Status DeQueue(SqQueue &Q, QElemType &e)
{
if (Q.front == Q.rear)
return ERROR; // 队列为空
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAX_QSIZE;
return OK;
}
void Partner(int num)
{
InitQueue(Mdancers); // 男生队列初始化
InitQueue(Fdancers); // 女生队列初始化
QElemType p;
for (int i = 0; i < num; i++)
{
//cin >> p.name >> p.sex;
scanf("%s %c",p.name,&(p.sex));
if (p.sex == 'F')
EnQueue(Fdancers, p); // 插入女队
else
EnQueue(Mdancers, p); // 插入男队
}
if (QueueEmpty(Fdancers) || QueueEmpty(Mdancers))
cout << "配对失败!" << endl;
else {
cout << "配对成功小组:" << endl;
while (!QueueEmpty(Fdancers) && !QueueEmpty(Mdancers))
{ // 依次输出男女志愿者的姓名
DeQueue(Fdancers, p); // 女生出队
printf("%s ",p.name);
//cout << p.name << " ";
DeQueue(Mdancers, p); // 男生出队
cout << p.name << endl;
}
}
}