桔梗页子 2021-12-06 02:36 采纳率: 33.3%
浏览 45

火车进站问题(栈相关)

问题出在哪里呢?好像是输入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");
    }
}

  • 写回答

1条回答 默认 最新

  • 五一编程 2021-12-06 08:30
    关注
    
    
    #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;
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 12月6日

悬赏问题

  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表