跳到正文

个人记录

题解 P3377 【【模板】左偏树(可并堆)】

Segment_Tree约 3 分钟
原文
文章信息与版本

文章信息

发布
2018年1月4日
收录
2026年3月31日
更新
2026年11月17日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

Powered by 2e8_konjak

裸模板(逃

左偏树(Leftist Tree),可并堆的实现方法之一,满足堆的性质,同时满足其独特性质:每个节点的左子节点的距离不小于右子节点的距离。

附上绝世好文:左偏树教程

最后是代码:(24ms,3.32Kb,洛谷第一,欢迎超越)

C++
#include<cstdio>
#define N 100001
inline char nc()
{
    static char buf[1<<14],*p1=buf,*p2=buf;
    return (p1==p2)&&(p2=(p1=buf)+fread(buf,1,1<<14,stdin),p1==p2)?EOF:*p1++;
}//ps:字符读入优化很重要
int inline read()
{
    int x=0,f=1;char ch=nc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=nc();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=nc();}
    return x*f;
}
inline void swap(int &x,int &y){int t=x;x=y,y=t;}
int ch[N][2],val[N],dis[N],f[N],n,m;
int merge(int x,int y)
{
    if(x==0||y==0) return x+y;
    if(val[x]>val[y]||(val[x]==val[y]&&x>y)) swap(x,y);
    ch[x][1]=merge(ch[x][1],y);
    f[ch[x][1]]=x;
    if(dis[ch[x][0]]<dis[ch[x][1]]) swap(ch[x][0],ch[x][1]);
    dis[x]=dis[ch[x][1]]+1;
    return x;
}
inline int getf(int x)
{
    while(f[x]) x=f[x];
    return x;
}
void pop(int x)
{
    val[x]=-1;
    f[ch[x][0]]=f[ch[x][1]]=0;
    merge(ch[x][0],ch[x][1]);
}
int main()
{
    n=read(),m=read();
    dis[0]=-1;
    for(register int i=1;i<=n;i++) val[i]=read();
    for(register int i=1;i<=m;i++)
    {
        int com=read();
        if(com==1)
        {
            int x=read(),y=read();
            if(val[x]==-1||val[y]==-1) continue;
            if(x==y) continue;
            int fx=getf(x),fy=getf(y);
            merge(fx,fy);
        }
        else
        {
            int x=read();
            if(val[x]==-1) puts("-1");
            else
            {
                int y=getf(x);
                printf("%d\n",val[y]);
                pop(y);
            }
        }
    }
    return 0;
}
原文
抓取于
  1. l455435655

    404

  2. _October_

    附上绝世好文:左偏树教程404

  3. momentous

    膜拜大佬,蒟蒻我今天才知道有字符读入优化,感谢大佬不吝赐教

  4. 风浔凌

    404 not found

  5. xsun2001

    404妙啊

  6. Mr_Wolfram

    附上绝世好文:https://blog.csdn.net/qq_25978793/article/details/47732581 大约是洛谷换 Markdown 的锅

  7. Mingoal

    附上绝世好文:左偏树教程404

  8. misinclair

    附上绝世好文:左偏树教程404

  9. Mudrobøt

    404是什么鬼

  10. wky32768

    附上绝世好文:左偏树教程404