zoukankan      html  css  js  c++  java
  • 数据结构实验之栈六:下一较大值(二)

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

    Time Limit: 150MS Memory Limit: 8000KB

    Problem Description

    对于包含n(1<=n<=100000)个整数的序列,对于序列中的每一元素,在序列中查找其位置之后第一个大于它的值,如果找到,输出所找到的值,否则,输出-1。

    Input

     输入有多组,第一行输入t(1<=t<=10),表示输入的组数;

    以后是 t 组输入:每组先输入n,表示本组序列的元素个数,之后依次输入本组的n个元素。

    Output

     输出有多组,每组之间输出一个空行(最后一组之后没有);

    每组输出按照本序列元素的顺序,依次逐行输出当前元素及其查找结果,两者之间以-->间隔。

    Example Input

    24 12 20 15 185 20 15 25 30 6 

    Example Output

    12-->2020-->-115-->1818-->-120-->2515-->2525-->3030-->-16-->-1

    Hint

     本题数据量大、限时要求高,须借助栈来完成。

    #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;
        stack<node>S;
        while(scanf("%d",&k)!=EOF)
        {
            for(int t = 1; t <= k; t++)
            {
                while(!S.empty())
                {
                    S.pop();
                }//栈清空
                scanf("%d",&n);
                for(int j = 1; j <= n; j++)
                {
                    scanf("%d",&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++)
                {
                    printf("%d-->%d\n",array[i].data,array[i].nextdata);
                }
                if(t != k)
                {
                    printf("\n");
                }
            }
        }
        return 0;
    }

  • 相关阅读:
    48. Rotate Image
    83. Remove Duplicates from Sorted List
    46. Permutations
    HTML5笔记
    18. 4Sum
    24. Swap Nodes in Pairs
    42. Trapping Rain Water
    Python modf() 函数
    Python min() 函数
    Python max() 函数
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/6444601.html
Copyright © 2011-2022 走看看