数据结构实验之栈与队列六:下一较大值(二)
Time Limit: 150MS
Memory Limit: 8000KB
Problem Description
对于包含n(1<=n<=100000)个整数的序列,对于序列中的每一元素,在序列中查找其位置之后第一个大于它的值,如果找到,输出所找到的值,否则,输出-1。
Input
输入有多组,第一行输入t(1<=t<=10),表示输入的组数;
以后是 t 组输入:每组先输入n,表示本组序列的元素个数,之后依次输入本组的n个元素。
Output
输出有多组,每组之间输出一个空行(最后一组之后没有);
每组输出按照本序列元素的顺序,依次逐行输出当前元素及其查找结果,两者之间以-->间隔。
Example Input
2 4 12 20 15 18 5 20 15 25 30 6
Example Output
12-->20 20-->-1 15-->18 18-->-1 20-->25 15-->25 25-->30 30-->-1 6-->-1
Hint
本题数据量大、限时要求高,须借助栈来完成。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//从数组后面倒着寻找最大值,把c数组初始化为-1,省去了给没有最大值的数处理的麻烦
int main()
{
int a[100005],stack[100005],c[100005];//a存数据,stack充当栈,c存最大值
int i,t,n,top;
while(~scanf("%d",&t))
{
while(t--)
{
top=0;
memset(c,-1,sizeof(c));
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=n-2;i>=0;i--)
{
if(a[i+1]>a[i]) //后一个数比当前数大,则当前数的最大值为后一个数
{
c[i]=a[i+1];
stack[++top]=a[i+1];
}
else //后一个数比当前数小
{
while(top!=0) //从栈顶开始找是否有比他大的数,在此过程中比他小的数会不断弹出栈
{
if(stack[top]>a[i])
{
c[i]=stack[top];
break;
}
top--;
}
}
}
for(i=0;i<n;i++)
printf("%d-->%d\n",a[i],c[i]);
if(t==1)
printf("\n");
}
}
return 0;
}
最近学STL,所以用c++里面的stack写一下这题。
没学过C++,只能半C半C++混着用啦...如果代码不规范,请见谅
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stack>
int a[100005],b[100005];
using namespace std;
int main()
{
int t,n,i;
while(~scanf("%d",&t))
{
while(t--)
{
stack<int>s;
memset(b,-1,sizeof(b));
cin>>n;
for(i=0; i<n; i++)
{
cin>>a[i];
}
for(i=n-2; i>=0; i--)
{
if(a[i]<a[i+1])
{
b[i]=a[i+1];
s.push(a[i+1]);
}
else if(a[i]>=a[i+1])
{
while(!s.empty())
{
if(a[i]<s.top())
{
b[i]=s.top();
break;
}
s.pop();
}
}
}
for(i=0; i<n; i++)
printf("%d-->%d\n",a[i],b[i]); //这个地方换成cout<<a[i]<<"-->"<<b[i]<<endl;就TLE了
if(t==1) //不懂为什么,求解释
cout<<endl;
}
}
return 0;
}