舞伴问题 队列 c++

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_39993896/article/details/79117421

问题描述:

 在一个舞会上,男士们和女士们进入舞厅,各自排成一队。跳舞开始时,依次从男队和女队的队列头上各出一个人进行配对。若两队初始人数不同,则较长的那一队中未配对者等待下一轮舞曲。 编写算法显示成功配对的信息,若有未配对者则输出其所在的队名(男队或女队)及其姓名。

解决:c++,队列

#include<iostream>
using namespace std;
struct Person
{
    char sex;
    char name[20];
};
struct Queue
{
    Person person[20];
    int front=0;
    int rear=0;
    int count=0;
};

void Match(Person* person,int num,Queue *Female,Queue* Male)//匹配。先将所有人都录入到person数组中,num为男女总人数,再根据性别分别入女队female和男队male中
{
    person=new Person[num];
    Female=new Queue;
    Male=new Queue;
    for( int i=0;i<num;i++)
    {
        cin>>person[i].sex;
        cin>>person[i].name;
    }
    for( int i=0;i<num;i++)
    {
        if(person[i].sex=='m'||person[i].sex=='M')
        {
            Male->person[Male->rear++]=person[i];
            Male->count++;
        }
        if(person[i].sex=='f'||person[i].sex=='F')
        {
            Female->person[Female->rear++]=person[i];
            Female->count++;
        }
    }
    while(Male->count>0&&Female->count>0)
    {
        cout<<"配对";
        cout<<Male->person[Male->front].sex<<"    "<<Male->person[Male->front].name<<"  an +   "<<Female->person[Female->front].sex<<"   "<<Female->person[Female->front].name<<endl;
        Male->front++;
        Female->front++;
        Male->count--;
        Female->count--;
    }
    if(Male->count)
    {
        cout<<"下一轮等待:男队的"<<Male->person[Male->front].name<<endl;
    }
    if(Female->count)
    {
        cout<<"下一轮等待:女队的"<<Female->person[Female->front].name<<endl;
    }
}

int main()
{
    int num;
    while(cin>>num)
    {
        Person* person;
    Queue* female,*male;
    Match(person,num,female,male);
    }

    return 0;
}


展开阅读全文

没有更多推荐了,返回首页