Independent Set 独立集问题

和独立集相关的一些图论的概念如下:

  • Independent Set 独立集问题
  • Bipartite Graph 二分图
  • Dominant Set 主导集
  • Cycle Graph循环图

问题:给你一个二叉树,求出该二叉树的最大独立集。

思路:二叉树问题可以用递归的办法来解决,这个也不例外。更好的是,这个问题还可以用动态规划的方法来解决。

设二叉树的根节点是root,那么,此二叉树的最大独立集要么包含root,要么不包含root。所以,最大独立集的大小 LISS (root) == max( is_LISS(root), not_LISS(root) ).

使用递归的方法,代码如下:

#include <iostream>
using namespace std;

struct Node{
        int value;
        int is_LISS; // used in the dynamic programming version
                     // the size of LIS when this is a member of the LIS
        int not_LISS; // used in the dynamic programming version
                     // the size of LIS when this is not a member of the LIS
        Node* lchild;
        Node* rchild;
        Node(int val, int is_, int not_, Node* lch, Node* rch):
                value(val), is_LISS(is_), not_LISS(not_),
                lchild(lch), rchild(rch) {}     
};

int is_LISS(Node* root); // return the size of LIS when root is a member of the LIS
int not_LISS(Node* root); // return the size of LIS when root is not a member of the LIS

int is_LISS(Node* root)
{
        if(root==NULL)
                return 0;
        else
                return 1 + not_LISS(root->lchild) + not_LISS(root->rchild);
}

int not_LISS(Node* root)
{
        if(root==NULL)
                return 0;
        else
                return max(is_LISS(root->lchild), not_LISS(root->lchild)) +
                max(is_LISS(root->rchild), not_LISS(root->rchild));
}

// return the size of LIS of the tree rooted at root
int LISS(Node* root)
{
        return max(is_LISS(root), not_LISS(root));
}

int main(int argc, char** argv)
{
        Node* n70 = new Node(70,-1,-1,NULL,NULL);
        Node* n80 = new Node(80,-1,-1,NULL,NULL);
        Node* n50 = new Node(50,-1,-1,n70,n80);
        Node* n40 = new Node(40,-1,-1,NULL,NULL);
        Node* n20 = new Node(20,-1,-1,n40,n50);
        Node* n60 = new Node(60,-1,-1,NULL,NULL);
        Node* n30 = new Node(30,-1,-1,NULL,n60);
        Node* n10 = new Node(10,-1,-1,n20,n30);

        cout<< LISS(n10) <<endl;
}

上面的程序构造了一棵如下图所示的二叉树,求出的LISS是5. 只要把is_LISS函数和not_LISS函数改一下,在把每次得到的函数返回值保存在每个节点的is_LISS和not_LISS成员中,这样,就可以免去每次递归调用,而是直接检查is_LISS和not_LISS是否已经求得(如果是-1,说明还没求得)。这样就可用得到动态规划版的最大对立集问题求解。


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值