【資料結構】佇列的應用-舞伴配對問題
阿新 • • 發佈:2019-01-13
舞會的舞伴配對問題:
某單位舉辦週末友誼舞會,在舞會上,男、女各自排成一隊。舞會開始時,依次從男隊和女隊的隊頭各出一人配成舞伴。如果兩隊初始人數不等,則較長的那一隊中未配對者等待下一輪舞曲。假設初始男、女人數已經固定,舞會的輪數表示舞曲數。試模擬解決上述舞伴配對問題。
核心程式碼:
void PartnerPairing(CQueue &Qm,CQueue &Qw,int Rotation){ int n,m,Min; m=(Qm.Rear-Qm.Front+Maxn)%Maxn; n=(Qw.Rear-Qw.Front+Maxn)%Maxn; printf("%d %d\n",n,m); Min=m<n?m:n; QElemType man,woman,dancer; for(int i=0;i<Rotation ;i++){ for(int j=0;j<Min;j++){ DeQueue(Qm,man);DeQueue(Qw,woman); cout<<man.name<< "<----->"<<woman.name<<endl; EnQueue(Qm,man);EnQueue(Qw,woman); } m>n?GetHead(Qm,dancer):GetHead(Qw,dancer); cout<<"Next Round Dancer : " <<dancer.name<<endl; } }
完整的除錯程式碼:
#include<string> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<iostream> #define Maxn 100 #define QueueSize 100 using namespace std; typedef struct QElemType{ string name; int age ; QElemType(string t="Bin",int Age=20){ name=t;age=Age; } }QElemType; typedef struct { QElemType *base; int Front ,Rear; }CQueue; void InitQueue(CQueue &Q){ Q.base = new QElemType [ QueueSize ]; Q.Front = Q.Rear = 0; } void EnQueue(CQueue &Q,QElemType e){ Q.base[Q.Rear]=e; Q.Rear=(Q.Rear+1)%Maxn; } void DeQueue(CQueue &Q,QElemType &e){ if(Q.Front==Q.Rear){ printf("error !!! Queue is empty !!!\n");return ; } e=Q.base[Q.Front++]; Q.Front=Q.Front%Maxn; } void GetHead(CQueue &Q,QElemType &e){ if(Q.Front==Q.Rear){ printf("error !!! Queue is empty !!!\n");return ; } e=Q.base[Q.Front]; } void PartnerPairing(CQueue &Qm,CQueue &Qw,int Rotation){ int n,m,Min; m=(Qm.Rear-Qm.Front+Maxn)%Maxn; n=(Qw.Rear-Qw.Front+Maxn)%Maxn; printf("%d %d\n",n,m); Min=m<n?m:n; QElemType man,woman,dancer; for(int i=0;i<Rotation ;i++){ for(int j=0;j<Min;j++){ DeQueue(Qm,man);DeQueue(Qw,woman); cout<<man.name<< "<----->"<<woman.name<<endl; EnQueue(Qm,man);EnQueue(Qw,woman); } m>n?GetHead(Qm,dancer):GetHead(Qw,dancer); cout<<"Next Round Dancer : " <<dancer.name<<endl; } } int main() { int n,m,Rotation; QElemType man,woman; CQueue Qm,Qw; InitQueue(Qm),InitQueue(Qw); printf("請輸入舞會 男舞者,女舞者各人數: \n"); cin>>n>>m; printf("請輸入%d位男舞者的名字和年齡\n",n); for(int i=0;i<n;i++){ printf("第%d位 男舞者 name , age \n",i+1); cin>>man.name>>man.age; EnQueue(Qm,man); } printf("請輸入%d位女舞者的名字和年齡",m); for(int i=0;i<m;i++){ printf("第%d位 女舞者 name , age \n",i+1); cin>>woman.name>>woman.age; EnQueue(Qw,woman); } printf("請輸入需要多少輪舞會: "); scanf("%d",&Rotation); PartnerPairing(Qm,Qw,Rotation); return 0; }