C + + Hoj train Pit Stop

Source: Internet
Author: User
Tags stdin

"Description of the problem"
Given a positive integer n represents the number of trains. 0<n<10, next enter the train inbound sequence, altogether N trains, each train numbered 1-9.

Requires a dictionary order to output the serial number of the train outbound.
Input:
There are several test cases, the first line of each set of input a positive integer n (0<n<10), the second row contains n positive integers, ranging from 1 to 9.


Output:
Outputs a dictionary-ordered train outbound serial number, with each number separated by a space and each output sequence wrapped. See Sample for details.


Example input:
3
1 2 3
Example output:
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1

"A solution to the problem"

The stack has advanced post-out, LIFO features, so no matter what a scheduling result should be 1, 2, 3, 4 an element in the full array. Because the order of the stack is small to large, so the stack sequence should meet the following conditions: For any number in the sequence after all its smaller than its number should be reversed, such as 4321 is a valid out of the stack, 1423 is not a valid stack result (4 is smaller than its two number 2, 3 is not reversed).

Accordingly. This can be done by the algorithm to generate a full array of n, and then will meet the stack rules of the sequence output.

This is defined recursively. Recursive algorithms such as the following:

#include <stdio.h> int cont=1;  void print (int str[],int n);      void Perm (int str[],int k,int n) {int i,temp; if (k==n-1) print (str,n),//k and n-1 are equal. That is, a trip to the end of the recursive else{for (i=k;i<n;i++) {//the current node element and perhaps the node element Exchange Temp=str[k]; str[k]=str[i]; str[i]=temp; Exchange Perm (STR,K+1,N);//Exchange the next node element with a node element temp=str[i]; STR[I]=STR[K]; str[k]=temp;//)}}///This function infers whether the integer sequence str[] satisfies the incoming and outgoing stack rules, if satisfied then output */void print (int str[],int n) {i       NT I,j,k,l,m,flag=1,b[2];           for (i=0;i<n;i++)//For each str[i] infer whether the smaller number is followed by a descending sequence */{m=0; for (j=i+1;j<n&&flag;j++) {if (Str[i]>str[j]) {if (m==0) b[m++]=                       str[j];//record Str[i] after it is smaller than the number else {//assuming that the number of occurrences is larger than the number of records, change the tag variable                      if (str[j]>b[0]) flag=0;                   Otherwise record this smaller number else b[0]=str[j];  }             }}} if (flag)/* satisfies the stack rule then outputs the sequence in str[] */{printf ("%2d:", cont+ +);       Output serial number for (i=0;i<n;i++) printf ("%d", str[i]);//output sequence printf ("\ n");       }} int main () {int str[100],n,i;     printf ("Input a int:");       /* The number of elements in the output arrangement */scanf ("%d", &n);             for (i=0;i<n;i++)/* Initialize permutation set */str[i]=i+1;       The first node is assigned i+1 printf ("Input the result:\n");              Perm (Str,0,n);       Call the recursive printf ("\ n");   return 0; }

"Two ways to solve the problem"
Here the so-called dictionary ordering means how many of these n trains have the possible order of outbound (that is, how many stacks in the data structure are in the stack order). The idea is to use three variables to store incoming trains, station trains, and outbound trains, in which train queue (queue) storage and station train use stack (stack) storage, outbound trains are used StringBuilder to store, detailed implementation is the use of recursive method, The parameters of the recursive function are the ternary group consisting of the values of the current train, station train, and outbound train, and the recursive end condition is. Both the train and the station train are empty. At this point the output of the outbound train is a possibility for all outbound, the recursive relationship for the current situation there is to let the next train stop or let a train station in two possible, for the two may be called recursively function. The solution of the problem can be obtained.

"Java Implementation"


