美文网首页
ACM——栈

ACM——栈

作者: 香儿1025 | 来源:发表于2018-02-03 21:54 被阅读0次

知识点:

(原理)所谓栈即只能单进单出的顺序列,对于一串以某种顺序进栈的数列A我们要判断它是否能通过某种序列B出栈需要借用第三个栈C,依次把A的数列进栈C,每进一个判断一次C栈栈顶的数是否能与B栈将出的第一个数相同,若是相同则把栈C的栈顶出栈,同时把栈B的第一个欲出数换成第二个欲出数,即在逻辑上把栈B的第一个欲出数出栈,然后栈C继续将栈A的数依次进栈、判断、进栈、判断。

(例题)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1022

题目分析: 此题是一个典型的栈题,用栈的方法解决。用in与out数组分别代表进栈与出栈用res数组来模仿第三个交换栈。

题解代码:


#include<stdio.h>

#include<stdlib.h>

#include<math.h>

int main()

{

    charin[100],out[100],res[200]={'\0'};

    intn,flag[200],i=0,j=0,top=0;

   while(scanf("%d",&n)!=EOF){

       scanf("%s",in);

       scanf("%s",out);

       for(i=0;i<=n;){

           if(res[0]=='\0'){              

                    if(top<0){

                        top=0;

                    }

               res[top]=in[i];

               top=strlen(res)-1;

               flag[i+j]=0;

               i++;

            }

           if(res[0]!='\0' && res[top]!=out[j]){

               res[top+1]=in[i];

               top=strlen(res)-1;

               flag[i+j]=0;

               i++;

           }

           if(res[0]!='\0' && res[top]==out[j]){

               res[top]='\0';

               top=strlen(res)-1;

               flag[i+j]=1;

               j++;

           }

        }

       if(res[0]=='\0'){

               printf("Yes.\n");

       for(i=0;i<2*n;i++){

               if(flag[i]==0){

                    printf("in\n");

               }

               else{

                    printf("out\n");

               }

        }

               printf("FINISH\n");

        }

       else{

               printf("No.\n");

           printf("FINISH\n");

        }

       for(i=0;i<2*n;i++){

           res[i]='\0';

        }

  top=0,j=0;

    }

}

相关文章

网友评论

      本文标题:ACM——栈

      本文链接:https://www.haomeiwen.com/subject/enrpzxtx.html