假设在周末舞会上,男士和女士们分别进入舞厅,各自排成一队。跳舞开始,依次从男队和女队队头各出一人配成舞伴,若两队初始人数不同,则较长那一队未配对者等待下一轮舞曲。现要求写一算法模拟上述舞伴配对问题。
你需要用队列操作实现上述算法。请完成下面5个函数的操作。
函数接口定义:
int QueueLen(SqQueue Q);//队列长度
int EnQueue(SqQueue &Q, Person e);//加入队列
int QueueEmpty(SqQueue &Q);//队列是否为空
int DeQueue(SqQueue &Q, Person &e);//出队列
void DancePartner(Person dancer[], int num); //配对舞伴
Q
:队列e
:参加舞会的人dancer
:全部舞者num
:参加舞会的人数
###输入说明
先输入参加舞会人数,再分别输入参加舞会人的姓名和性别
###输出说明
先输出配对的男女舞伴,若队伍有剩人,则输出剩下人性别及剩下人数目。
裁判测试程序样例:
#include<iostream>
#define MAXQSIZE 100//队列可能达到的最大长度
#define OK 1
#define ERROR 0
#define OVERFLOW -2
using namespace std;
typedef struct {
char name[20]; //姓名
char sex; //性别,'F'表示女性,'M'表示男性
} Person;
//- - - - - 队列的顺序存储结构- - - - -
typedef struct {
Person data[MAXQSIZE];
int front; //头指针
int rear; //尾指针
} Queue;
typedef Queue *SqQueue;
SqQueue Mdancers, Fdancers; //分别存放男士和女士入队者队列
int InitQueue(SqQueue &Q);
void DestroyQueue(SqQueue &q);
int QueueLen(SqQueue Q);//队列长度
int EnQueue(SqQueue &Q, Person e);//加入队列
int QueueEmpty(SqQueue &Q);//队列是否为空
int DeQueue(SqQueue &Q, Person &e);//出队列
void DancePartner(Person dancer[], int num); //配对舞伴
int main(){
int i;
int n;
Person dancer[MAXQSIZE];
cin>>n;
for(i=0;i<n;i++) cin>> dancer[i].name >> dancer[i].sex;
InitQueue(Mdancers); //男士队列初始化
InitQueue(Fdancers); //女士队列初始化
cout << "The dancing partners are:" << endl;
DancePartner(dancer, n);
if (!QueueEmpty(Fdancers)) {
cout << "F:"<<QueueLen(Fdancers) ;
} else if (!QueueEmpty(Mdancers)) {
cout << "M:"<<QueueLen(Mdancers) ;
}
DestroyQueue(Fdancers);
DestroyQueue(Mdancers);
return 0;
}
int InitQueue(SqQueue &Q) {//构造一个空队列Q
Q = new Queue; //为队列分配一个最大容量为MAXSIZE的数组空间
if (!Q->data)
exit( OVERFLOW); //存储分配失败
Q->front = Q->rear = 0; //头指针和尾指针置为零,队列为空
return OK;
}
void DestroyQueue(SqQueue &q)
{
delete q;
}
/* 请在这里填写答案 */
输入样例:
6
张1 F
林1 F
王2 M
李1 F
薛2 M
翁1 F
输出样例:
The dancing partners are:
张1 王2
林1 薛2
F:2
代码如下:
int QueueLen(SqQueue Q){
int n = 0;
int a = Q->front;
int b = Q->rear;
while(a != b){
a = (a+1)%MAXQSIZE;
n++;
}
return n;
}
int EnQueue(SqQueue &Q, Person e){
if((Q->rear + 1)%MAXQSIZE == Q->front)return ERROR ;
Q->rear = (Q->rear + 1)%MAXQSIZE;
Q->data[((Q->rear))] = e;
return OK;
}
int QueueEmpty(SqQueue &Q){
return (Q->front == Q->rear);
}
int DeQueue(SqQueue &Q, Person &e){
if(QueueEmpty(Q)) return -1;
Q->front = (Q->front + 1)%MAXQSIZE;
e = Q->data[Q->front];
return OK;
}
void DancePartner(Person dancer[], int num){
int i;
for(i = 0 ; i < num; ++i)
{
if(dancer[i].sex == 'F')
EnQueue(Fdancers,dancer[i]);
else
EnQueue(Mdancers,dancer[i]);
}
Person e;
while((!QueueEmpty(Fdancers)) && (!QueueEmpty(Mdancers)))
{
DeQueue(Fdancers,e);
cout<<e.name<<" ";
DeQueue(Mdancers,e);
cout<<e.name<<endl;
}
}