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
本题数据量大、限时要求高,须借助栈来完成。
Source
思路:
此题用双重for循环会超时,因此思路是简化第二重循环的次数。
a数组存所给数据,b数组是答案,c数组是存当答案不是a[i+1]>a[i]的时候,c数组从前往后寻找b对应的数(在序列中查找其位置之后第一个大于它的值)并且通过
while(top!=1)
{
if(c[top]<c[top-1])
{
b[i]=c[top-1];
f=1;
break;
}
else//用来减少c数组的长度。
{
c[top-1]=c[top];
top–;
}
}
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int i,j,T,n,m,a[100005],b[100005],c[100005];
cin>>T;
while(T--)
{
cin>>n;
for(i=1; i<=n; i++)
scanf("%d",&a[i]);
int top=0;
b[n]=-1;
c[++top]=a[n];
for(i=n-1; i>=1; i--)
{
c[++top]=a[i];
if(a[i+1]>a[i])
b[i]=a[i+1];
else
{
int f=0;
while(top!=1)
{
if(c[top]<c[top-1])
{
b[i]=c[top-1];
f=1;
break;
}
else
{
c[top-1]=c[top];
top--;
}
}
if(f==0)
b[i]=-1;
}
}
for(i=1; i<=n; i++)
cout<<a[i]<<"-->"<<b[i]<<endl;
if(T!=0)
cout<<endl;
}
}