定义
左偏树是堆的一种,和二叉堆不同:左偏树不用是完全二叉树,且可以快速合并。
x节点的距离定义为x儿子距离中小的+1(任何一个儿子为空的节点距离为0)。左偏树除了具有堆性质外,还具有左偏性质:除叶节点外,任何节点左儿子的距离不小于右儿子的距离。根据左偏性质我们知道左偏树中一个节点的距离就是右儿子距离+1(或没有右儿子),且左右子树都是左偏树。
实现
ps:和其他一些数据结构一样,对于每棵左偏树,用根节点代表就行了。
左偏树的核心就是合并,合并a和b的操作方法如下:
1.如果a或b有一个是空树,返回另一个。
2.如果a的优先级比b低,交换a,b。
3.递归处理,将b和a的右子树合并。
4.如果合并过后a的右儿子距离大于a的左儿子,交换a的左右儿子。
5.更新a的距离。
为什么是将b和a的右子树合并呢?不难发现合并过程中,是不停向一边递归处理的,则处理次数就是那一边的距离。而我们已经保证了左偏性质,当然是往右走,也就是和右子树合并(某些男左女右观念强烈的强迫症患者可以选择“右偏树”,这样你就可以往左走了:P)。
最恶劣的情况下,合并的复杂度是log2(n)的,这种情况出现在左偏树是一棵完全二叉树的时候,因为只有这种情况下,全部节点左右距离是相等的,其他情况下,总有节点的右儿子距离<左儿子(这样的话合并复杂度就比log2(n)小了)。
如何加入节点?和二叉堆完全不同,但又特别简单:你只需要把这个节点当成一棵左偏树然后合并就行了。
模板
以洛谷P3377为例。
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=100000;
int n,te,father[maxn+5];
bool vis[maxn+5];
//==================================================
struct Node
{
Node *son[2];
int x,id,dis;
bool operator < (const Node &a) const {return x<a.x||x==a.x&&id<a.id;}
};
typedef Node* P_node;
Node tem[maxn+5];
P_node null=tem,len=null,ro[maxn+5];
P_node newNode(int k,int id)
{
len++;len->son[0]=len->son[1]=null;
len->dis=0;len->x=k;len->id=id;
return len;
}
P_node Join(P_node a,P_node b) //合并a和b
{
if (a==null) return b;if (b==null) return a;
if ((*b)<(*a)) swap(a,b); //如果b优先级更高,交换
a->son[1]=Join(a->son[1],b); //合并a的右儿子和b
if (a->son[0]->dis<a->son[1]->dis) swap(a->son[0],a->son[1]); //维护左偏性质
if (a->son[1]==null) a->dis=0; else a->dis=a->son[1]->dis+1; //更新距离
return a;
}
P_node del(P_node ro) {return Join(ro->son[0],ro->son[1]);} //删除堆顶
//==================================================
bool Eoln(char ch) {return ch==10||ch==13||ch==EOF;}
int readi(int &x) //读入优化
{
int tot=0,f=1;char ch=getchar(),lst=' ';
while ('9'<ch||ch<'0') {if (ch==EOF) return EOF;lst=ch;ch=getchar();}
if (lst=='-') f=-f;
while ('0'<=ch&&ch<='9') tot=tot*10+ch-48,ch=getchar();
x=tot*f;
return Eoln(ch);
}
int getfa(int x) //并查集
{
if (father[x]==x) return x;
return father[x]=getfa(father[x]);
}
int main()
{
freopen("Leftist_Tree.in","r",stdin);
freopen("Leftist_Tree.out","w",stdout);
readi(n);readi(te);
for (int i=1;i<=n;i++)
{
int x;readi(x);father[i]=i;
ro[i]=newNode(x,i);
}
while (te--)
{
int td,x,y;readi(td);
if (td==1)
{
readi(x);readi(y);if (vis[x]||vis[y]) continue;
int fx=getfa(x),fy=getfa(y);if (fx==fy) continue;
P_node now=Join(ro[fx],ro[fy]);
ro[now->id]=now;father[fx]=father[fy]=now->id;
} else
{
readi(x);if (vis[x]) {printf("-1\n");continue;}
int fx=getfa(x);printf("%d\n",ro[fx]->x);
P_node now=del(ro[fx]);vis[fx]=true;
if (now==null) continue;
ro[now->id]=now;father[fx]=now->id;father[now->id]=now->id;
}
}
return 0;
}