算法导论 思考题 14-1

本文介绍了一种利用平衡二叉树存储区间端点的方法,通过为每个端点分配特定值来快速查找区间重叠部分的最大值。文章详细解释了算法原理,并提供了具体的红黑树实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一下解析:

Keep a balanced binary tree of the endpoints. That is, to insert an interval,we insert its endpoints separately. With each left endpoint e, associate a value p[e] = +1 (increasing the overlap by 1). With each right endpoint e associate a value p[e] = −1 (decreasing the overlap by 1). When multiple endpoints have the same value, insert all the left endpoints with that value before inserting any  of the right endpoints with that value.Here’s some intuition. Let e 1 , e 2 , . . . , e n be the sorted sequence of endpoints  corresponding to our intervals. Let s(i, j ) denote the sum p[e i ] + p[e i+1 ] + · · · + p[e j ] for 1 ≤ i ≤ j ≤ n. We wish to find an i maximizing s(1, i). Each node x stores three new attributes. Suppose that the subtree rooted at x includes the endpoints e l[x] , . . . , e r[x] . We store v[x] = s(l[x], r[x]), the sum of the values of all nodes in x’s subtree. We also store m[x], the maximum value14-16 Solutions for Chapter 14: Augmenting Data Structures obtained by the expression s(l[x], i) for any i in {l[x], l[x] + 1, . . . , r[x]}. Finally, we store o[x] as the value of i for which m[x] achieves its maximum. we define v[nil[T ]] = m[nil[T ]] = 0.We can compute these  attributes in a bottom-up fashion to satisfy the requirements of Theorem 14.1:
v[x] = v[left[x]] + p[x] + v[right[x]].

