SDUT-3332&3333_数据结构实验之栈与队列五:下一较大值

时间:2023-03-09 23:21:32
SDUT-3332&3333_数据结构实验之栈与队列五:下一较大值

数据结构实验之栈与队列六:下一较大值

Time Limit: 150 ms Memory Limit: 8000 KiB

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

本题数据量大、限时要求高,须借助栈来完成。

由于3333是3332的升级版,所以直接放了3333的题解。

将数字与栈顶元素比较,如果栈顶元素小于该数字,则说明这个数字是栈顶元素的下一最大值。

直到栈顶元素大于该数字或者栈为空时,将该数字入栈。

#include <stdio.h>
#include <stdlib.h>
#include <string.h> typedef struct node
{
int data;
struct node *next;
}Node; typedef struct stack
{
Node *base,*top;
}Stack; struct num
{
int data,next;
}s[100050]; Node *newnode()//建立节点
{
Node *t;
t = (Node *)malloc(sizeof(Node));
t->next = NULL;
return t;
}; Stack *Newstack()//建立新栈
{
Stack *t;
t = (Stack *)malloc(sizeof(Stack));
t->top = newnode();
t->base = t->top;
return t;
} void push(Stack *t,int x)//入站
{
Node *p = newnode();
p->data = x;
p->next = t->top->next;
t->top->next = p;
t->base = p;
} int top(Stack *t)//询问栈顶元素
{
return t->top->next->data;
} void pop(Stack *t)//出栈
{
Node *p;
p = t->top->next;
t->top->next = t->top->next->next;
free(p);
} int empty(Stack *t)//询问栈是否为空
{
if(t->top->next==NULL)
return 1;
return 0;
} void del(Stack *t)//清空栈
{
while(!empty(t))
pop(t);
} int main()
{
int i,n,k;
Stack *t;
t = Newstack();
scanf("%d",&k);
while(k--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&s[i].data);
s[i].next = -1;
}
for(i=0;i<n;i++)
{
if(empty(t))
push(t,i);
else
{
while(!empty(t)&&s[i].data>s[top(t)].data)
{
s[top(t)].next = s[i].data;
pop(t);
}
push(t,i);
}
}
for(i=0;i<n;i++)
printf("%d-->%d\n",s[i].data,s[i].next);
del(t);
if(k!=0)
printf("\n");
}
return 0;
}

线性表

#include <stdio.h>
#include <stdlib.h>
#include <string.h> struct node
{
int data,next;
}s[100050]; typedef struct Static
{
int *top,*base;
}Static; Static newStatic()
{
Static t;
t.top = (int *)malloc(100050*sizeof(int));
t.base = t.top;
return t;
} int top(Static t)
{
return *(t.top-1);
} void pop(Static *t)
{
t->top--;
} void push(Static *t,int x)
{
*(t->top++) = x;
} int empty(Static t)
{
if(t.base==t.top)
return 1;
return 0;
} void clear(Static *t)
{
while(!empty(*t))
pop(t);
} int main()
{
Static k;
int n,i,t;
scanf("%d",&t);
k = newStatic();
while(t--)
{
if(!empty(k))
clear(&k);
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&s[i].data);
s[i].next = -1;
while(!empty(k)&&s[i].data>s[top(k)].data)
{
s[top(k)].next = s[i].data;
pop(&k);
}
push(&k,i);
}
for(i=0;i<n;i++)
printf("%d-->%d\n",s[i].data,s[i].next);
if(t!=0)
printf("\n");
}
return 0;
}