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
本题数据量大、限时要求高,须借助栈来完成。
Author
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
int next;
int pos;
};
struct node p[100860];
typedef struct node elemtype;
typedef int status;
#define MAXSIZE 100
#define OVERFLOW -2
#define another 50
//#define true 1
//#define false 0
typedef struct{
elemtype *base;
elemtype *top;
int stacksize;
}Sqstack;
status isEmpty(Sqstack &S){
if(S.top == S.base)
return true;
else
return false;
}
elemtype getTop(Sqstack &S){
return *(S.top-1);
}
void initStack(Sqstack &S){
S.base = new elemtype[MAXSIZE];
S.top = S.base;
S.stacksize = MAXSIZE;
}
void Push(Sqstack &S, elemtype e){
if(S.top-S.base >= S.stacksize){
S.base = (elemtype *)realloc(S.base,(another+S.stacksize)*sizeof(elemtype));
S.top = S.base + S.stacksize;
S.stacksize += another;
}
*S.top++ = e;
}
elemtype Pop(Sqstack &S, elemtype &e){
return e = *--S.top;
}
void LineEdit(Sqstack &S, int n)
{
for(int i = 0; i < n; i++)
{
scanf("%d", &p[i].data);
p[i].pos = i;
p[i].next = -1;
if(isEmpty(S))
{
Push(S, p[i]);
}
else
{
while(!isEmpty(S))
{
struct node a = getTop(S);
if(a.data < p[i].data)
{
p[a.pos].next = p[i].data;
Pop(S, a);
}
else break;
}
}
Push(S, p[i]);
}
for(int i = 0; i < n; i++){
printf("%d-->%d\n", p[i].data, p[i].next);
}
printf("\n");
}
int main(){
int t, n;
scanf("%d", &t);
while(t--)
{
Sqstack S;
initStack(S);
scanf("%d", &n);
LineEdit(S, n);
}
return 0;
}