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

来源:互联网 发布:中国跳水最厉害的知乎 编辑:程序博客网 时间:2024/06/05 11:44
#include <bits/stdc++.h>#include <iostream>using namespace std;struct node{    int data;    int next;//记录下一个元素死亡值    int pos;//用来记录每个元素的位置*/} a[100001],val[100000];int main(){    int t;    while(~scanf("%d",&t))    {        int l=0;        while(t--)        {            int n;            scanf("%d",&n);            for(int i=0; i<n; ++i)            {                cin>>a[i].data;                a[i].pos=i;                if(i==0)                {                    val[l]=a[i];                    ++l;                }                else                {                    for(int j=l-1; j>=0; --j)                    {                        if(a[i].data>val[j].data)                        {                            a[val[j].pos].next=a[i].data;                            //cout<<a[val[j].pos].data<<"-jkj->"<<a[i].data<<endl;                            val[j]=a[i];                        }                        else                        {                            val[l++]=a[i];                            break;                        }                    }                }            }            for(int i=0; i<l; ++i)            {               // cout<<val[i].data<<endl;                a[val[i].pos].next=-1;            }            for(int i=0; i<n; ++i)              printf("%d-->%d\n",a[i].data,a[i].next);//[i].data<<"-->"<<a[i].next<<endl;        }    }    return 0;}

AC

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<stack>#define N 100001using namespace std;struct node{    int num;int id;int next;};struct node a[N];int main(){    int t;    scanf("%d",&t);    stack <struct node > p;    for(int i=1; i<=t; i++)    {        while(!p.empty())        {            p.pop();        }        int n;        if(i>1)            printf("\n");        scanf("%d",&n);        for(int j=1; j<=n; j++)        {            scanf("%d",&a[j].num);            a[j].id=j;            a[j].next=-1;            if(p.empty())            {                p.push(a[j]);            }            else            {                while(!p.empty())                {                    struct node b;                    b=p.top();                    if(b.num<a[j].num)                    {                        a[b.id].next=a[j].num;                        p.pop();                    }                    else                        break;                }                p.push(a[j]);            }        }        for(int j=1; j<=n; j++)        {            printf("%d-->%d\n",a[j].num,a[j].next);        }    }    return 0;}




0 0
原创粉丝点击