• 舞伴问题代码


    问题描述:

            假设在周末舞会上,男士们和女士们进入舞厅时,各自排成一队。跳舞开始时,依次从男队和女队的队头各出一人配成舞伴。若两队初始人数不相同,则较长的那一队中未配对者等待下一轮舞曲。现要求写一算法模拟上述舞伴配对问题

    1. #include
    2. #define OVERFLOW -1
    3. #define Maxsize 100
    4. using namespace std;
    5. typedef struct {
    6. char name[20];
    7. char sex;
    8. }Dancer;
    9. typedef struct QNode{
    10. Dancer data;
    11. struct QNode* next;
    12. }QNode,*QuePtr;
    13. typedef struct {
    14. QuePtr front;
    15. QuePtr rear;
    16. }LinkQue;
    17. void InitQue(LinkQue& Q) {
    18. Q.front = Q.rear = new QNode;
    19. if (!Q.front)
    20. exit(OVERFLOW);
    21. Q.front->next = NULL;
    22. }
    23. bool QueEmpty(LinkQue& Q) {
    24. return(Q.front->next==NULL);
    25. }
    26. //出队
    27. void DeQue(LinkQue& Q,Dancer &d) {
    28. if (QueEmpty(Q))
    29. return;
    30. QuePtr p = Q.front->next;
    31. d = p->data;
    32. Q.front->next = p->next;
    33. delete p;
    34. }
    35. //入队
    36. void EnQue(LinkQue& Q,Dancer d) {
    37. QuePtr s = new QNode;
    38. s->data = d;
    39. Q.rear->next = s;
    40. Q.rear = s;
    41. s->next = NULL;
    42. }
    43. //取队头
    44. Dancer GetHead(LinkQue Q) {
    45. return(Q.front->next->data);
    46. }
    47. void DancingPartner(LinkQue &Mdancers,LinkQue &Fdancers,Dancer d[],int num) {
    48. Dancer p;
    49. for (int i = 0; i < num; i++) {
    50. p = d[i];
    51. if (p.sex == 'F')
    52. EnQue(Fdancers, p);
    53. else
    54. EnQue(Mdancers, p);
    55. }
    56. cout << "舞伴配对为 男/女:\n";
    57. //当男女舞者均不为空时,分别出队配对
    58. while (!QueEmpty(Mdancers) && !QueEmpty(Fdancers)) {
    59. DeQue(Mdancers, p);
    60. cout << p.name << " ";
    61. DeQue(Fdancers, p);
    62. cout << p.name << endl;
    63. }
    64. if (!QueEmpty(Fdancers)) {
    65. p = GetHead(Fdancers);
    66. cout << "下一轮第一个获得舞伴的是:" << p.name << endl;
    67. }
    68. else if (!QueEmpty(Mdancers)) {
    69. p = GetHead(Mdancers);
    70. cout << "下一轮第一个获得舞伴的是:" << p.name << endl;
    71. }
    72. }
    73. int main() {
    74. Dancer d[Maxsize];
    75. LinkQue Mdancers;
    76. LinkQue Fdancers;
    77. InitQue(Mdancers);
    78. InitQue(Fdancers);
    79. printf("请输入各个跳舞人的姓名和性别('F'表示女性,'M'表示男性):\n");
    80. for (int i = 0; i < 5; i++)
    81. {
    82. printf("请输入第%d个跳舞人的姓名和性别:\n", i + 1);
    83. cin >> d[i].name;
    84. cin>>d[i].sex;
    85. }
    86. DancingPartner(Mdancers, Fdancers, d, 5);
    87. }

  • 相关阅读:
    蓝桥杯打卡Day10
    网络工程师知识点6
    CCF- CSP 201512-3画图 简单思路 满分题解
    Head First设计模式(阅读笔记)-07.适配器模式
    好用的js快速排序的方法
    【JS高级】ES6_模板字符串、let的简谈与应用_12
    微信新功能,图片直接一键生成Excel表格
    LeetCode 1694. 重新格式化电话号码
    python及第三方库交叉编译
    FPS_AI编程
  • 原文地址:https://blog.csdn.net/m0_64267256/article/details/127674217