C++ Queue Example Rearranging RailRoad Cars 火车车厢重排问题
Before in article C++ Stack Example Rearranging RailRoad Cars 火车车厢重排问题
The Whole Code
// RailRoadQueue.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include #include using namespace std;template void PrintfNum(T a[], const int & n);bool Hold(queue q[], int n,int totalQueue){ for(int i=0;i q[], int n, int totalQueue,int& min){ for(int i = 0;i< totalQueue;++i){ if(!q[i].empty() && q[i].front() == min){ cout << "Move car " << q[i].front() << " from holding track " << i << " to output" << endl; q[i].pop(); ++min; i = -1;// find next car from the first holding track 0 } }}int main(int argc, char* argv[]){ const int NUM = 9; const int QUEUENUM = 2; queue q[QUEUENUM]; int min = 1; int a[NUM] = {5,8,1,7,4,2,9,6,3}; PrintfNum(a,NUM); for(int i = NUM - 1; i >=0 ;--i){ if(a[i] == min){ cout << "Move car " << a[i] << " from input to output" << endl; ++min; //move cars from holding tracks OutPut(q,a[i],QUEUENUM,min); }else{// move cars to holding tracks if(!Hold(q, a[i] ,QUEUENUM)){ cout << "Not enough holding track" << endl; break; } } } return 0;}template void PrintfNum(T a[], const int & n){ for(int i = 0; i < n; ++i){ cout << a[i] << ","; } cout << endl;}
While two holding track are sufficient to rearrange the cars from the initial ordering of gif picture. However, other initial arrangements may need more tracks. For example, the inital arrangement 1, 2, 3, 4, 5, 6, 7, 8, 9 requires 8 holding tracks.
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~