Cartesian Tree

Cartesian Tree

struct CartesianTree
{
    static const int __=50005;

    struct node
    {
        int val,key,id,fa,lson,rson;

        void clear(){fa=lson=rson=0;}

        bool operator<(const node &b)const
        {
            return val<b.val;
        }
    }t[__];

    CartesianTree() {clear();}

    node& operator[](int x){return t[x];}

    int root;
    stack<int>S;

    void build(int n)
    {
        sort(t+1,t+n+1);
        for(int i=1;i<=n;++i)
        {
            while(!S.empty() && t[S.top()].key>t[i].key)
                S.pop();
            t[i].clear();
            if(S.empty())
            {
                t[root].fa=i;
                t[i].lson=root;
                root=i,S.push(i);
                continue;
            }
            t[i].lson=t[S.top()].rson;
            t[t[S.top()].rson].fa=i;
            t[S.top()].rson=i;
            t[i].fa=S.top();
            S.push(i);
        }
    }

    void clear(){for(root=0;!S.empty();S.pop());}
}ct;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容