C语言队列解决舞伴匹配问题

舞伴问题:男女站成两队依次结成舞伴,两队人数不同,人数多的队伍则会出现无人匹配的情况,所以多出的人等待下一轮其他组完成跳舞,再继续结成舞伴。

#include <stdio.h>
#include <stdlib.h> 
#include <string.h>
#include<time.h>
#define MAXSIZE 13
typedef struct
{
	char name[20];
	char sex;
}Person;
typedef Person DataType;
typedef struct
{	
	DataType data[MAXSIZE];
	int front,rear;
}SqQueue;


//初始化队列 
void initQueue(SqQueue &Q)
{
	Q.front = Q.rear = -1;
}

//判断队空 
int queueEmpty(SqQueue Q)
{
	return (Q.front == Q.rear ? 1:0); 
}

//判断队满
int queueFull(SqQueue Q)
{
	return ((Q.rear + 1)%MAXSIZE == Q.front? 1:0); 
}
 

//进队
int enQueue(SqQueue &Q,DataType e)
{
	//队满 
	if(queueFull(Q))
	{
		return 0;	
	}
	//rear加1,队尾位置移动 
	Q.rear = (Q.rear + 1)%MAXSIZE;
	Q.data[Q.rear] = e;
	return 1;
}

//出队
int deQueue(SqQueue &Q,DataType &e)
{
	//队为空 
	if(queueEmpty(Q))
	{
		return 0;	
	}
	//front加1,队头位置上移 
	Q.front = (Q.front + 1)%MAXSIZE; 
	e = Q.data[Q.front];
	return 1;
} 
//取队头
int queueFront(SqQueue &Q,DataType &e)
{
	if(queueEmpty(Q))
	{
		return 0;
	}
	e = Q.data[(Q.front + 1)%MAXSIZE];
	return 1;	
} 

//求队列的长度
int queueLength(SqQueue Q)
{
	return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;	
} 

void dancePartner(Person dancer[],int num)
{
	Person p;
	SqQueue Mdancers,Fdancers;
	initQueue(Mdancers);
	initQueue(Fdancers);
	for(int i = 0;i<num;i++)
	{
		//依次按姓名入队 
		p = dancer[i];
		if(p.sex == 'F')
		{
			//排入女队 
			enQueue(Fdancers,p);
		}else
		{	
			//排入男队 
			enQueue(Mdancers,p);
		}
		putchar(10);
		printf("================================\n");
		printf("The dancing partners are: \n \n");
		while(!queueEmpty(Fdancers) && !queueEmpty(Mdancers))
		{
			deQueue(Fdancers,p);
			printf("%s	",p.name);
			deQueue(Mdancers,p);
			printf("%s\n",p.name);
		}
		if(!queueEmpty(Fdancers))
		{
			printf("\nThere are %d women wating for the next round.\n",queueLength(Fdancers)); 
			queueFront(Fdancers,p);
			printf("%s will be the first to get a partner.\n",p.name); 
		}
		
		if(!queueEmpty(Mdancers))
		{

			printf("\nThere are %d men wating for the next round.\n",queueLength(Mdancers)); 
			queueFront(Mdancers,p);
			printf("%s will be the first to get a partner.\n",p.name); 
		}
	}
}

int main()
{
	srand((unsigned)time(NULL));
	Person pArr[100];
	//动态生成数据测试 
	for(int i= 0;i<MAXSIZE;i++)
	{
		int sexNum = rand()%2;
		char pre[10] = "";
		strcpy(pre,rand()%2 == 0 ? "男":"女");
		strcmp(pre,"男") == 0 ? pArr[i].sex='M' :pArr[i].sex='F';
		char suf[10] = "";
		sprintf(suf,"%d",rand()%10000);
		strcpy(pArr[i].name,strcat(pre,suf));
	}
	printf("生成男女生数据为:\n");
	for(int i= 0;i<MAXSIZE;i++){
		printf("%s=%c   ",pArr[i].name,pArr[i].sex);
	}
	dancePartner(pArr,10);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值