舞伴问题算法
#include <stdio.h>#include <stdlib.h>
#include <iostream.h>
#define MAX_DANCERS 100
#define Queuesize 100//假定预分配的队列空间最多为100个元素
typedef struct{
char name[20];
char sex;//性别,‘F’代表女性,‘M’代表男性
}Person;
typedef Person DataType;
typedef struct{
DataType data[Queuesize];
int front;
int rear;
int count;
}CirQueue;
void Initial(CirQueue *Q)
{
Q->front=Q->rear=0;
Q->count=0;
}
int IsEmpty(CirQueue *Q)
{
return Q->front==Q->rear;
}
int IsFull(CirQueue *Q)
{
return Q->rear==Queuesize-1+Q->front;
}
void EnQueue(CirQueue *Q,DataType x)
{
if(IsFull(Q))
{
printf("队列上溢");
exit(1);
}
Q->count++;
Q->data[Q->rear]=x;
Q->rear=(Q->rear+1)%Queuesize;
}
DataType DeQueue(CirQueue *Q)
{
DataType temp;
if(IsEmpty(Q))
{
printf("队列为空");
exit(1);
}
temp=Q->data[Q->front];
Q->count--;
Q->front=(Q->front+1)%Queuesize;
return temp;
}
DataType Front(CirQueue *Q)
{
if(IsEmpty(Q))
{
printf("队列为空");
exit(1);
}
return Q->data[Q->front];
}
void DancePartner(Person dancer[],int num)
{
int i;
Person p;
CirQueue Mdancers,Fdancers;
Initial(&Mdancers);
Initial(&Fdancers);
for(i=0;i<num;i++)
{
p=dancer[i];
if(p.sex=='F')
EnQueue(&Fdancers,p);
else if(p.sex=='M')
EnQueue(&Mdancers,p);
}
printf("舞队是:\n\n");
while(!IsEmpty(&Fdancers)&&!IsEmpty(&Mdancers)){
p=DeQueue(&Fdancers);
printf("%s ",p.name);
p=DeQueue(&Mdancers);
printf("%s\n",p.name);
}
if(!IsEmpty(&Fdancers)){
printf("\n还有 %d 个女士等下一轮.\n",Fdancers.count);
p=Front(&Fdancers);
printf("%s will be first to get a partner.\n",p.name);
}
else if(!IsEmpty(&Mdancers)){
printf("\n 还有%d 个男士等下一轮.\n",Mdancers.count);
p=Front(&Mdancers);
printf("%s will be first to get a partner.\n",p.name);
}
}
void InitialDancer(Person dancer[],int n)
{
int i;
printf("请输入参加跳舞的舞者:\n\n");//跳舞报名
for(i=0;i<n;i++){
dancer[i].sex=getchar();
if(dancer[i].sex=='a') break;//结束标志
gets(dancer[i].name);
}
}
void main()
{
Person dancer[MAX_DANCERS];
int n=93;
InitialDancer(dancer,n);
DancePartner(dancer,n);
}
第一次发帖多多顶顶谢谢!!!