第三章作业4--循环队列及线性结构综合 列车调度

    科技2023-09-30  72

    7-2 列车调度 (25分)

    火车站的列车调度铁轨的结构如下图所示。

    两端分别是一条入口(Entrance)轨道和一条出口(Exit)轨道,它们之间有N条平行的轨道。每趟列车从入口可以选择任意一条轨道进入,最后从出口离开。在图中有9趟列车,在入口处按照{8,4,2,5,3,9,1,6,7}的顺序排队等待进入。如果要求它们必须按序号递减的顺序从出口离开,则至少需要多少条平行铁轨用于调度?

    输入格式:

    输入第一行给出一个整数N (2 ≤ N ≤10^5​​ ),下一行给出从1到N的整数序号的一个重排列。数字间以空格分隔。

    输出格式:

    在一行中输出可以将输入的列车按序号递减的顺序调离所需要的最少的铁轨条数。

    输入样例:

    9 8 4 2 5 3 9 1 6 7

    输出样例:

    4

    Accepted Code

    #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> #include <string> #include <cmath> #include <algorithm> using namespace std; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Position; typedef int ElementType; struct QNode { ElementType *Data; /* 存储元素的数组 */ Position Front, Rear; /* 队列的头、尾指针 */ int MaxSize; /* 队列最大容量 */ }; typedef struct QNode *Queue; Queue CreateQueue(int MaxSize) { Queue Q = (Queue) malloc(sizeof(struct QNode)); Q->Data = (ElementType *) malloc(MaxSize * sizeof(ElementType)); Q->Front = Q->Rear = -1; Q->MaxSize = MaxSize; return Q; } bool IsFull(Queue Q) { return ((Q->Rear + 1) % Q->MaxSize == Q->Front); } bool AddQ(Queue Q, ElementType X) { if (IsFull(Q)) { //printf("队列满"); return false; } else { Q->Rear = (Q->Rear + 1) % Q->MaxSize; Q->Data[Q->Rear] = X; return true; } } bool IsEmpty(Queue Q) { return (Q->Front == Q->Rear); } ElementType DeleteQ(Queue Q) { if (IsEmpty(Q)) { //printf("队列空"); return ERROR; } else { Q->Front = (Q->Front + 1) % Q->MaxSize; return Q->Data[Q->Front]; } } //判断当前队内是否有比该车号小的元素 bool IfLess(ElementType , Queue); //二分查找 void BinarySearch(int* , int , int ); #define MaxNum 100005 int main() { int n; scanf("%d", &n); Queue Q = CreateQueue(MaxNum); for (int i = 0; i < n; ++i) { int num; scanf("%d", &num); AddQ(Q, num); } int Track[MaxNum] = {0}; int T_num = 0; Track[T_num++] = DeleteQ(Q); while (!IsEmpty(Q)) { int tmp = DeleteQ(Q); if (tmp > Track[T_num - 1]) { Track[T_num++] = tmp; } else if (tmp < Track[T_num - 1]) { BinarySearch(Track, tmp, T_num); } } printf("%d\n", T_num); return 0; } bool IfLess(ElementType num, Queue Q) { for (int i = 0; i < (Q->Rear - Q->Front + Q->MaxSize) % Q->MaxSize; i++) { if (num > Q->Data[i]) return false; } return true; } void BinarySearch(int *Track, int tmp, int T_num) { //每个轨道的最后一个元素呈递增序 int _begin = 0, _end = T_num, mid; while (_begin < _end) { mid = _begin + (_end - _begin) / 2; if (Track[mid] > tmp) _end = mid; else if (Track[mid] < tmp) _begin = mid + 1; } Track[_end] = tmp; }

    仅供参考

    Processed: 0.011, SQL: 9