火车车厢重排(链队列)

来源:互联网 发布:网络扒皮是什么意思 编辑:程序博客网 时间:2024/05/01 17:31

1.题目:

 

Problem Description

一列货运列车共有n节车厢,每节车厢将停放在不同的车站。假定n个车站的编号分别为1~n,即货运列车按照第n站至第1站的次序经过这些车站。为了便于从列车上卸掉相应的车厢,车厢的编号应与车站的编号相同。这样,在每个车站只需卸掉最后一节车厢。因此,对于给定的任意次序车厢,必须进行重新排列,使其符合要求。车厢重排工作可通过转轨站完成,在转轨站中有一个入轨、一个出轨和k个缓冲轨,缓冲轨位于入轨和出轨之间。假定缓冲轨按先进先出的方式工作,现要求设计算法解决火车车厢重排问题。

 

Input

有多组数据,每组第一行为车厢节数n和缓冲轨数目k(2<=k<=5,k<=n<=10),第二行为初始给定的车厢编号次序序列。

 

Output

若给定的车厢编号次序序列可重排,则输出1;否则输出0。

 

Sample Input

9 33 6 9 2 4 7 1 8 59 33 6 9 2 4 7 5 8 1

 

Sample Output

10

 

 

2.参考代码:

 

#include <iostream>using namespace std;struct Node{int data;Node* next;};class LinkQueue{private:Node* front,* rear;public:LinkQueue();   ///构造函数~LinkQueue();   ///析构函数void EnQueue(int x);   ///入队列int DeQueue();   ///出队列int GetFront(){   ///获得队头元素if(!empty())return front->next->data;}int GetRear(){   ///获得队尾元素if(front!=rear)return rear->data;}bool empty(){   ///判断队列是否为空if(front==0)return true;elsereturn false;}void Trans();   ///遍历火车车厢序列friend void PermuteTrans(int* arr,LinkQueue* a,int n,int k);   ///重排火车车厢序列};LinkQueue::LinkQueue(){Node* s=new Node;s->next=NULL;front=rear=s;}LinkQueue::~LinkQueue(){Node* p=new Node;p->next=NULL;front=rear=p;}void LinkQueue::EnQueue(int x){Node* s=new Node;s->data=x;s->next=NULL;rear->next=s;rear=s;}int LinkQueue::DeQueue(){if(!empty()){   ///队列不空才能出队Node* p=new Node;p=front->next;int x=p->data;if(p->next==NULL)rear=front;delete p;return x;}}void LinkQueue::Trans(){Node* p=front->next;while(p){cout<<p->data<<" ";p=p->next;}}void PermuteTrans(int* arr,LinkQueue* a,int n,int k){int i=0;bool flag=true;   ///设置标志,初始为真while(i<n && flag){   ///当还有车厢没有进入缓冲轨时flag=false;   ///改变标志for(int j=0;j<k;j++){if(a[j].GetRear()<arr[i] || a[j].front->next==NULL)///如果某条缓冲轨道的第一个车厢的编号小于即将进来的车厢编号,那么他就可以进入轨道///或者某条缓冲轨道空置的时候也可以进入轨道{a[j].EnQueue(arr[i]);   ///入队列flag=true;   ///改变标志i++;   ///下标加一break;   }}}if(flag)   ///如果全部进入轨道,说明可以排cout<<1<<endl;else   ///否则排不了cout<<0<<endl;}int main(){int i,n,k,a[1111];while(cin>>n>>k){for(i=0;i<n;i++)cin>>a[i];LinkQueue lq;for(i=0;i<n;i++)lq.EnQueue(a[i]);LinkQueue* H=new LinkQueue[k];PermuteTrans(a,H,n,k);}return 0;}