杭电acm1022(用栈进行配对)

http://acm.hdu.edu.cn/showproblem.php?pid=1022

刚开始想着用数组逐个进行判断,但是发现非常麻烦,得记录较多变量,当然,也可能自己太菜了,。。。下学期开始时学到了栈,感觉情形很像,就想着用栈来做,一边存入,一边和另一个字串,也就是O2进行比较,一旦有相同的,就出栈,这样能很全面的按照O2的顺序输出了,当最后栈顶元素为空时,就是可以按顺序输入,输出了,另外,用一个数组来存储每一次的进栈和出栈,最后输出“in”和“out”

View Code
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct node1{
 4                      char s;
 5                      struct node1 *next;//栈的结构 
 6                      }zh; 
 7 typedef struct node2{
 8                      zh *top;
 9                      }tou;//栈顶结构 
10 tou *creat()//初始化栈 
11 {
12    tou *S;
13    S=(tou *)malloc(sizeof(tou));
14    S->top=NULL;
15    return (S);
16 }
17 void push(tou *S,char a)//进栈 
18 {
19      zh *L;
20      L=(zh *)malloc(sizeof(zh));
21      L->s=a;
22      L->next=S->top;
23      S->top=L;
24 }
25 void take(tou *S)//出栈 
26 {
27      zh *L;
28      L=S->top;
29      S->top=S->top->next;
30      free(L);
31 }
32 tou *S;
33 int main()
34 {
35     char  in[50],out[50];
36     int n,i,len,j,ans[100],a;
37     while(scanf("%d ",&len)!=EOF)
38     {
39       S=creat();
40       scanf("%s %s",in,out);
41       j=0;
42       a=0;
43       
44       
45       for(i=0;in[i]!='\0';i++)
46       {
47           if(S->top==NULL||S->top->s!=out[j])
48           {
49            push(S,in[i]);//没有和O2一样的字串时或空栈时进栈 
50            ans[a++]=1;
51           }
52           if(S->top->s==out[j])
53           {
54               while(S->top&&S->top->s==out[j]&&out[j])
55               {
56                 take(S);
57                 j++;
58                 ans[a++]=0;// 有相同的时候出栈 
59               }
60           }
61       }
62       
63       
64       if(S->top!=NULL)
65         printf("No.\n");
66       else {
67             printf("Yes.\n");
68             for(i=0;i<a;i++)
69              if(ans[i])
70               printf("in\n");
71              else printf("out\n");
72            }
73       printf("FINISH\n");
74     }
75     return 0;
76 }

这题算是用栈进行记录的标志性成功^_^

posted @ 2013-04-23 22:50  执着追求的IT小小鸟  阅读(167)  评论(0编辑  收藏  举报