您的位置:首页 > 理论基础 > 数据结构算法

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

2018-03-19 21:27 302 查看
数据结构实验之栈与队列六:下一较大值(二)

Time Limit: 150 ms Memory Limit: 8000 KiB

Submit Statistic

Problem Description

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

Input

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

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

Output

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

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

Sample Input

2

4 12 20 15 18

5 20 15 25 30 6

Sample Output

12–>20

20–>-1

15–>18

18–>-1

20–>25

15–>25

25–>30

30–>-1

6–>-1

Hint

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

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;
typedef struct
{
int d;
int n;
int id;
}da;
da a[1001111];
int main()
{
stack<da>s;
int t;
//?
while(cin>>t)
{
while(t--)
{
int n;
cin>>n;
int i;
for(i=0; i<n; i++)
{
cin>>a[i].d;
a[i].n = -1;
a[i].id = i;
}
for(i=0; i<n; i++)
{
if(s.empty())
{
s.push(a[i]);
}
else
{
while(!s.empty())
{

if(s.top().d < a[i].d)
{
a[s.top().id].n = a[i].d;
s.pop();
}
else
{
break;
}
}
s.push(a[i]);
}
}
while(!s.empty())
s.pop();
for(i=0; i<n; i++)
{
cout<<a[i].d<<"-->"<<a[i].n<<endl;
}
if(t!=0)
cout<<endl;
}

}
return 0;
}

/***************************************************
User name: jk160532姜兴友
Result: Accepted
Take time: 152ms
Take Memory: 2180KB
Submit time: 2017-10-18 13:47:57
****************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: