数据结构 周末舞会(循环队列解法)

Description

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

Input

第一行男士人数m和女士人数n(1<=m,n<=100);
第二行舞曲的数目k(1<=k<=100)。

Output

共k行,每行两个数,表示配对舞伴的序号,男士在前,女士在后。

Sample Input

4 3
6

Sample Output

1 1
2 2
3 3
4 1
1 2
2 3

 

题目很简单,已经告诉了舞曲数目,用两个数组,循环遍历即可。

用队列的话,构造俩个循环队列存放男女人数编号,然后循环遍历k次打印出编号即可。

主要注意循环队列的构建,多加练习,增加熟练度。

思路很简单。

这里给出循环队列代码实现,以及数组代码实现。

#include<stdio.h>
#include<malloc.h>
typedef struct QNode{
	int x;
	struct QNode *next;
}QDataNode;
typedef struct{
	QDataNode *front;
	QDataNode *rear;
}QHeadNode,*LinkQueue;
int InitQueue(LinkQueue *Q);
int EnQueue(LinkQueue *Q,int elem); 
int InitQueue(LinkQueue *Q)
{
	LinkQueue qhead=(LinkQueue)malloc(sizeof(QHeadNode));
	QDataNode *vhead=(QDataNode *)malloc(sizeof(QDataNode));
	if(qhead==NULL||vhead==NULL)
	{
		return -1;//内存分配失败 
	}
	vhead->next=NULL;
	*Q=qhead;
	(*Q)->front=vhead;
	(*Q)->rear=vhead;
	return 0;
}
int EnQueue(LinkQueue *Q,int elem)//入队列 
{
	QDataNode *p=(QDataNode *)malloc(sizeof(QDataNode));
	p->x=elem;
	(*Q)->rear->next=p;
	(*Q)->rear=p;
	(*Q)->rear->next=(*Q)->front->next;//循环队列 !!!
}
int main()
{
	int m,n,k;
	scanf("%d%d%d",&m,&n,&k);
	//建立两个队列 存放男女编号 
	LinkQueue Q1;
	InitQueue(&Q1);
	for(int i=1;i<=m;i++)
	{
		EnQueue(&Q1,i);
	}
	LinkQueue Q2;
	InitQueue(&Q2);
	for(int i=1;i<=n;i++)
	{
		EnQueue(&Q2,i);
	}
	//用两个指针 遍历两个队列 打印编号 
	QDataNode *p1,*p2;
	p1=Q1->front->next;
	p2=Q2->front->next; 
	for(int i=0;i<k;i++)//循环遍历k次 
	{
		printf("%d %d\n",p1->x,p2->x);
		p1=p1->next;
		p2=p2->next;
	} 
} 

数组代码实现:

#include<stdio.h>
int main()
{
	int m[100],n[100];
	int M,N,i,k;
	scanf("%d%d%d",&M,&N,&k);
	for(i=1;i<=M;i++)//数组存放编号 
		m[i]=i;
	for(i=1;i<=N;i++)
	    n[i]=i;
	for(i=1;i<=k;i++)
	{
		if(i<=M)
		printf("%d ",m[i]);
		else
		{
			if(i%M==0)//取余控制循环 
		    printf("%d ",m[M]);
		    else
		    printf("%d ",m[i%M]);
		}
		if(i<=N)
		printf("%d\n",n[i]);
		else
		{
			if(i%N==0)
		    printf("%d\n",n[N]);
		    else
		    printf("%d\n",n[i%N]);
		}
	}
 } 

 

    原文作者:舞伴问题
    原文地址: https://blog.csdn.net/holly_z_p_f/article/details/79823440
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