0

すべての最も近い小さい値の問題を解決するためのコードを作成したいのですが、これが私の努力です

#include<iostream>
#include<stack>
using namespace std;
void all_smallest(int a[],int n)
{
    stack<int>s;
    for(int x=0;x<n;x++)
    {
        while(!s.empty() && s.top()>=a[x])
        {
            cout<<s.top();
            s.pop();
        }
        if(s.empty()){ continue;}
        else
        {
            s.push(a[x]);
        }

    }
}

int main()
{
    int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
    int n=sizeof(a)/sizeof(a[0]);
    all_smallest(a,n);

    return 0;
}

コンパイルされますが、出力がありません、なぜですか?助けてください

4

2 に答える 2

2

ウィキペディアをチェックすると、アルゴリズムが正しく実装されていません。あるべき姿は次のとおりです。

    #include<iostream>
    #include<stack>
    using namespace std;
    void all_smallest(int a[],int n)
    {
        stack<int>s;
        for(int x=0;x<n;x++)
        {
            while(!s.empty() && s.top()>=a[x])
            {
                s.pop();
            }
            if(!s.empty())
            {
                cout<<s.top();
            }
            s.push(a[x]);
        }
    }

    int main()
    {
        int a[]={0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
        int n=sizeof(a)/sizeof(a[0]);
        all_smallest(a,n);
        cout << "\n";
        return 0;
    }

出力:

    004022601151337
于 2012-04-16T17:41:55.900 に答える
1

sは最初は空であるため、else句は発生しません(したがって、sは空のままです)。

于 2012-04-16T17:29:33.383 に答える