数据结构实验之栈六:下一较大值(二)
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 <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node
{
int num, id, next;
}a[112345];
int main()
{
int t;
scanf("%d", &t);
int i, j;
while(t--){
stack<struct node>q;
int n;
scanf("%d", &n);
for(j = 0;j < n;j++){
scanf("%d", &a[j].num);
a[j].id = j;
a[j].next = -1;
}
for(j = 0;j < n;j++){
if(q.empty()){
q.push(a[j]);
}else {
while(!q.empty()){
node x = q.top();
if(a[j].num > x.num){
a[x.id].next = a[j].num;
q.pop();
}else {
break;
}
}
q.push(a[j]);
}
}
for(i = 0;i < n;i++){
printf("%d-->%d\n",a[i].num,a[i].next);
}
cout << endl;
}
return 0;
}