火车进站问题(栈相关)

问题出在哪里呢?好像是输入6以后有什么没初始化,导致后面的答案错了,如果我第一组就输入6答案就是对的了,有大佬帮忙指出问题吗

img

img

#include<stdio.h>
int a[100000],b[100000];
int main()
{
    int n,i,t;
    while(scanf("%d",&n),n)
    {
        while(scanf("%d",&a[0]),a[0])
        {
            int top=1;
            for(i=1;i<n;i++)
            {
                scanf("%d",&a[i]);
            }
            i=1,t=0;
            while(i<=n)
            {
                b[top]=i;
                while(a[t]==b[top]&&t<n)
                {
                    printf("%d ",a[t]);
                    top--;
                    t++;
                }
                top++;
                printf("%d\n",top);
                i++;
            }
            if(top==1)
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
        }
        printf("\n");
    }
}



#include <stack>
#include <list>
using namespace std;
 
int total=0;  //记录出站的可能数目
int SIZE;  //输入几列火车
list<int> output;  //采用list来存储结果序列,如果采用copy方式保存,那么每次都复制会浪费内存;
//如果用栈的话每次结束需要弹栈再压栈,也不划算,上面已经讲过
stack<int> to; //存储当前火车站的序列
void dispatch(int *from,int fPos,int tPos){
    //fPos火车出到第几列,tPos火车站的火车还有几列
    if(fPos == SIZE && tPos ==0){ //终止
            total++;
            list<int>::iterator it;
            for(it=output.begin();it!=output.end();it++){
                cout<<*it;
            }
            cout<<endl;
            return;
    }
    if(!to.empty()){ //我们先让当前列直接出,这样最终的顺序是从小到大的排列
        int popped = to.top();
        to.pop();
        output.push_back(popped);
        dispatch(from,fPos,tPos-1);  //从火车站开出去一列
        output.pop_back();        //保证回溯的结果序列回到之前状态
        to.push(popped);
    }
 
    if(fPos<SIZE){
        int tmp = from[fPos];
        to.push(tmp);
        dispatch(from,fPos+1,tPos+1);    //火车站进来一辆火车
        to.pop();
    }
}
 
 
int main(){
    cout<<"please input total size of the train"<<endl;
    while(SIZE<=0){
        cout<<"请输入大于0的整数"<<endl;
        cin>>SIZE;
    }
    int arr[SIZE]; //初始的火车序列
    for(int i=0;i<SIZE;i++){
        arr[i] = i+1;
    }
    dispatch(arr,0,0);
    printf("共有%d种出站顺序\n",total );
    return 0;
}