火车车厢重排(链队列)

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 3
3 6 9 2 4 7 1 8 5
9 3
3 6 9 2 4 7 5 8 1

 

Sample Output

1
0

 

 

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;
		else
			return 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;
}


 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值