问题
问题描述:在舞会上,男、女各自排成一队。舞会开始时。依次从男队和女队的队头各出一人配成舞伴。如果两队初始人数不等,则较长的那一队中未配对者等待下一轮舞曲。初始男、女人数及性别已经固定,舞会的轮数从键盘输入。
解答
男 | 女 |
1 | 7 |
2 | 8 |
3 | 9 |
4 | 10 |
5 | |
6 |
例如跳舞人员共十人,6男4女,那么配对情况应该像上面表格前4行那样,然后下一轮最先配对的应该是男5号。接着第二轮:
男 | 女 |
5 | 7 |
6 | 8 |
1 | 9 |
2 | 10 |
3 | |
4 |
第二轮最先配对如上表,5号先与第一个女舞伴配对。然后下一轮最先配对应为男3号。
代码实现
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define MAXQSIZE 100
typedef int Status;
//舞伴问题
typedef struct
{
char name[20];//名字
char sex;//F为女性,M为男性
}person;
//队列
typedef struct
{
person* base;
int front;//头指针
int rear;//尾指针
}SqQueue;
typedef person ElemType;
//队列初始化
Status InitQueue(SqQueue& q)
{
q.base = new person[MAXQSIZE];
if (!q.base)
exit(OVERFLOW);
q.front = q.rear = 0;
return OK;
}
//求长度
int QueueLength(SqQueue* q)
{
return(q->rear - q->front + MAXQSIZE) % MAXQSIZE;
}
//判断是否为空
bool queue_empty(SqQueue& q)
{
if (q.front == q.rear)
return true;
else
return false;
}
//入队
Status EnQueue(SqQueue& q, person e)
{
if ((q.rear + 1) % MAXQSIZE == q.front)
{
return ERROR;
}
q.base[q.rear] = e;
q.rear = (q.rear + 1) % MAXQSIZE;
return OK;
}
//出队(保留队头元素)
Status DeQueue(SqQueue& q, person& e)
{
if (q.front == q.rear)
return ERROR;
e = q.base[q.front]; //保留队头元素
q.front = (q.front + 1) % MAXQSIZE;
return OK;
}
//出队(不保留对头元素)
Status DeQueuee(SqQueue& q)
{
if (q.front == q.rear)
return ERROR;
q.front = (q.front + 1) % MAXQSIZE;
return OK;
}
//取队头元素
person GetHead(SqQueue& q)
{
if (q.rear != q.front)
{
return q.base[q.front];
}
}
//舞伴问题解决
void dancer_solve(person dancer[], int num,int m, SqQueue male,SqQueue female)
{
/*SqQueue male, female;
InitQueue(male);
InitQueue(female);*/
for (int j = 0; j < m; j++)
{
cout << "第" << j + 1 << "轮:" << endl;
for (int i = 0; i < num; i++)
{
if (dancer[i].sex == 'F')
EnQueue(female, dancer[i]);
else
EnQueue(male, dancer[i]);
}
cout << "The dancing partners are:\n";
while (!queue_empty(male) && !queue_empty(female))
{
person p;
DeQueue(male, p);
cout << p.name << ' ';
DeQueue(female, p);
cout << p.name << endl;
}
person e;
if (!queue_empty(female))
{
e = GetHead(female);
cout << "The first woman to get a partner is:" << e.name << endl;
}
else if (!queue_empty(male))
{
e = GetHead(female);
cout << "The first man to get a partner is:" << e.name << endl;
}
}
}
//主函数
int main()
{
int n;
cout << "请输入跳舞人的人数:";
cin >> n;
person *dancer = new person[n];
cout << "请依次输入跳舞人的信息:" << endl;
for (int i = 0; i < n; i++)
{
cout << "name:";
cin >> dancer[i].name;
cout << "sex:";
cin >> dancer[i].sex;
}
int m;
cout << "请输入舞会的轮数:";
cin >> m;
SqQueue male, female;
InitQueue(male);
InitQueue(female);
dancer_solve(dancer, n,m, male, female);
return 0;
}