Think:
1知识点:单调栈
2题意:输入一个序列(1<=n<=100000),输出序列中当前数以及序列中大于这个数的第一个数,
3解题思路:数据量较大,暴力会超时,可通过维护一个单调栈
第一步:若栈为空或者栈顶大于等于当前元素,当前元素进栈
第二步:若栈不为空且栈顶小于当前元素,栈顶出栈
第三步:重复第一步和第二步,直至所有元素处理完成
4反思:
(1):数组开小了导致超时错误-why不是数组越界呢?
以下为Accepted代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int max_size = 100414;
struct Node{
int x, id;
};
class stack{
private:
int size;
Node sta[max_size];
public:
stack(){size = 0;}
void push(Node x);
Node top();
void pop();
bool empty();
};
void stack::push(Node x){
sta[size++] = x;
}
Node stack::top(){
return sta[size-1];
}
void stack::pop(){
size--;
}
bool stack::empty(){
return size == 0;
}
int rec[max_size];
int book[max_size];
int main(){
int T, n, i;
Node t1, t2;
scanf("%d", &T);
while(T--){
stack s1;
scanf("%d", &n);
for(i = 1; i <= n; i++){
scanf("%d", &rec[i]);
t1.x = rec[i], t1.id = i;
while(!s1.empty()){
t2 = s1.top();
if(t2.x < t1.x){
s1.pop();
book[t2.id] = t1.x;
}
else break;
}
s1.push(t1);
}
while(!s1.empty()){
t2 = s1.top();
s1.pop();
book[t2.id] = -1;
}
for(i = 1; i <= n; i++){
printf("%d-->%d\n", rec[i], book[i]);
}
if(T) printf("\n");
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 88ms
Take Memory: 1752KB
Submit time: 2017-10-04 10:37:33
****************************************************/