SDUT 3333 数据结构实验之栈六:下一较大值(二)

来源:互联网 发布:打印发票软件 编辑:程序博客网 时间:2024/05/21 12:43

点击打开题目链接

#include <bits/stdc++.h>using namespace std;struct node{    int data;//当前数值    int Id;//标记当前数值Id所在,若找到其后的较大值,更新其所在Id数值    int nextdata;//下一较大值};node _array[100010];int main(){    int n, k, m;    stack<node>S;    while(cin >> k)    {        for(int t = 1; t <= k; t++)        {            while(!S.empty())            {                S.pop();            }//栈清空            cin >> n;            for(int j = 1; j <= n; j++)            {                cin >> _array[j].data;                _array[j].Id = j;                _array[j].nextdata = -1;                if(S.empty())                {                    S.push(_array[j]);                }                else                {                    while(!S.empty())//不断取其栈顶元素,更新其栈顶元素下一较大值                    {                        node tmp = S.top();//取栈顶元素                        int k = tmp.Id;//获取栈顶元素Id                        if(tmp.data < _array[j].data)                        {                            _array[k].nextdata = _array[j].data;//更新栈顶元素Id所在的较大值                            S.pop();//将较大值出栈                        }                        else break;                    }                    S.push(_array[j]);//将当前数值入栈,便于查找当前值下一较大值                }            }            for(int i = 1; i <= n; i++)            {                cout << _array[i].data << "-->" << _array[i].nextdata << endl;            }            if(t != k)            {                cout << endl;            }        }    }    return 0;}


0 0
原创粉丝点击