数据结构实验之栈五:下一较大值(一)
Time Limit: 1000MS Memory Limit: 65536KB
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
Hint
本题的数据量小、限时要求低,可以不用栈来完成。
Author
PS:数据量小,直接for循环求解即可 栈的操作方法,下一较大值二
AC:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t, n, x[10000] = {0}, i, j;
while(~scanf("%d", &t))
{
while(t--)
{
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &x[i]);
}
for(i = 0; i< n; i++)
{
int flag = 0;
for(j = i + 1; j < n; j++)
{
if(x[j] > x[i])
{
flag = 1;
printf("%d-->%d\n", x[i], x[j]);
break;
}
}
if(flag == 0) printf("%d-->-1\n", x[i]);
}
if(t != 0)
cout<<endl;
memset(x, 0, sizeof(x));
}
}
return 0;
}
利用栈:
#include <iostream>
#include <algorithm>
#include <stack>
#include <stdio.h>
using namespace std;
struct node
{
int data;//当前数值
int Id;//标记当前数值Id所在,若找到其后的较大值,更新其所在Id数值
int Next_Max_Data;//下一较大值
};
node _array[100010];
int main()
{
int n, t;
stack<node>S;
scanf("%d", &t);
for(int ii = 1; ii <= t; ii++)
{
while(!S.empty())
{
S.pop();
}//栈清空
scanf("%d", &n);
for(int j = 1; j <= n; j++)
{
scanf("%d", &_array[j].data);
_array[j].Id = j;
_array[j].Next_Max_Data = -1;
if(S.empty())
{
S.push(_array[j]);
}
else
{
while(!S.empty())//不断取其栈顶元素,更新其栈顶元素下一较大值
{
node tmp = S.top();//取栈顶元素
int k = tmp.Id;//获取栈顶元素Id
if(tmp.data < _array[j].data)
{
_array[k].Next_Max_Data = _array[j].data;//更新栈顶元素Id所在的较大值
S.pop();//将较大值出栈
}
else break;
}
S.push(_array[j]);//将当前数值入栈,便于查找当前值下一较大值
}
}
for(int i = 1; i <= n; i++)
{
cout << _array[i].data << "-->" << _array[i].Next_Max_Data << endl;
}
if(ii != t)
{
cout << endl;
}
}
return 0;
}