单调栈模板&数组模拟优化

链接: 模板题链接.

STL做法,简单易懂,但是太慢了,后面有优化

#include 

using namespace std;

const int N = 3e6 + 10;

int n, a[N], b[N];
stack<int> st;

signed main() {

    scanf("%d", &n);
    for(int i = 1; i <= n; i++) scanf("%d", &a[i]);

    for(int i = 1; i <= n; i++) {
        while(st.empty()) {
            st.push(i);
        }

        while(!st.empty() && a[i] > a[st.top()]) {
            b[st.top()] = i;
            st.pop();
        }

        st.push(i);
    }


    for(int i = 1; i <= n; i++) printf("%d ", b[i]);


    return 0;

}

数组模拟栈+快读快写

//-----模拟栈-----
int stk[N],tt;
 
//插入
skt[++t] = x

//弹出
tt--

//判断栈是否为空
tt > 0 ? not empty : empty

//栈顶 
sk[tt]

接下来上优化后的题目代码

#include 

using namespace std;
template <typename T> inline void read(T& t) {
    int f = 0, c = getchar();
    t = 0;
    while (!isdigit(c)) f |= c == '-', c = getchar();
    while (isdigit(c)) t = t * 10 + c - 48, c = getchar();
    if (f) t = -t;
}

template <typename T> void print(T x) {
    if (x < 0) x = -x, putchar('-');
    if (x > 9) print(x / 10);
    putchar(x % 10 + 48);
}

const int N = 3e6 + 10;
const int inf = 0x3f3f3f3f;

int stk[N], tt;
int n, a[N], b[N];

signed main() {
    read(n);

    for(int i  = 1; i <= n; i++) read(a[i]);

    stk[0] = inf;

    for(int i = 1; i <= n; i++) {

        while(tt == 0) {
            stk[++tt] = i;
        }

        while(tt != 0 && a[i] > a[stk[tt]]) {
            b[stk[tt]] = i;
            tt--;
        }

        stk[++tt] = i;
    }

    for(int i = 1; i <= n; i++) {
        print(b[i]);
        putchar(' ');
    }

    return 0;

}

单调栈模板&数组模拟优化_第1张图片

2.45s—>1.31s 数组的优化还是十分给力!!!

你可能感兴趣的:(#,数据结构,c++)