版本比较
【模板】平衡树
正文
增加 21 行删除 21 行
34 行未改动353637383939404142434344454647474849505151525354552 行未改动5859606162626364656614 行未改动8182838485858687888990919293949595969798989910010110234 行未改动13713813914014114114214314414514614614714814915022 行未改动17317417517617717717817918018118218318318418518518618718818912 行未改动20220320420520620620720820921021121121221321421521521621721821977 行未改动29729829930030130130230330430554 行未改动36036136236336436436536636736836937037037137237337438 行未改动4134144154164174174184194204214 行未改动42642742842943043043143234 行未改动 int y = tr[x].fa; // x的父节点 int z = tr[y].fa; // x的祖父节点 int k1 = (x == tr[y].ch[1]); // x是y的右孩子为1,左孩子为0 int k2 = (y == tr[z].ch[1]); // y是z的右孩子为1,左孩子为0
// 1. 将x的对应孩子接到y上 tr[y].ch[k1] = tr[x].ch[k1 ^ 1]; if (tr[x].ch[k1 ^ 1]) tr[tr[x].ch[k1 ^ 1]].fa = y;
// 2. 将y接到x上 tr[x].ch[k1 ^ 1] = y; tr[y].fa = x;
// 3. 更新祖父节点连接 tr[x].fa = z; if (z) tr[z].ch[k2] = x; // 如果祖父节点存在,更新其孩子指针
// 4. 更新节点大小(自底向上) update(y); update(x);}2 行未改动void splay(int x, int goal) { while (tr[x].fa != goal) { // 持续旋转直到x的父节点是goal int y = tr[x].fa; // 父节点 int z = tr[y].fa; // 祖父节点
if (z != goal) { // 如果祖父节点不是goal,需要双旋 // 判断是之字形还是一字形 if ((tr[y].ch[0] == x) ^ (tr[z].ch[0] == y)) rotate(x); // 之字形:先转x14 行未改动 tr[root].v = x; tr[root].cnt = 1; return; }
int now = root, fa = 0; while (true) { if (x == tr[now].v) { // 值已存在 tr[now].cnt++; // 增加计数 update(now); // 更新当前节点 if (fa) update(fa); // 更新父节点 splay(now, 0); // 伸展到根 break; }
fa = now; // 记录父节点 now = tr[now].ch[x > tr[now].v]; // 根据值大小选择方向
if (!now) { // 到达叶子位置,创建新节点 cur++; tr[cur].size = 1; tr[cur].v = x;34 行未改动 now = tr[now].ch[0]; // 进入左子树 } else { // 计算左子树大小 + 当前节点计数 int temp = (tr[now].ch[0] ? tr[tr[now].ch[0]].size : 0) + tr[now].cnt;
// 如果第x小在当前节点范围内 if (x <= temp) { return tr[now].v; // 返回当前节点值 }
// 否则进入右子树继续查找 x -= temp; now = tr[now].ch[1]; }22 行未改动
// 删除操作:从树中删除值xvoid del(int x) { int temp = find_rank(x); // 将值为x的节点伸展到根
// 情况1:有重复值,只减少计数 if (tr[root].cnt > 1) { tr[root].cnt--, tr[root].size--; return; }
int now = root;
// 情况2:叶子节点 if (!tr[now].ch[0] && !tr[now].ch[1]) { clear(now); root = 0;12 行未改动 clear(now); tr[root].fa = 0; return; }
// 情况5:左右子树都存在 int oldroot = root; // 找到前驱并伸展到根 int temp2 = find_rank(tr[pre()].v);
// 将原根的右子树接到新根上 tr[root].ch[1] = tr[oldroot].ch[1]; tr[tr[oldroot].ch[1]].fa = root;
// 清空原根节点 clear(oldroot); update(root); // 更新新根的大小}77 行未改动 } if(goal==0) root = x;}void insert(int x){ if(!root){//空树 if(!root){//空树 cur++; root = cur; tr[root].size = 1; tr[root].v = x;54 行未改动 }}int pre(){ int now = tr[root].ch[0]; while(tr[now].ch[1]&&now) while(tr[now].ch[1]&&now) now = tr[now].ch[1]; return now;}int nxt(){ int now = tr[root].ch[1]; while(tr[now].ch[0]&&now) while(tr[now].ch[0]&&now) now = tr[now].ch[0]; return now;}void del(int x){38 行未改动 if(opt==3){ insert(x); printf("%d\n",find_rank(x)); del(x); } } if(opt==4) printf("%d\n",find_kth(x)); if(opt==5){ insert(x); printf("%d\n",tr[pre()].v);4 行未改动 printf("%d\n",tr[nxt()].v); del(x); } }} }```# P3391 【模板】文艺平衡树