Problem Description
对于包含n(1<=n<=1000)个整数的序列,对于序列中的每一元素,在序列中查找其位置之后第一个大于它的值,如果找到,输出所找到的值,否则,输出-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
Author
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
int next;
int id;
}p;
void nextmax(int n)
{
int i,j;
stack <struct node> s;
p a[100010],t;
for(i=0;i<n;i++)
{
cin>>a[i].data;
a[i].next=-1;
a[i].id=i;
if(s.empty())
s.push(a[i]);
else
{
while(!s.empty())
{
t=s.top();
if(t.data<a[i].data)
{
a[t.id].next=a[i].data;
s.pop();
}
else
break;
}
s.push(a[i]);
}
}
for(i=0;i<n;i++)
cout<<a[i].data<<"-->"<<a[i].next<<endl;
}
int main()
{
int i,n,m;
cin>>n;
while(n--)
{
cin>>m;
nextmax(m);
if(n)
cout<<endl;
}
return 0;
}
本文介绍了一种算法,该算法针对一个整数序列,为每个元素找到在其右侧的第一个比它大的数值,并输出这些结果。例如,对于序列[12, 20, 15, 18, 20, 15, 25, 30],输出将为12->20, 20->-1, 15->18, 18->-1, 20->25, 15->25, 25->30, 30->-1。使用栈来高效实现这一功能。

被折叠的 条评论
为什么被折叠?



