順序表示的佇列——順序佇列4——輪渡管理
阿新 • • 發佈:2018-11-29
【問題】
某汽車輪渡口,過江渡船每次能載10輛車過江。過江車輛分為客車類和貨車類,上船有以下規定:同類車先到先上船,客車先於貨車上渡船,且每上4輛客車,才允許上一輛貨車;若等待貨車不足4輛,則以貨車代替,如果無貨車等待則允許客車都上船。設計一個演算法模擬渡口管理。
【分析】
初始時,上渡船汽車數count、上渡船客車數countbus、上渡船貨車數counttrunk均為0。若輸入命令E或e表示有汽車來渡江,可以分別按客車汽車分別進入相應的佇列排隊。
若輸入命令O或o表示渡船到渡口,可按排隊順序將客車或貨車上渡船:
(1)若車輛總數count<4,且客車佇列非空,將客車佇列的隊頭汽車出隊上渡船。並進行計數,即count和countbus增1;
(2)若客車數countbus≥4,或客車佇列為空隊,且貨車佇列非空,將貨車佇列的隊頭汽車出隊上渡輪。將countbus置為0,並進行計數即count和counttrunk增1;
(3)若貨車佇列為空且客車佇列非空,將客車隊佇列的隊頭汽車出隊上渡輪。count和countbus增1,將counttrunk置為0。
輸入命令Q或q表示退出程式。
SeqQueue.h
#pragma once #define QueueSize 100 //typedef int DataType; typedef struct Squeue { DataType queue[QueueSize]; int front, rear; }SeqQueue; void InitQueue(SeqQueue *SCQ) { SCQ->front = SCQ->rear = 0; } int QueueEmpty(SeqQueue SCQ) { if (SCQ.front==SCQ.rear) { return 1; } else { return 0; } } int EnQueue(SeqQueue *SCQ, DataType e) { if (SCQ->front==(SCQ->rear+1)%QueueSize) { return 0; } SCQ->queue[SCQ->rear] = e; SCQ->rear = (SCQ->rear + 1) % QueueSize; return 1; } int DeQueue(SeqQueue *SCQ, DataType *e) { if (SCQ->front==SCQ->rear) { return 0; } else { *e = SCQ->queue[SCQ->front]; SCQ->front = (SCQ->front + 1) % QueueSize; return 1; } } int GetHead(SeqQueue SCQ, DataType *e) { if (SCQ.front==SCQ.rear) { return 0; } else { *e = SCQ.queue[SCQ.front]; return 1; } } void ClearQueue(SeqQueue *SCQ) { SCQ->front = SCQ->rear = 0; }
main.cpp
#include <iostream> using namespace std; typedef int DataType; #include "SeqQueue.h" void FerryManage() { SeqQueue bus, trunk; char ch; DataType n; int tag; int count=0, countbus=0, counttrunk=0; InitQueue(&bus); InitQueue(&trunk); while (1) { fflush(stdin); cout << "輸入命令(e或E表示入隊,o或O表示出隊,q或Q表示退出):" << endl; //printf("輸入命令(e或E表示入隊,o或O表示出隊,q或Q表示退出):\n"); scanf("%c", &ch); switch (ch) { case 'e': case 'E': cout << "請輸入車號(整數):"; scanf("%d", &n); getchar(); cout << "是客車(1)還是貨車(2):"; scanf("%d", &tag); getchar(); if (tag==1) { EnQueue(&bus, n); } else { EnQueue(&trunk, n); } break; case 'o': case 'O': while (count<10) { if (count<4&&!QueueEmpty(bus)) { DeQueue(&bus, &n); cout << "上船的車號:" << n << endl; count++; countbus++; } else if(!QueueEmpty(trunk)) { countbus = 0; DeQueue(&trunk, &n); cout << "上船的車號:" << n << endl; count++; counttrunk++; } else if (!QueueEmpty(bus)) { counttrunk = 0; DeQueue(&bus, &n); cout << "上船的車號:" << n << endl; count++; countbus++; } else { cout << "排隊輪渡的車輛少於10輛。"<<endl; return; } } break; case 'q': case 'Q': break; } if (ch=='q'||ch=='Q') { break; } } } void main() { FerryManage(); system("pause"); }
結果: