假设在周末舞会上,男士和女士们分别进入舞厅,各自排成一队。跳舞开始,依次从男队和女队队头各出一人配成舞伴,若两队初始人数不同,则较长那一队未配对者等待下一轮舞曲。现要求写一算法模拟上述舞伴配对问题。 你需要用队列操作实现上述算法。请完成下面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
AC代码
int QueueLen(SqQueue Q){//队列长度
return (Q->rear -Q->front + MAXQSIZE ) % MAXQSIZE;
}
int EnQueue(SqQueue &Q, Person e){//入队
Q->rear = (Q->rear + 1) %MAXQSIZE;
Q->data[Q->rear] = e;
return 0;
}
int QueueEmpty(SqQueue &Q){//判空
if(Q->front==Q->rear){
return 1;
}else{
return 0;
}
}
int DeQueue(SqQueue &Q, Person &e){//出队
//就很神奇,把出队那个存到e中
Q->front=(Q->front+1)%MAXQSIZE;
e=Q->data[Q->front];
return 0;
}
void DancePartner(Person dancer[], int num){
/*
*函数作用:
*1.将Person里存的人分到Mdancers, Fdancers两个队列
*2.Mdancers, Fdancers一比一配队出列
*/
//Mdancers, Fdancers
for(int i=0;i<num;i++){
if(dancer[i].sex=='M'){
EnQueue(Mdancers,dancer[i]);
}else{
EnQueue(Fdancers,dancer[i]);
}
}
while(QueueEmpty(Mdancers)!=1&&QueueEmpty(Fdancers)!=1){
Person x,y;
DeQueue(Mdancers, x);
DeQueue(Fdancers, y);
cout<<y.name<<" "<<x.name<<endl;
}
}
神志不清的我硬是看了半天才看明白