1473-数据结构:出栈顺序的判定

本题考查栈的应用之“栈混洗”,O(n2)的算法可直接根据提示写出。

对于任意一个长度为n(1~n)的序列,栈混洗总数为 ( (2*n)! ) / ( (n+1)! * n! )

另外,直接借助栈A、B、S,模拟混洗过程,每次S.pop之前,检查S是否为空,或需弹出的元素在S中,却非栈顶元素,可导出O(n)的算法

详情请参考《数据结构(邓俊辉)》第四章C3

#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
    //#ifndef _OJ_  //ONLINE_JUDGE
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    //#endif
    int m, n, a[1000];
    scanf("%d", &m);
    while (m--)
    {
        int t = 0, i, j;
        scanf("%d", &n);
        for (int i = 0; i < n; i++)
            scanf("%d", &a[i]);
        for (i = 0; i < n - 1; ++i)
        {
            t = a[i];
            for (j = 1; j < n; ++j)
            {
                if (a[j] < a[i])
                {
                    if (t > a[j]) t = a[j];
                    else break;
                }
            }
            if (j < n) break;
        }
        if (i == n - 1 && j == n)printf("YES\n");
        else    printf("NO\n");
    }
    return 0;
}

 

posted @ 2015-01-16 21:03  swanGooseMan  阅读(233)  评论(0编辑  收藏  举报