舞伴问题 队列(c++
时间: 2023-12-11 21:30:21 浏览: 222
舞伴问题是一个经典的算法问题,可以使用队列来解决。以下是使用C++语言实现的代码:
```
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int main() {
queue<string> maleQueue, femaleQueue;
int maleNum, femaleNum;
string name;
// 输入男女队列人数
cout << "请输入男队人数:";
cin >> maleNum;
cout << "请输入女队人数:";
cin >> femaleNum;
// 输入男队姓名
cout << "请输入男队姓名:" << endl;
for (int i = 0; i < maleNum; i++) {
cin >> name;
maleQueue.push(name);
}
// 输入女队姓名
cout << "请输入女队姓名:" << endl;
for (int i = 0; i < femaleNum; i++) {
cin >> name;
femaleQueue.push(name);
}
// 配对
while (!maleQueue.empty() && !femaleQueue.empty()) {
cout << maleQueue.front() << " 和 " << femaleQueue.front() << " 配对成功! << endl;
maleQueue.pop();
femaleQueue.pop();
}
// 输出未配对者
if (!maleQueue.empty()) {
cout << "男队中未配对者:" << endl;
while (!maleQueue.empty()) {
cout << maleQueue.front() << endl;
maleQueue.pop();
}
}
if (!femaleQueue.empty()) {
cout << "女队中未配对者:" << endl;
while (!femaleQueue.empty()) {
cout << femaleQueue.front() << endl;
femaleQueue.pop();
}
}
return 0;
}
```
阅读全文