Tree array maintains the maximum value of the interval

Title description
Give you a 1->n arrangement and a stack. The stacking order is given.
You need to sort the array from largest to smallest without disturbing the stacking sequence.
When it is not possible to sort completely, please output the lexicographic order. The largest popping sequence
Input description:
one number in the
first line n number in the second line, indicating the order of stacking, separated by spaces, and no spaces at the end.
Output description:
output a line of n numbers to represent the answer, separated by spaces , No space at the end
Example 1
input
copy
5
2 1 5 3 4
output
copy
5 4 3 1 2
Description
2 push; 1 push; 5 push; 5 pop; 3 push; 4 push; 4 pop; 3 pops; 1 pops; 2 pops

The simple idea is to find the maximum value of the interval, output it directly, and push the rest into the stack.

#include <stdio.h>
#include <iostream>
using namespace std;
const int maxn = 1e6 + 5;
int n, cnt = 0;
int a[maxn], c[maxn * 4], sta[maxn]; //栈和树状数组以及栈
int lowbit(int x){
    
    return x & (-x);}

//获得某个区间的最大值
int query(int l, int r){
    
    
    int ans=a[r];
    while(l!=r)
    {
    
    
        for(--r;r>=l+lowbit(r);r-=lowbit(r))
        {
    
    
            ans=max(ans,c[r]);
        }
        ans=max(ans,a[r]);
    }
    return ans;
}

//将x位置修改为p
void update(int x, int p){
    
    
    while(x <= n){
    
    
        c[x] = a[x];
        for(int i = 1; i < lowbit(x); i<<=1){
    
    
            c[x] = max(h[x], c[x - i]);
        }
        x += lowbit(x);
    }
}

void test(){
    
    
    n = 9;
    int t[] = {
    
    0,1,3,4,8,5,6,9,7,2};
    for(int i = 1; i <= 9; i++){
    
    
        update(i, t[i]);
    }
    printf("%d %d %d",query(1, 9), query(5, 5), query(6, 9));

}
int main(){
    
    
    scanf("%d", &n);
    for(int i = 1; i <= n; i++){
    
    
        int x;
        scanf("%d", &x);
        update(i, x);
    }
    int maxv = n;
    for(int i = 1; i <= n; i++){
    
    
        if(a[i] == maxv){
    
               //等于最大值就直接输出
            if(i != n - 1)
                printf("%d ", maxv);
            else printf("%d\n", maxv);
            maxv = query(i, n);     //查询下个区间的最大值
        }else{
    
    
            sta[cnt++] = a[i];      //否则入栈;
        }
    }
    //出栈
    for(--cnt; cnt > 0;cnt--){
    
    
        printf("%d ", sta[cnt]);
    }
    printf("%d\n", sta[0]);
    return 0;
}

Guess you like

Origin blog.csdn.net/fuzekun/article/details/104502062