数学建模问题求最大独立集
Problem statement:
问题陈述:
Given a tree, you have to find out the largest independent set. Independent elements are those that don’t have any common edges. Print the length of the largest independent set.
给定一棵树,您必须找出最大的独立集合。 独立元素是指没有共同优势的元素。 打印最大独立集的长度。
T Test case
T no. of input string will be given to you.
E.g.
2
Example
例
T=2
Input:
Explanation with example:
举例说明:
To find out the length of the independent set we have to consider every node in our consideration.
为了找出独立集的长度,我们必须考虑考虑中的每个节点。
A node with its grandchildren are in the set
带有孙子项的节点在集合中
The child nodes are in the set.
子节点在集合中。
Independent set of node(x) = max (1+independent set of its grandchildren,independent set of its children)
节点(x)的独立集合=max(1+个其子代的独立集合,其子代的独立集合)
Example:
例:
Problem Solution:
问题方案:
Recursive algorithm:
递归算法:
Function(Node):
if(node==NULL)
return 0
excluding_the_node=Function(node->left)+Function(node->right)
including_the_node=1
if(node->left)
including_the_node+=Function(node->left->left)+Function(node->left->right)
if(node->right)
including_the_node+=Function(node->right->left)+Function(node->right->right)
return max(including_the_node,excluding_the_node)
DP conversion:
DP转换:
Function(Node):
if(node==NULL)
return 0
if(vis[node])
return vis[node]
excluding_the_node=Function(node->left)+Function(node->right)
including_the_node=1
if(node->left)
including_the_node+=Function(node->left->left)+Function(node->left->right)
if(node->right)
including_the_node+=Function(node->right->left)+Function(node->right->right)
return vis[node]=max(including_the_node,excluding_the_node)
C++ Implementation:
C ++实现:
#include <bits/stdc++.h>
using namespace std;
struct tree {
int val, value;
tree* left;
tree* right;
};
struct tree* make_node(int x)
{
tree* t = new tree;
t->val = x;
t->value = 0;
t->left = t->right = NULL;
return t;
}
int set_count(tree* t)
{
if (t == NULL) {
return 0;
}
if (t->value) {
return t->value;
}
int excluding = set_count(t->left) + set_count(t->right);
int including = 1;
if (t->left)
including += set_count(t->left->left) + set_count(t->left->right);
if (t->right)
including += set_count(t->right->left) + set_count(t->right->right);
return max(excluding, including);
}
int main()
{
tree* t = NULL;
t = make_node(10);
t->left = make_node(20);
t->right = make_node(30);
t->left->left = make_node(40);
t->left->right = make_node(50);
t->right->right = make_node(60);
t->right->left = make_node(90);
t->left->right->left = make_node(70);
t->left->right->right = make_node(80);
cout << "Max set count : " << set_count(t) << endl;
return 0;
}
Output
输出量
Max set count : 6
翻译自: https://www.includehelp.com/icp/largest-independent-set-problem.aspx
数学建模问题求最大独立集