【问题描述】
一班有m个女生,有n个男生(m不等于n),现要开一个舞会。男女生分别编号坐在舞池的两边的椅子上。每曲开始时,依次从男生和女生中各出一人配对跳舞,本曲没成功配对者坐着等待下一曲找舞伴。
【基本要求】
请设计一系统模拟动态地显示出上述过程,要求如下:
(1)输出每曲配对情况;
(2)计算出任何一个男生(编号为X)和任意女生(编号为Y),在第K曲配对跳舞的情况.至少求出K的两个值;
(3)尽量设计出多种算法及程序。
【算法思想】
用循环队列来解决,入队和出队可分别对应男女各自配对并重新回到座位上。
#include"pch.h"
#include <iostream>
using namespace std;
template <class T>
class seqQueue {
private:
T*data;
int maxSize;
int front; //队头指针
int rear; //队尾指针
public:
seqQueue(int initsize);
~seqQueue() //定义析构函数,使对象在撤销时释放
{
front = rear = 0;
delete[]data;
}
void thefrist();
void enQueue(T x);
void deQueue(T&x);
};
template<class T>
seqQueue<T>::seqQueue(int initsize) { //创建队列
data = new T[initsize];
maxSize = initsize;
front = rear = 0;
}
template<class T>
void seqQueue<T>:: thefrist() //队列的声明
{
for (int i = 0; i < maxSize - 1; i++)
enQueue(i);
}
template<class T>
void seqQueue<T>:: enQueue(T x) { //入队
data[rear] = x;
rear = (rear + 1) % maxSize;
}
template <class T>
void seqQueue<T>:: deQueue(T &x) { //出队
x = data[front];
front = (front + 1) % maxSize;
}
void thefrist(seqQueue<int> & a, int m);
void exchange(int, int);
void start(int, int);
static int b = 0, g = 0;
int song = 0;
int main()
{
int b_2 = 0, g_2 = 0;
cout << "请依次输入男女生人数:" << endl;
cin >> b >> g;
start(b, g);
cout << "请输入男生和女生的编号:";
cin >> b_2 >> g_2;
while ((b_2 > b) || (g_2 > g)) //如果输入错误
{
cout << "输入的编号过大,请重新输入:";
cin >> b_2 >> g_2;
}
exchange(b_2, g_2);
cout << "是否继续(是请输入'y',否则请输入'n'):";
}
void thefrist(seqQueue<int> &Q, int m) //初始化队列
{
for (int i = 1; i <= m; i++)
Q.enQueue(i);
}
void start(int b, int g) {
seqQueue<int> man(b + 1);
seqQueue<int>woman(g + 1); //创建男女两个队列
thefrist(man, b);
thefrist(woman, g);
cout << "请输入将要播放的曲目数\n";
cin >> song;
cout << "配对情况如下:\n";
for (int i = 1; i <= song; i++)
{
int x, y;
man.deQueue(x);
woman.deQueue(y);
cout << "第" << i << "首曲子:" << x << "号男生>>>>" << y << "号女生" << endl;
man.enQueue(x);
woman.enQueue(y);
}
}
void exchange(int b_2, int g_2)
{
int f = 0;
seqQueue<int>man2(b + 1);
seqQueue<int>woman2(g + 1);
thefrist(man2, b);
thefrist(woman2, g);
while (f <= song)
{
int x, y;
f++;
man2.deQueue(x);
woman2.deQueue(y);
man2.enQueue(x);
woman2.enQueue(y);
if ((x == b_2) && (y == g_2))
{
cout << "第" << f << "首曲:\t" << x << "号男生<->" << y << "号女生" << endl;
}
}
if (f == song)
cout << "他们在这个舞会上不可能在一起跳舞" << endl;
}