This repository has been archived on 2024-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
justhomework/ex8/ex8.cpp

115 lines
2.9 KiB
C++
Raw Normal View History

2021-11-18 12:44:57 +00:00
#include "queue.hpp"
#include <stdio.h>
#include <time.h>
2021-11-18 13:42:21 +00:00
#define JIE 10
2021-11-18 12:44:57 +00:00
class Train
{
private:
2021-11-18 13:42:21 +00:00
int _v[10];
Queue<int> come[2];
2021-11-18 12:44:57 +00:00
Queue<int> temp[4];
Queue<int> out;
public:
Train()
{
srand(time(NULL));
for (int i = 0; i < JIE; i++)
_v[i] = JIE - i;
for (int i = 0; i < JIE; i++)
swap(i, rand() % JIE);
printf("入队序列: \n");
2021-11-18 13:42:21 +00:00
printf("#1到达轨 ");
for (int i = 0; i < 5; i++)
{
come[0].enqueue(_v[i]);
printf("%2d ", _v[i]);
}
printf("\n");
printf("#2到达轨 ");
for (int i = 5; i < 10; i++)
2021-11-18 12:44:57 +00:00
{
2021-11-18 13:42:21 +00:00
come[1].enqueue(_v[i]);
printf("%2d ", _v[i]);
2021-11-18 12:44:57 +00:00
}
printf("\n");
}
bool orgnize()
{
int j = 0;
2021-11-18 13:42:21 +00:00
while (!come[1].empty() || !come[0].empty())
2021-11-18 12:44:57 +00:00
{
for (int i = 0; i < 4;)
{
2021-11-18 13:42:21 +00:00
if (temp[i].back() <
(come[1].front() < come[0].front() ?
(come[1].front() ? come[1].front() : come[0].front()) :
(come[0].front() ? come[0].front() : come[1].front())))
2021-11-18 12:44:57 +00:00
{
2021-11-18 13:42:21 +00:00
printf("%2d号车厢由#%d到达轨推入#%d缓冲轨 \n",
(come[1].front() < come[0].front() ?
(come[1].front() ? come[1].front() : come[0].front()) :
(come[0].front() ? come[0].front() : come[1].front())),
(come[1].front() < come[0].front() ?
(come[1].front() ? 2 : 1) :
(come[0].front() ? 1 : 2)),
i + 1);
temp[i].enqueue(
(come[1].front() < come[0].front() ?
(come[1].front() ? come[1].dequeue() : come[0].dequeue()) :
(come[0].front() ? come[0].dequeue() : come[1].dequeue())));
2021-11-18 12:44:57 +00:00
}
else
{
j++;
i++;
2021-11-18 13:42:21 +00:00
if (j > 100)
2021-11-18 12:44:57 +00:00
return false;
}
}
}
return true;
}
int Out()
{
for (int i = 1; i <= JIE;)
{
2021-11-18 13:42:21 +00:00
for (int j = 0; j < 4; j++)
2021-11-18 12:44:57 +00:00
{
2021-11-18 13:42:21 +00:00
if (temp[j].front() == i)
2021-11-18 12:44:57 +00:00
{
2021-11-18 13:42:21 +00:00
printf("%2d号车厢经#%d缓冲轨推入出发区出发队列为 ", temp[j].front(), j + 1);
2021-11-18 12:44:57 +00:00
out.enqueue(temp[j].dequeue());
2021-11-18 12:54:44 +00:00
for (int i = 0; i < out.size(); i++)
printf("%d ", out[i]);
printf("\n");
2021-11-18 12:44:57 +00:00
i++;
}
}
}
return 0;
}
protected:
void swap(int a, int b)
{
int temp = _v[a];
_v[a] = _v[b];
_v[b] = temp;
}
};
int main()
{
Train T;
T.orgnize() ? T.Out() : printf("编组失败\n");
return 0;
}