C语言队列解决舞伴匹配问题
生活随笔
收集整理的這篇文章主要介紹了
C语言队列解决舞伴匹配问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
舞伴問題:男女站成兩隊依次結(jié)成舞伴,兩隊人數(shù)不同,人數(shù)多的隊伍則會出現(xiàn)無人匹配的情況,所以多出的人等待下一輪其他組完成跳舞,再繼續(xù)結(jié)成舞伴。
#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];//動態(tài)生成數(shù)據(jù)測試 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("生成男女生數(shù)據(jù)為:\n");for(int i= 0;i<MAXSIZE;i++){printf("%s=%c ",pArr[i].name,pArr[i].sex);}dancePartner(pArr,10);return 0; }總結(jié)
以上是生活随笔為你收集整理的C语言队列解决舞伴匹配问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言队列ADT 学习总结
- 下一篇: c226打印机驱动安装_打印机驱动怎么安