"Three ways to solve the problem"
The problem can be refined into a given stack sequence. Find out the full stack order. The problem is a simulated problem, simulating the sequence of the stack out. There are 2 behaviors for each element after it has been added to the stack: out of the stack or residing on the stack. The whole process can be expressed in the form of a tree. So the use of the back method (backtracking process is the form of a lesson tree)
Backtracking method. The core is loop + recursion. In order to express correctness, each step of the operation (such as change data, stack, etc.)//should have a corresponding symmetric operation restore (such as change data restore, stack, etc.) #include <stdio.h> #include <string.h> #include  <vector> #include <algorithm> using namespace std;  int num;  int input[10];  int output[10];  int output_index;  int heap[10];  int heap_index;  vector<int* >vec;  void DF (int n);      void df (int n) {if (heap_index==0) return;  Exit stack into the input queue Output[output_index++]=heap[--heap_index];      Symmetrical 1 heap[heap_index]=0;          for (int i=0;i<2;i++) {if (i==0) DF (n);      else DF (n+1);   } Heap[heap_index++]=output[--output_index];      Symmetrical 1 output[output_index]=0;  } void DF (int n) {heap[heap_index++]=input[n]; Into.          Symmetric 2 if (n==num-1)//When the function exits (generally in backtracking, there is no symmetric structure inside the function exit, but there are other functions in the problem DF call the backtracking function, so return to) {int temp=heap_index; Output[output_index++]=heap[--heap_index];            Symmetrical 3 heap[heap_index]=0; while (Heap_index)             Output[output_index++]=heap[--heap_index];          int *p= (int *) malloc (sizeof (int) *num);          for (int i=0;i<output_index;i++) p[i]=output[i];          Vec.push_back (P);              while (temp)//symmetric 3 {Heap[heap_index++]=output[--output_index];              output[output_index]=0;          temp--;          } heap[--heap_index]=0;          Symmetric 2 return;          } for (int i=0;i<2;i++) {if (i==0) DF (n);   else DF (n+1);      I==1 the time is not to pull the data out of the stack} heap[--heap_index]=0; Symmetric 2} BOOL CMP (int* t1,int* T2) {for (int i=0;i<num;i++) {if (T1[i]==t2[i]) CO          Ntinue;      Return t1[i]<t2[i];  } return true;      } int main () {freopen ("A.txt", "R", stdin);          while (scanf ("%d", &num)!=eof) {memset (input,0,sizeof (input)); memset (Output,0,sizeof (inPut));          memset (heap,0,sizeof (input));          output_index=0;          heap_index=0;          Vec.clear ();          for (int i=0;i<num;i++) scanf ("%d", input+i);          DF (0);          Sort (Vec.begin (), Vec.end (), CMP); for (unsigned int i=0;i<vec.size (), i++) {for (int j=0;j<num-1;j++) printf ("%d              ", Vec[i][j]);          printf ("%d\n", vec[i][num-1]);  }} return 0;   }

"Four ways to solve the problem"
StL Method: 1, if N=1 then a sort of way. 2, N>1 first find out the n-1 of the stack order. Then separate n before inserting n-1. After n-1 and each number after each n-1!
#include <iostream> #include <string> #include <algorithm> #include <vector>using namespace std void Helper (String &inTrain,vector<string> &outtrain,int index) {if (index = = intrain.size ()) {RET    Urn        }//if if (index = = 0) {string outnum ("");        Outnum + = Intrain[index];    Outtrain.push_back (Outnum);        }//if else{vector<string> Newouttrain;        Out stack sequence int size = Outtrain.size ();            Index train into the stack for (int i = 0;i < Size;++i) {//I-out stack sequence int count = Outtrain[i].size ();            Looking for the previous inbound train subscript int targetindex; for (int j = 0;j < Count;++j) {if (intrain[index-1] = = Outtrain[i][j]) {Targetindex = j                    ;                Break            }//if}//for string tmp (Outtrain[i]); for (int j = targetindex;j <= count;++j) {Tmp.insert (Tmp.begin () +j,intrain[index]);                Newouttrain.push_back (TMP);            Tmp.erase (Tmp.begin () +j);    }//for}//for Swap (outtrain,newouttrain); }//else Helper (intrain,outtrain,index+1);}    Vector<string> trainleft (String intrain) {vector<string> result;    int size = Intrain.size ();    if (size <= 0) {result;    }//if Helper (intrain,result,0);    Sort (Result.begin (), Result.end ()); return result;}    int main () {int n;    Freopen ("C:\\users\\administrator\\desktop\\c++.txt", "R", stdin);        while (cin>>n) {string train ("");        int num;            for (int i = 1;i <= n;++i) {cin>>num;        Train + = num + ' 0 ';        }//for vector<string> trainnum = Trainleft (train);        output int size = Trainnum.size ();            for (int i = 0;i < size;++i) {int count = Trainnum[i].size (); for (int j = 0;j < Count;++j) {if (j = = 0) {Cout<<traINNUM[I][J];                }//if else{cout<< "" <<trainNum[i][j];        }//else}//for cout<<endl; }//for}//while return 0;}


C + + Hoj train Pit Stop

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.