m[x] =max(m[left[x]](max is in x’s left subtree) , v[left[x]] + p[x](max is at x) , v[left[x]] + p[x] + m[right[x]] (max is in x’s right subtree) .

The computation of v[x] is straightforward. The computation of m[x] bears further explanation. Recall that it is the maximum value of the sum of the p values for the nodes in x’s subtree, starting at l[x], which is the leftmost endpoint in x’s subtree and ending at any node i in x’s subtree. The value of i that maximizes this sum is either a node in x’s left subtree, x itself, or a node in x’s right subtree. If i is a node in x’s left subtree, then m[left[x]]
represents a sum starting at l[x], and hence m[x] = m[left[x]]. If i is x itself, then m[x] represents the sum of all p values in x’s left subtree plus p[x], so that m[x] = v[left[x]] + p[x]. Finally, if i is in x’s right subtree, then m[x] represents the sum of all p values in x’s left subtree, plus p[x], plus the sum of some set of p values in x’s right subtree. Moreover, the values taken from x’s right subtree must start from the leftmost endpoint in the right subtree. To maximize this sum, we need to maximize the sum from the right subtree, and that value is precisely m[right[x]]. Hence, in this case, m[x] = v[left[x]] + p[x] + m[right[x]]. Once we understand how to compute m[x], it is straightforward to compute o[x] from the information in x and its two children. Thus, we can implement the operations as follows:
I NTERVAL -I NSERT : insert two nodes, one for each endpoint of the interval.
I NTERVAL -D ELETE : delete the two nodes representing the interval end-points.

F IND -POM: return the interval whose endpoint is represented by o[root[T ]].Because of how we have deÞned the new attributes, Theorem 14.1 says that  each operation runs in O(lg n) time. In fact, F IND -POM takes only O(1) time.

看懂了没?没看懂多看几遍,再百度一下,你就知道。

根据答案用红黑树实现代码,实现的时候要当心,当出现key相等的左端点和右端点时,左端点总是要当做小于右端点插入,在insert时需要特别判断,代码中有关于这个的注释。看代码。

#include <stdio.h>      
#include <stdlib.h>      
#define RED 1      
#define BLACK 0      
      
typedef struct RBTreeNode      
{      
    int key;      
    int color;  
    int pp;//左端点1,右端点-1  
    int v;//子树所有端点P值之和  
    int m;//当前节点S(1,i)最大值  
    int o;//最大值对应的节点key  
    RBTreeNode *p;      
    RBTreeNode *left;      
    RBTreeNode *right;      
}RBT,*pRBT;      
      
pRBT nil=(pRBT)malloc(sizeof(RBT));      
int bh=0;    
    
void initNil()      
{      
    nil->key=-1;      
    nil->color=BLACK;      
    nil->p=NULL;      
    nil->left=NULL;      
    nil->right=NULL;  
    nil->pp=0;  
    nil->m=0;  
    nil->o=-1;  
    nil->v=0;  
}  
  
int max(int a,int b,int c)  
{  
    if(a>=b && a>=c)  
        return a;  
    else if(b>=c)  
        return b;  
    else  
        return c;  
}  
  
void updateVOM(pRBT z)  
{  
    z->v=z->left->v+z->pp+z->right->v;  
    z->m=max(z->left->m,z->left->v+z->pp,z->left->v+z->pp+z->right->m);  
    if(z->m==z->left->m)  
        z->o=z->left->o;  
    else if(z->m==z->left->v+z->pp)  
        z->o=z->key;  
    else  
        z->o=z->right->o;  
}  
      
void leftRotate(pRBT *root,pRBT x)      
{      
    //左旋要有右子树      
    if(x->right==nil)      
        return;      
    pRBT y=x->right;      
    x->right=y->left;      
    if(y->left != nil)      
        y->left->p=x;      
    y->p=x->p;      
    if(x->p==nil)      
    {      
        (*root)=y;      
    }      
    else if(x == x->p->left)      
    {      
        x->p->left=y;      
    }      
    else      
    {      
        x->p->right=y;      
    }      
    y->left=x;      
    x->p=y;     
    updateVOM(x);  
    updateVOM(y);  
}      
      
void rightRotate(pRBT *root,pRBT y)      
{      
    //右旋要有左子树      
    if(y->left==nil)      
        return;      
    pRBT x=y->left;      
    y->left=x->right;      
    x->p=y->p;      
    if(x->right != nil)    
        x->right->p=y;    
    if(y->p==nil)      
    {      
        (*root)=x;      
    }      
    else if(y==y->p->left)      
    {      
        y->p->left=x;      
    }      
    else      
    {      
        y->p->right=x;      
    }      
    x->right=y;      
    y->p=x;  
    updateVOM(y);  
    updateVOM(x);  
}      
      
void rbInsertFixup(pRBT *root,pRBT z)      
{      
    while(z->p->color==RED)      
    {      
        if(z->p==z->p->p->left)      
        {      
            pRBT y=z->p->p->right;      
            if(y->color==RED)      
            {      
                z->p->color=BLACK;      
                y->color=BLACK;      
                z->p->p->color=RED;      
                z=z->p->p;      
            }      
            else       
            {      
                if(z==z->p->right)      
                {      
                    z=z->p;      
                    leftRotate(root,z);      
                }      
                z->p->color=BLACK;      
                z->p->p->color=RED;      
                rightRotate(root,z->p->p);      
            }      
        }      
        else      
        {      
            pRBT y=z->p->p->left;      
            if(y->color==RED)      
            {      
                z->p->color=BLACK;      
                y->color=BLACK;      
                z->p->p->color=RED;      
                z=z->p->p;      
            }      
            else       
            {      
                if(z==z->p->left)      
                {      
                    z=z->p;      
                    rightRotate(root,z);      
                }      
                z->p->color=BLACK;      
                z->p->p->color=RED;      
                leftRotate(root,z->p->p);      
            }      
        }      
    }      
    if((*root)==nil || (*root)->color==RED)    
        bh++;    
    (*root)->color=BLACK;    
        
}      
      
void rbInsert(pRBT *root,int key,char c)      
{      
    pRBT z=(pRBT)malloc(sizeof(RBT));      
    z->key=key;    
	if(c=='L')  
        z->pp=1;  
    else  
        z->pp=-1;
    pRBT x=(*root);      
    pRBT y=nil;      
    while(x != nil)      
    {      
        y=x;  
		// When multiple endpoints have the same value, 
		//insert all the left endpoints with that value before inserting any  of the right endpoints with that value
		if(z->key<x->key || (z->key==x->key && z->pp>x->pp))      
        {      
            x=x->left;      
        }      
        else      
        {      
            x=x->right;      
        }      
    }      
    z->p=y;      
    if(y==nil)      
    {      
        (*root)=z;      
    }      
	// When multiple endpoints have the same value, 
	//insert all the left endpoints with that value before inserting any  of the right endpoints with that value
    else if(z->key<y->key || (z->key==y->key && z->pp>y->pp))      
    {      
        y->left=z;      
    }      
    else      
    {      
        y->right=z;      
    }      
    z->left=nil;      
    z->right=nil;      
    z->color=RED;  
      
    pRBT u=z;  
    while(u != nil)  
    {  
        updateVOM(u);  
        u=u->p;  
    }  
    rbInsertFixup(root,z);      
}    
    
void rbTransplant(pRBT *root,pRBT u,pRBT v)    
{    
    if(u->p==nil)    
        (*root)=v;    
    else if(u==u->p->left)    
        u->p->left=v;    
    else    
        u->p->right=v;    
    v->p=u->p;    
}    
    
pRBT treeMinimum(pRBT root)    
{    
    if(root==nil)    
        return root;    
    pRBT x=root;    
    while(x->left!=nil)    
    {    
        x=x->left;    
    }    
    return x;    
}    
    
void rbDeleteFixup(pRBT *root,pRBT x)    
{    
    while(x != *root && x->color==BLACK)    
    {    
        if(x==x->p->left)    
        {    
            pRBT w=x->p->right;    
            if(w->color==RED)    
            {    
                w->color=BLACK;    
                x->p->color=RED;    
                leftRotate(root,x->p);    
                w=x->p->right;    
            }    
            if(w->left->color==BLACK && w->right->color==BLACK)    
            {    
                w->color=RED;    
                x=x->p;    
                if(x==*root)    
                    bh--;    
            }    
            else    
            {    
                if(w->right->color == BLACK)    
                {    
                    w->left->color=BLACK;    
                    w->color=RED;    
                    rightRotate(root,w);    
                    w=x->p->right;    
                }    
                w->color=x->p->color;    
                x->p->color=BLACK;    
                w->right->color=BLACK;    
                leftRotate(root,x->p);    
                x=(*root);    
            }    
        }    
        else    
        {    
            pRBT w=x->p->left;    
            if(w->color==RED)    
            {    
                w->color=BLACK;    
                x->p->color=RED;    
                rightRotate(root,x->p);    
                w=x->p->left;    
            }    
            if(w->left->color==BLACK && w->right->color==BLACK)    
            {    
                w->color=RED;    
                x=x->p;    
            }    
            else    
            {    
                if(w->left->color == BLACK)    
                {    
                    w->right->color=BLACK;    
                    w->color=RED;    
                    leftRotate(root,w);    
                    w=x->p->left;    
                }    
                w->color=x->p->color;    
                x->p->color=BLACK;    
                w->left->color=BLACK;    
                rightRotate(root,x->p);    
                x=(*root);    
            }    
        }    
    }    
    pRBT u=x;  
    while(u != nil)  
    {  
        updateVOM(u);  
        u=u->p;  
    }  
    x->color=BLACK;    
}    
    
void rbDelete(pRBT *root,pRBT z)    
{    
    pRBT y=z,x;    
    int yOrigColor=y->color;    
    if(z->left==nil)    
    {    
        x=z->right;    
        rbTransplant(root,z,x);    
    }    
    else if(z->right==nil)    
    {    
        x=z->left;    
        rbTransplant(root,z,x);    
    }    
    else    
    {    
        y=treeMinimum(z->right);    
        yOrigColor=y->color;    
        x=y->right;    
        if(y->p==z)    
        {    
            x->p=y;    
        }    
        else    
        {    
            rbTransplant(root,y,x);    
            y->right=z->right;    
            y->right->p=y;    
        }    
        rbTransplant(root,z,y);    
        y->left=z->left;    
        y->left->p=y;    
        y->color=z->color;    
        if(yOrigColor==BLACK)    
            rbDeleteFixup(root,x);    
    }    
}    
    
void preTrav(pRBT root,char c)    
{    
    if(root==nil)    
        return;    
    else    
    {    
		printf("key=%d,o=%d,m=%d,pp=%d,v=%d ",root->key,root->o,root->m,root->pp,root->v);    
        if(root->color==BLACK)    
            printf("%s ","黑");    
        else    
            printf("%s ","红");    
        printf("%c ",c);    
        printf("\n");  
        preTrav(root->left,'L');    
        preTrav(root->right,'R');    
    }    
}    
    
pRBT treeSearch(pRBT root,int key)    
{    
    pRBT x=root;    
    while(x!=nil && x->key!=key)    
    {    
        if(key<x->key)    
            x=x->left;    
        else    
            x=x->right;    
    }    
    return x;    
}    
    
void main()    
{    
    initNil();    
    pRBT root=nil;    
    rbInsert(&root,1,'L');    
    rbInsert(&root,2,'R');    
    rbInsert(&root,3,'L');    
    rbInsert(&root,5,'R');    
    rbInsert(&root,4,'L');    
    rbInsert(&root,6,'R');    
    rbInsert(&root,5,'L');    
    rbInsert(&root,7,'R');    
    rbInsert(&root,8,'L');    
    rbInsert(&root,9,'R');    
    preTrav(root,'M');    
    printf("\n");    
    printf("最大值:%d,最大次数:%d\n",root->o,root->m);    
    getchar();    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值