车厢调度问题-递归算法

来源:互联网 发布:东方航空网络值机 编辑:程序博客网 时间:2024/06/05 17:51

第一篇博文,小激动。

问题描述:

假设停在铁路调度站入口处的车厢系列的编号依次为1,2,3,…n。设计一个程序,求出所有可能由此输出的长度为n 的车厢系列。


解法综述:

车厢调度问题的每次操作都有两种选择:①车厢进调度站②车厢直接出站。因此,一种显而易见的解法是递归模拟车厢的调度过程,得到所有可能的输出序列。
设置两个栈
s1:代表车厢初始状态所在的铁轨
s2:代表调度站
设置一个数组
list:存储车厢的输出序列
每次调度抽象为一个递归方法onestep,递归出口为s1 s2均为空的状态

代码实现:

首先自定义一个栈,考虑到通用编程,使用了模板

*****Stack.h*****

#pragma once#include<iostream>using namespacestd; template<classT>class Stack{public:    Stack(intMaxStackSize = 10);    ~Stack(){ delete[]stack; }    bool IsEmpty()const{ returntop == -1; }    bool IsFull()const{ returntop == MaxTop; }    T Top()const;    Stack<T>&Add(constT&x);    Stack<T>&Delete(T&x);private:    int top;    int MaxTop;    T*stack;}; template<classT>Stack<T>::Stack(intMaxStackSize){    //Stack类构造函数    MaxTop = MaxStackSize - 1;    stack = new T[MaxStackSize];    top = -1;} template<classT>T Stack<T>::Top()const{    //返回栈顶元素    if (IsEmpty())cout <<'aaa';//throw OutOfBounds();    return stack[top];} template<classT>Stack<T>&Stack<T>::Add(constT& x){    //添加元素x    if (IsFull())       cout << 'aaa';//throw NoMem();    else       stack[++top] =x;    return *this;} template<classT>Stack<T>&Stack<T>::Delete(T&x){    if (IsEmpty())       cout << 'aa';//throw OutOfBounds();    else       x = stack[top--];    return *this;}



****main.cpp****

#include <iostream>#include "Stack.h"using namespacestd; template<classT>void onestep(Stack<T>&s1, Stack<T>& s2,int *list,int count,int listsize)//注意 s1,s2必须为引用!!!!保持其唯一性!!!!{//将一个对象放入list中或者放入堆栈中等待输出    int temp;    if (!s1.IsEmpty()){       s1.Delete(temp);       s2.Add(temp);       onestep(s1,s2, list,count, listsize);       s2.Delete(temp);       s1.Add(temp);    }    if (!s2.IsEmpty()){       s2.Delete(temp);       list[count - 1] =temp;       onestep(s1,s2, list,count + 1, listsize);       s2.Add(temp);       list[count - 1] = 0;    }//当原堆栈和中专堆栈都为空时,输出list    if (s1.IsEmpty() &&s2.IsEmpty()){       for (inti = 0; i<listsize;i++)           cout << list[i];       cout << endl;    }} void main(){    Stack<int>s1, s2,s3;    int n;    cout << 'n' << ':';    cin >> n;    for (inti = n;i >= 1; i--)       s1.Add(i);    int *list =new int[n];       onestep(s1,s2, list, 1,n);}






0 0
原创粉丝点击