Poj-1363-Rails-栈

来源:互联网 发布:淘宝店铺id 编辑:程序博客网 时间:2024/05/22 06:25

题面:
There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.
大意:
给出若干个长度为n的序列,问该序列能否由序列123……n依次入栈并出栈得到
AC代码:

int coach[1001];//车厢stack<int> s;//栈int main(){    int n;    while(scanf("%d",&n) && n)//简洁的判断方法,学习了    {        while(scanf("%d",&coach[1]) && coach[1])//同上        {            for(int i = 2; i <= n; ++i)//输入剩余车厢的编号                scanf("%d",&coach[i]);            int j = 1;//指针            for(int i = 1; i <= n; ++i)//模拟序列123......n入栈的过程            {                s.push(i);//入栈                //首先要判断非空,才能访问栈顶元素                //这里用到循环是因为可能会执行多次                while(!s.empty() && s.top() == coach[j])//栈顶元素是否等于coach的第j个元素                {                    s.pop();//是的话就出栈                    j++;//指针后移                }            }            if(j == n + 1)//j是否被累加了n次,是的话就代表这n个数全部出栈,此时栈为空                printf("Yes\n");            else                printf("No\n");            //为什么需要重置?            //明明会被覆盖!            memset(coach,0,sizeof(coach));// ?????写了这句就AC了        }        cout << endl;    }    return 0;}

解决方法:
①while(~scanf(“%d%d”,&m,&n))等同于while(scanf(“%d%d”,&m,&n) != EOF)
因为EOF为-1,-1十六进制补码表示为0xffffffff,f是二进制的1111,所以按位取反后就会变成0
②忘记s.pop()会导致死循环
③一个方向不行就换一个方向。说不定那个方向易于实现

原创粉丝点击